feat(models): let system admins edit builtin model config

Allow platform system administrators to update builtin model parameters
and credentials from the management UI while keeping secrets masked in API
responses. UI edits clear YAML ownership so startup reconciliation no
longer overwrites runtime overrides.
This commit is contained in:
wizardchen
2026-07-14 15:51:32 +08:00
committed by lyingbug
parent f409bd756b
commit e1572b71b9
20 changed files with 328 additions and 35 deletions
+24 -7
View File
@@ -227,7 +227,8 @@ func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) erro
logger.Info(ctx, "Start updating model")
logger.Infof(ctx, "Updating model ID: %s, name: %s", model.ID, model.Name)
// Check if the model is builtin - builtin models cannot be updated
// Built-in models are platform-wide. Tenant administrators may view them,
// but only a system administrator may change their shared configuration.
tenantID := types.MustTenantIDFromContext(ctx)
existingModel, err := s.repo.GetByID(ctx, tenantID, model.ID)
if err != nil {
@@ -237,8 +238,15 @@ func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) erro
return err
}
if existingModel != nil && existingModel.IsBuiltin {
logger.Warnf(ctx, "Attempted to update builtin model: %s", model.ID)
return errors.New("builtin models cannot be updated")
if !types.IsSystemAdminFromContext(ctx) {
logger.Warnf(ctx, "Non-system-admin attempted to update builtin model: %s", model.ID)
return apperrors.NewForbiddenError("only system administrators can update builtin models")
}
// A UI edit is an explicit runtime override. Clear YAML ownership so
// the startup reconciler does not silently replace the saved values.
model.TenantID = existingModel.TenantID
model.IsBuiltin = true
model.ManagedBy = ""
}
// Update model in repository
@@ -271,8 +279,9 @@ func (s *modelService) UpdateModelCredentials(
if existing == nil {
return nil, ErrModelNotFound
}
if existing.IsBuiltin {
return nil, errors.New("builtin models cannot have credentials modified")
if existing.IsBuiltin && !types.IsSystemAdminFromContext(ctx) {
return nil, apperrors.NewForbiddenError(
"only system administrators can modify builtin model credentials")
}
changed := false
@@ -287,6 +296,10 @@ func (s *modelService) UpdateModelCredentials(
if !changed {
return existing, nil
}
if existing.IsBuiltin {
// Credential changes are also runtime overrides of YAML-managed data.
existing.ManagedBy = ""
}
if err := s.repo.Update(ctx, existing); err != nil {
return nil, err
}
@@ -304,8 +317,9 @@ func (s *modelService) ClearModelCredential(ctx context.Context, id, field strin
if existing == nil {
return ErrModelNotFound
}
if existing.IsBuiltin {
return errors.New("builtin models cannot have credentials modified")
if existing.IsBuiltin && !types.IsSystemAdminFromContext(ctx) {
return apperrors.NewForbiddenError(
"only system administrators can modify builtin model credentials")
}
changed := false
@@ -326,6 +340,9 @@ func (s *modelService) ClearModelCredential(ctx context.Context, id, field strin
if !changed {
return nil
}
if existing.IsBuiltin {
existing.ManagedBy = ""
}
if err := s.repo.Update(ctx, existing); err != nil {
return err
}
@@ -0,0 +1,99 @@
package service
import (
"context"
"testing"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func builtinModelContext(systemAdmin bool) context.Context {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
return context.WithValue(ctx, types.SystemAdminContextKey, systemAdmin)
}
func TestUpdateBuiltinModel_RequiresSystemAdmin(t *testing.T) {
stored := &types.Model{
ID: "builtin-chat", TenantID: 10000, IsBuiltin: true,
ManagedBy: types.BuiltinModelManagedBy,
}
updated := false
svc := NewModelService(&stubModelRepoForDelete{
model: stored,
update: func(*types.Model) error {
updated = true
return nil
},
}, nil, nil, nil, nil, nil)
err := svc.UpdateModel(builtinModelContext(false), &types.Model{ID: stored.ID})
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrForbidden, appErr.Code)
assert.False(t, updated)
}
func TestUpdateBuiltinModel_SystemAdminCreatesRuntimeOverride(t *testing.T) {
stored := &types.Model{
ID: "builtin-chat", TenantID: 10000, IsBuiltin: true,
ManagedBy: types.BuiltinModelManagedBy,
}
var saved *types.Model
svc := NewModelService(&stubModelRepoForDelete{
model: stored,
update: func(model *types.Model) error {
copy := *model
saved = &copy
return nil
},
}, nil, nil, nil, nil, nil)
input := &types.Model{ID: stored.ID, Name: "edited"}
require.NoError(t, svc.UpdateModel(builtinModelContext(true), input))
require.NotNil(t, saved)
assert.Equal(t, uint64(10000), saved.TenantID)
assert.True(t, saved.IsBuiltin)
assert.Empty(t, saved.ManagedBy, "UI edit must stop later YAML reconciliation")
}
func TestUpdateBuiltinModelCredentials_SystemAdminOnly(t *testing.T) {
newKey := "sk-new"
t.Run("tenant admin denied", func(t *testing.T) {
stored := &types.Model{ID: "builtin-chat", TenantID: 10000, IsBuiltin: true}
svc := NewModelService(&stubModelRepoForDelete{model: stored}, nil, nil, nil, nil, nil)
_, err := svc.UpdateModelCredentials(builtinModelContext(false), stored.ID, &newKey, nil)
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrForbidden, appErr.Code)
})
t.Run("system admin saves runtime override", func(t *testing.T) {
stored := &types.Model{
ID: "builtin-chat", TenantID: 10000, IsBuiltin: true,
ManagedBy: types.BuiltinModelManagedBy,
}
var saved *types.Model
svc := NewModelService(&stubModelRepoForDelete{
model: stored,
update: func(model *types.Model) error {
copy := *model
saved = &copy
return nil
},
}, nil, nil, nil, nil, nil)
updated, err := svc.UpdateModelCredentials(
builtinModelContext(true), stored.ID, &newKey, nil,
)
require.NoError(t, err)
assert.Equal(t, newKey, updated.Parameters.APIKey)
require.NotNil(t, saved)
assert.Empty(t, saved.ManagedBy)
})
}
@@ -75,6 +75,7 @@ func (s *stubAgentRepoForModelDelete) CountByModelID(context.Context, uint64, st
type stubModelRepoForDelete struct {
model *types.Model
delete func(id string) error
update func(model *types.Model) error
}
func (s *stubModelRepoForDelete) Create(context.Context, *types.Model) error { return nil }
@@ -87,7 +88,12 @@ func (s *stubModelRepoForDelete) GetByID(_ context.Context, _ uint64, id string)
func (s *stubModelRepoForDelete) List(context.Context, uint64, types.ModelType, types.ModelSource) ([]*types.Model, error) {
return nil, nil
}
func (s *stubModelRepoForDelete) Update(context.Context, *types.Model) error { return nil }
func (s *stubModelRepoForDelete) Update(_ context.Context, model *types.Model) error {
if s.update != nil {
return s.update(model)
}
return nil
}
func (s *stubModelRepoForDelete) Delete(_ context.Context, _ uint64, id string) error {
if s.delete != nil {
return s.delete(id)
+6 -5
View File
@@ -29,8 +29,8 @@ type ModelResponse struct {
Status types.ModelStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-field "configured?" map. Omitted for builtin models (no
// per-tenant credentials). See MCPServiceResponse.Credentials.
// Per-field "configured?" map. Omitted for builtin models unless the
// caller is a system administrator. See MCPServiceResponse.Credentials.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
@@ -71,12 +71,13 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
MaxConcurrency: m.Parameters.MaxConcurrency,
AppID: m.Parameters.AppID,
}
if !CanViewIntegrationSecrets(ctx) {
canManageBuiltin := m.IsBuiltin && types.IsSystemAdminFromContext(ctx)
if !CanViewIntegrationSecrets(ctx) && !canManageBuiltin {
params.ExtraConfig = nil
params.CustomHeaders = nil
params.BaseURL = ""
}
if m.IsBuiltin {
if m.IsBuiltin && !canManageBuiltin {
// Builtin: strip everything that could reveal per-tenant config.
// EmbeddingParameters and ParameterSize / Provider / InterfaceType /
// SupportsVision are intentionally preserved (they describe the
@@ -87,7 +88,7 @@ func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
params.AppID = ""
}
var creds map[string]CredentialFieldMetadata
if !m.IsBuiltin {
if !m.IsBuiltin || canManageBuiltin {
creds = map[string]CredentialFieldMetadata{
"api_key": {Configured: m.Parameters.APIKey != ""},
"app_secret": {Configured: m.Parameters.AppSecret != ""},
+31
View File
@@ -1,12 +1,14 @@
package dto
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestModelResponse_OmitsSecrets(t *testing.T) {
@@ -70,6 +72,35 @@ func TestModelResponse_BuiltinStripsTenantConfig(t *testing.T) {
assert.False(t, strings.Contains(string(body), "tenant-private.example.com"))
}
func TestModelResponse_SystemAdminCanManageBuiltinConfig(t *testing.T) {
ctx := context.WithValue(viewerContext(), types.SystemAdminContextKey, true)
m := &types.Model{
ID: "builtin-1",
IsBuiltin: true,
Parameters: types.ModelParameters{
BaseURL: "https://global-provider.example.com",
APIKey: "should-never-be-returned",
AppSecret: "also-never-returned",
AppID: "global-app-id",
ExtraConfig: map[string]string{"region": "ap-guangzhou"},
CustomHeaders: map[string]string{"X-Route": "global"},
},
}
resp := NewModelResponse(ctx, m)
assert.Equal(t, "https://global-provider.example.com", resp.Parameters.BaseURL)
assert.Equal(t, "global-app-id", resp.Parameters.AppID)
assert.Equal(t, map[string]string{"region": "ap-guangzhou"}, resp.Parameters.ExtraConfig)
assert.Equal(t, map[string]string{"X-Route": "global"}, resp.Parameters.CustomHeaders)
assert.True(t, resp.Credentials["api_key"].Configured)
assert.True(t, resp.Credentials["app_secret"].Configured)
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "should-never-be-returned")
assert.NotContains(t, string(body), "also-never-returned")
}
func TestModelResponse_ViewerStripsIntegrationDetail(t *testing.T) {
m := &types.Model{
ID: "m-2",
+10
View File
@@ -615,6 +615,12 @@ func (h *ModelHandler) UpdateModel(c *gin.Context) {
newParams.AppSecret = storedAppSecret
// Preserve backend-managed fields not sent by the frontend either.
newParams.ParameterSize = model.Parameters.ParameterSize
if newParams.InterfaceType == "" {
newParams.InterfaceType = model.Parameters.InterfaceType
}
if newParams.AppID == "" {
newParams.AppID = model.Parameters.AppID
}
if newParams.ExtraConfig == nil {
newParams.ExtraConfig = model.Parameters.ExtraConfig
}
@@ -625,6 +631,10 @@ func (h *ModelHandler) UpdateModel(c *gin.Context) {
logger.Infof(ctx, "Updating model, ID: %s, Name: %s", id, model.Name)
if err := h.service.UpdateModel(ctx, model); err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
+8
View File
@@ -66,6 +66,10 @@ func (h *ModelCredentialsHandler) Put(c *gin.Context) {
c.Error(errors.NewNotFoundError("Model not found"))
return
}
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{"model_id": secutils.SanitizeForLog(id)})
c.Error(errors.NewInternalServerError("failed to update credentials: " + err.Error()))
return
@@ -98,6 +102,10 @@ func (h *ModelCredentialsHandler) DeleteField(c *gin.Context) {
c.Error(errors.NewNotFoundError("Model not found"))
return
}
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": secutils.SanitizeForLog(id),
"field": field,
+20
View File
@@ -110,6 +110,26 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
}
}
// RequireRoleOrSystemAdmin applies the tenant role floor while also allowing
// platform system administrators. Use it for routes that normally mutate
// tenant infrastructure but have a narrowly-scoped platform-owned resource
// (for example built-in models) that system administrators must be able to
// maintain independently of their role in the active tenant.
//
// API-key behavior remains identical to RequireRole: the APIKeyGate is the
// source of truth for machine principals, so they short-circuit the role
// check here as well.
func RequireRoleOrSystemAdmin(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
requireRole := RequireRole(min, cfg)
return func(c *gin.Context) {
if types.IsSystemAdminFromContext(c.Request.Context()) {
c.Next()
return
}
requireRole(c)
}
}
// RequireSystemAdmin returns a gin middleware that aborts the request with
// HTTP 403 unless the caller is a system administrator
// (User.IsSystemAdmin = true).
+28
View File
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
// rbacTestHarness builds a tiny gin engine with the RBAC middleware in
@@ -80,6 +81,33 @@ func TestRequireRole_RejectsBelowMin(t *testing.T) {
}
}
func TestRequireRoleOrSystemAdmin_AllowsSystemAdminBelowTenantRole(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, types.TenantRoleViewer)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, true)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
router.GET("/protected",
RequireRoleOrSystemAdmin(types.TenantRoleAdmin, cfgRBAC(true)),
func(c *gin.Context) { c.Status(http.StatusOK) },
)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/protected", nil))
assert.Equal(t, http.StatusOK, w.Code)
}
func TestRequireRoleOrSystemAdmin_RejectsOrdinaryViewer(t *testing.T) {
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireRoleOrSystemAdmin(types.TenantRoleAdmin, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("ordinary Viewer must not clear Admin-or-SystemAdmin gate, got %d", w.Code)
}
}
func TestRequireRole_FailOpenWhenRBACDisabled(t *testing.T) {
// EnableRBAC=false: the middleware should log but not block, so the
// downstream handler still runs. This is the rollout-safety guarantee.
+4
View File
@@ -204,6 +204,10 @@ func (g *rbacGuards) Admin() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleAdmin, g.cfg)
}
func (g *rbacGuards) AdminOrSystemAdmin() gin.HandlerFunc {
return middleware.RequireRoleOrSystemAdmin(types.TenantRoleAdmin, g.cfg)
}
func (g *rbacGuards) Owner() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleOwner, g.cfg)
}
+4 -4
View File
@@ -719,13 +719,13 @@ func RegisterModelRoutes(
models.POST("/:id/debug", g.Admin(), handler.DebugModel)
// 获取单个模型 — Viewer+
models.GET("/:id", g.Viewer(), handler.GetModel)
// 更新模型 — Admin+
models.PUT("/:id", g.Admin(), handler.UpdateModel)
// 更新模型 — Admin+;内置模型仍由服务层额外限定为 SystemAdmin。
models.PUT("/:id", g.AdminOrSystemAdmin(), handler.UpdateModel)
// 删除模型 — Admin+
models.DELETE("/:id", g.Admin(), handler.DeleteModel)
// Per-field credential subresource (see internal/handler/model_credentials.go) — Admin+
models.PUT("/:id/credentials", g.Admin(), credHandler.Put)
models.DELETE("/:id/credentials/:field", g.Admin(), credHandler.DeleteField)
models.PUT("/:id/credentials", g.AdminOrSystemAdmin(), credHandler.Put)
models.DELETE("/:id/credentials/:field", g.AdminOrSystemAdmin(), credHandler.DeleteField)
}
}
+21 -3
View File
@@ -68,9 +68,9 @@ func interpolateBuiltinModelEnv(s string) string {
// with the file contents.
//
// Lifecycle contract:
// - YAML loader only ever reads/writes rows tagged managed_by="yaml". Rows
// created via UI/API/SQL (managed_by="") are invisible to the loader and
// are never modified.
// - YAML loader only ever writes rows tagged managed_by="yaml". Rows created
// or explicitly overridden via UI/API/SQL (managed_by="") are detected by
// id and preserved, and are never modified.
// - Each YAML entry is UPSERTed by id, with deleted_at force-reset to NULL
// (so a row that was soft-deleted previously is resurrected when it
// reappears in the file).
@@ -135,6 +135,24 @@ func LoadBuiltinModelsConfig(ctx context.Context, db *gorm.DB, configDir string)
}
m := e.toModel()
// A system-admin edit clears managed_by to claim the row as a runtime
// override. Preserve that explicit override on subsequent starts rather
// than reclaiming and overwriting it from YAML. Unscoped is required so
// a manually managed soft-deleted collision is not resurrected either.
var existing Model
lookupErr := db.WithContext(ctx).Unscoped().
Select("id", "managed_by").
Where("id = ?", m.ID).
First(&existing).Error
if lookupErr == nil && existing.ManagedBy != BuiltinModelManagedBy {
log.Printf("[builtin-models] preserving runtime override: id=%s", m.ID)
continue
}
if lookupErr != nil && lookupErr != gorm.ErrRecordNotFound {
log.Printf("[builtin-models] WARN: inspect existing model %s failed: %v; skipping", m.ID, lookupErr)
continue
}
// Mirror the API path's "single default per (tenant_id, type)"
// invariant: clear other defaults before promoting this one.
// Excluded our own id so we don't churn against ourselves.
@@ -127,6 +127,29 @@ func TestLoadBuiltinModelsConfig_Idempotent(t *testing.T) {
assert.Equal(t, int64(1), count, "second load must not duplicate")
}
func TestLoadBuiltinModelsConfig_PreservesRuntimeOverride(t *testing.T) {
db := setupBuiltinModelsDB(t)
dir := writeYAML(t, `builtin_models:
- id: builtin-llm
name: from-yaml
type: KnowledgeQA
`)
require.NoError(t, LoadBuiltinModelsConfig(context.Background(), db, dir))
// System-admin edits clear managed_by. A later startup must not reclaim
// that row even when the same id remains declared in YAML.
require.NoError(t, db.Model(&Model{}).Where("id = ?", "builtin-llm").Updates(map[string]any{
"name": "from-admin-ui",
"managed_by": "",
}).Error)
require.NoError(t, LoadBuiltinModelsConfig(context.Background(), db, dir))
var m Model
require.NoError(t, db.Where("id = ?", "builtin-llm").First(&m).Error)
assert.Equal(t, "from-admin-ui", m.Name)
assert.Empty(t, m.ManagedBy)
}
func TestLoadBuiltinModelsConfig_EnvInterpolation(t *testing.T) {
db := setupBuiltinModelsDB(t)
t.Setenv("BUILTIN_TEST_KEY", "sk-from-env")