0.11.1: 旗舰版完善(资源权限等级/个人环境变量/收藏/企业报表/租户概览/ARM64发布/多渠道接入)

- 迁移 000035-000037(权限等级/环境变量/渠道)
- 新增 internal/channel 渠道抽象层(webhook/企微/钉钉/飞书)
- 全部功能端到端验证通过(25 包单测)
This commit is contained in:
2026-08-13 11:54:34 +08:00
parent c22669c31d
commit 4563979a15
25 changed files with 1664 additions and 7 deletions
+212
View File
@@ -0,0 +1,212 @@
package workbench
import (
"context"
"regexp"
"encoding/json"
"errors"
"net/http"
"strings"
"aigateway.local/core/internal/identity"
"aigateway.local/core/internal/platform/apiresponse"
"aigateway.local/core/internal/platform/cryptox"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// EnvVarService 管理门户用户个人环境变量(值加密存储)。
type EnvVarService struct {
pool *pgxpool.Pool
cipher cryptox.Cipher
}
func NewEnvVarService(pool *pgxpool.Pool, cipher cryptox.Cipher) *EnvVarService {
return &EnvVarService{pool: pool, cipher: cipher}
}
// List 返回用户环境变量(键列表,不含值)。
func (s *EnvVarService) List(ctx context.Context, userID string) ([]map[string]any, error) {
if s == nil || s.pool == nil {
return nil, errors.New("环境变量服务不可用")
}
rows, err := s.pool.Query(ctx, `SELECT key,octet_length(encrypted_value)>0,updated_at FROM gateway.user_env_vars WHERE portal_user_id=$1 ORDER BY key`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []map[string]any{}
for rows.Next() {
var key string
var hasValue bool
var updatedAt any
if err := rows.Scan(&key, &hasValue, &updatedAt); err != nil {
return nil, err
}
items = append(items, map[string]any{"key": key, "configured": hasValue, "updated_at": updatedAt})
}
return items, rows.Err()
}
// Upsert 设置一个环境变量;value 为空时删除。
func (s *EnvVarService) Upsert(ctx context.Context, userID, key, value string) error {
if s == nil || s.pool == nil || s.cipher == nil {
return errors.New("环境变量服务不可用")
}
key = strings.TrimSpace(key)
if key == "" || len(key) > 128 || !envKeyPattern.MatchString(key) {
return errors.New("变量名必须以字母开头,可含字母/数字/下划线,最长 128 字符")
}
if len(value) > 4096 {
return errors.New("变量值过长")
}
value = strings.TrimSpace(value)
if value == "" {
tag, err := s.pool.Exec(ctx, `DELETE FROM gateway.user_env_vars WHERE portal_user_id=$1 AND key=$2`, userID, key)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return errors.New("变量不存在")
}
return nil
}
encrypted, version, err := s.cipher.Encrypt([]byte(value))
if err != nil {
return err
}
_, err = s.pool.Exec(ctx, `INSERT INTO gateway.user_env_vars(portal_user_id,key,encrypted_value,value_kek_version) VALUES($1,$2,$3,$4)
ON CONFLICT(portal_user_id,key) DO UPDATE SET encrypted_value=$3,value_kek_version=$4,updated_at=clock_timestamp()`,
userID, key, encrypted, version)
return err
}
// Decrypt 解密单个变量(运行时合并用);不存在返回 ok=false。
func (s *EnvVarService) Decrypt(ctx context.Context, userID, key string) (string, bool, error) {
if s == nil || s.pool == nil || s.cipher == nil {
return "", false, nil
}
var encrypted []byte
var version int
err := s.pool.QueryRow(ctx, `SELECT encrypted_value,value_kek_version FROM gateway.user_env_vars WHERE portal_user_id=$1 AND key=$2`, userID, key).Scan(&encrypted, &version)
if errors.Is(err, pgx.ErrNoRows) {
return "", false, nil
}
if err != nil {
return "", false, err
}
plaintext, err := s.cipher.Decrypt(encrypted, version)
if err != nil {
return "", false, err
}
return string(plaintext), true, nil
}
// MergeVariables 把用户环境变量合并进请求变量(请求未提供的键)。
func (s *EnvVarService) MergeVariables(ctx context.Context, userID string, variables map[string]any) error {
if userID == "" || len(variables) >= 100 {
return nil
}
rows, err := s.pool.Query(ctx, `SELECT key,encrypted_value,value_kek_version FROM gateway.user_env_vars WHERE portal_user_id=$1 LIMIT 200`, userID)
if err != nil {
return err
}
defer rows.Close()
type pair struct{ key string; value []byte; version int }
pairs := []pair{}
for rows.Next() {
var p pair
if err := rows.Scan(&p.key, &p.value, &p.version); err != nil {
return err
}
pairs = append(pairs, p)
}
if err := rows.Err(); err != nil {
return err
}
for _, p := range pairs {
if _, exists := variables[p.key]; exists {
continue
}
plaintext, err := s.cipher.Decrypt(p.value, p.version)
if err != nil {
continue
}
variables[p.key] = string(plaintext)
}
return nil
}
var envKeyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,127}$`)
// EnvVarHTTPHandler 门户环境变量 CRUD。
type EnvVarHTTPHandler struct {
service *EnvVarService
identity *identity.Service
mux *http.ServeMux
}
func NewEnvVarHTTPHandler(service *EnvVarService, identityService *identity.Service) *EnvVarHTTPHandler {
h := &EnvVarHTTPHandler{service: service, identity: identityService, mux: http.NewServeMux()}
h.mux.HandleFunc("GET /api/v1/portal/env-vars", h.list)
h.mux.HandleFunc("PUT /api/v1/portal/env-vars/{key}", h.upsert)
h.mux.HandleFunc("DELETE /api/v1/portal/env-vars/{key}", h.delete)
return h
}
func (h *EnvVarHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.mux.ServeHTTP(w, r) }
func (h *EnvVarHTTPHandler) account(w http.ResponseWriter, r *http.Request) (identity.Account, bool) {
account, err := h.identity.Authenticate(r.Context(), identity.KindPortal, r.Header.Get("Authorization"))
if err != nil {
apiresponse.Error(w, http.StatusUnauthorized, "登录状态无效或已过期")
return identity.Account{}, false
}
return account, true
}
func (h *EnvVarHTTPHandler) list(w http.ResponseWriter, r *http.Request) {
a, ok := h.account(w, r)
if !ok {
return
}
items, err := h.service.List(r.Context(), a.ID)
if err != nil {
apiresponse.Error(w, http.StatusServiceUnavailable, "环境变量查询失败")
return
}
apiresponse.OK(w, items)
}
func (h *EnvVarHTTPHandler) upsert(w http.ResponseWriter, r *http.Request) {
a, ok := h.account(w, r)
if !ok {
return
}
var input struct {
Value string `json:"value"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
decoder.DisallowUnknownFields()
if decoder.Decode(&input) != nil {
apiresponse.Error(w, http.StatusBadRequest, "请求格式无效")
return
}
if err := h.service.Upsert(r.Context(), a.ID, r.PathValue("key"), input.Value); err != nil {
apiresponse.Error(w, http.StatusBadRequest, err.Error())
return
}
apiresponse.OK(w, map[string]bool{"saved": true})
}
func (h *EnvVarHTTPHandler) delete(w http.ResponseWriter, r *http.Request) {
a, ok := h.account(w, r)
if !ok {
return
}
if err := h.service.Upsert(r.Context(), a.ID, r.PathValue("key"), ""); err != nil {
apiresponse.Error(w, http.StatusBadRequest, err.Error())
return
}
apiresponse.OK(w, map[string]bool{"deleted": true})
}
+12 -2
View File
@@ -16,6 +16,7 @@ import (
// MarketItem is the lightweight unified catalog row for a published resource,
// regardless of which of the three resource tables it lives in.
type MarketItem struct {
PermissionLevel string `json:"permission_level,omitempty"`
Type string `json:"type"`
Code string `json:"code"`
Name string `json:"name"`
@@ -300,11 +301,20 @@ func (s *MarketplaceService) Detail(ctx context.Context, resourceType, code stri
// Install records a portal user's workspace binding to a published resource.
// It is the permission grant that lets a cross-department user invoke a
// resource that would otherwise be invisible to them.
func (s *MarketplaceService) Install(ctx context.Context, resourceType, code, portalUserID string) (bool, error) {
// Install 记录安装;permissionLevel 为 view/use/manage(默认 use)。
func (s *MarketplaceService) Install(ctx context.Context, resourceType, code, portalUserID, permissionLevel string) (bool, error) {
resourceID, err := s.publishedResourceID(ctx, resourceType, code)
if err != nil {
return false, err
}
switch permissionLevel {
case "", "view", "use", "manage":
default:
return false, errors.New("权限等级必须是 view/use/manage")
}
if permissionLevel == "" {
permissionLevel = "use"
}
id, err := newUUID()
if err != nil {
return false, err
@@ -314,7 +324,7 @@ func (s *MarketplaceService) Install(ctx context.Context, resourceType, code, po
return false, err
}
defer rollback(ctx, tx)
tag, err := tx.Exec(ctx, `INSERT INTO gateway.marketplace_installations(id,resource_type,resource_id,portal_user_id) VALUES($1,$2,$3,$4) ON CONFLICT(resource_type,resource_id,portal_user_id) DO NOTHING`, id, resourceType, resourceID, portalUserID)
tag, err := tx.Exec(ctx, `INSERT INTO gateway.marketplace_installations(id,resource_type,resource_id,portal_user_id,permission_level) VALUES($1,$2,$3,$4,$5) ON CONFLICT(resource_type,resource_id,portal_user_id) DO UPDATE SET permission_level=$5`, id, resourceType, resourceID, portalUserID, permissionLevel)
if err != nil {
return false, err
}
@@ -147,7 +147,7 @@ func TestMarketplaceLifecycle(t *testing.T) {
}
// Install/uninstall is idempotent and gated by published status.
created, err := market.Install(ctx, "skill", "mkt_skill", portalUserID)
created, err := market.Install(ctx, "skill", "mkt_skill", portalUserID, "use")
if err != nil || !created {
t.Fatalf("install created=%v err=%v", created, err)
}
@@ -155,7 +155,7 @@ func TestMarketplaceLifecycle(t *testing.T) {
if err != nil || !installed {
t.Fatalf("installed=%v err=%v", installed, err)
}
createdAgain, err := market.Install(ctx, "skill", "mkt_skill", portalUserID)
createdAgain, err := market.Install(ctx, "skill", "mkt_skill", portalUserID, "use")
if err != nil || createdAgain {
t.Fatalf("re-install should be a no-op: created=%v err=%v", createdAgain, err)
}
+5
View File
@@ -30,6 +30,7 @@ type RuntimeHTTPHandler struct {
logger *slog.Logger
mux *http.ServeMux
market MarketplaceDeps
envVars *EnvVarService
}
// MarketplaceDeps carries the resource-marketplace services into the runtime
@@ -72,6 +73,9 @@ func (h *RuntimeHTTPHandler) SetLogger(logger *slog.Logger) {
// conversations. When nil (the default) fact-checking is skipped entirely.
func (h *RuntimeHTTPHandler) SetFactCheckEngine(engine *factcheck.Engine) { h.factCheck = engine }
// SetEnvVarService 启用个人环境变量合并(应用/数字员工运行时变量补充)。
func (h *RuntimeHTTPHandler) SetEnvVarService(service *EnvVarService) { h.envVars = service }
// SetTraceStore enables metadata-only LLM Trace recording for application and
// digital-employee runs. Trace persistence is best effort and never changes
// the runtime response when the database is unavailable.
@@ -329,6 +333,7 @@ func (h *RuntimeHTTPHandler) runApplication(w http.ResponseWriter, r *http.Reque
runtimeError(w, 404, "应用不存在、未发布或不可见")
return
}
started := time.Now()
status := "error"
runError := ""