diff --git a/docs/BUILTIN_MODELS.md b/docs/BUILTIN_MODELS.md index 9fac0686..883c375a 100644 --- a/docs/BUILTIN_MODELS.md +++ b/docs/BUILTIN_MODELS.md @@ -2,14 +2,20 @@ ## 概述 -内置模型是系统级别的模型配置,对所有租户可见,但敏感信息会被隐藏,且不可编辑或删除。内置模型通常用于提供系统默认的模型配置,确保所有租户都能使用统一的模型服务。 +内置模型是系统级别的模型配置,对所有租户可见。普通租户用户(包括租户管理员)看到的敏感信息会被隐藏,且不能修改;系统管理员可以在「模型管理」界面编辑配置和凭据。内置模型通常用于提供系统默认的模型配置,确保所有租户都能使用统一的模型服务。 ## 内置模型特性 - **所有租户可见**:内置模型对所有租户都可见,无需单独配置 -- **安全保护**:内置模型的敏感信息(API Key、Base URL)会被隐藏,无法查看详情 -- **只读保护**:内置模型不能被编辑或删除,只能设置为默认模型 -- **统一管理**:由系统管理员统一维护,确保配置一致性和安全性 +- **安全保护**:API Key 等凭据永远不会明文返回;只有系统管理员能看到 Base URL 等管理信息和凭据是否已配置 +- **权限保护**:普通租户用户只能查看;系统管理员可以编辑配置和凭据 +- **统一管理**:内置模型对所有租户生效;删除仍通过 YAML 或 SQL 管理,避免部署配置与运行时状态冲突 + +## 在管理界面编辑 + +系统管理员可直接在「设置 → 模型管理」中点击内置模型,修改模型参数或更新凭据。普通租户管理员仍然只能查看。 + +首次通过管理界面保存 YAML 托管的内置模型后,该行会转为运行时托管(`managed_by` 清空),后续应用启动不会再用同 ID 的 YAML 条目覆盖它。这样可以保证界面保存的结果在重启后仍然有效。若希望重新交给 YAML 管理,需要由部署管理员在数据库中把该行的 `managed_by` 恢复为 `yaml`,或移除运行时覆盖后重新启动。 ## 如何添加内置模型 @@ -21,7 +27,7 @@ WeKnora 支持两种方式添加内置模型:**推荐**使用 YAML 声明式 默认路径是 `config/builtin_models.yaml`(与 `config.yaml`、`builtin_agents.yaml` 同目录)。如需挂载到其他位置,设置环境变量 `BUILTIN_MODELS_CONFIG=/absolute/path/builtin_models.yaml` 覆盖。 -文件不存在时启动期会跳过、不报错;解析失败仅记录 Warning、不影响主流程。每次应用启动会重新读取并按 `id` 字段 UPSERT 到 `models` 表(保留 `created_at`,刷新其他字段)。 +文件不存在时启动期会跳过、不报错;解析失败仅记录 Warning、不影响主流程。每次应用启动会重新读取并按 `id` 字段 UPSERT 到 `models` 表(保留 `created_at`,刷新其他字段)。如果同 ID 模型已经由系统管理员在界面保存并转为运行时托管,则保留运行时配置,不再由 YAML 覆盖。 #### Schema diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts index a548ac96..e18d9657 100644 --- a/frontend/src/api/model/index.ts +++ b/frontend/src/api/model/index.ts @@ -41,8 +41,8 @@ export interface ModelConfig { is_default?: boolean; is_builtin?: boolean; status?: string; - // Per-field configured? metadata from the main response. Absent for - // builtin models. + // Per-field configured? metadata from the main response. For builtin + // models it is returned only to system administrators. credentials?: Record; created_at?: string; updated_at?: string; diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 90d75d28..62e61fb2 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -4713,6 +4713,7 @@ export default { builtinModels: { title: 'Built-in Models', description: 'Built-in models are visible to all tenants. Sensitive information is hidden, and they cannot be edited or deleted.', + descriptionAdmin: 'Built-in models are visible to all tenants. System administrators can edit configuration and credentials; deletion remains deployment-managed.', viewGuide: 'View Built-in Models Guide', }, builtinTag: 'Built-in', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 8dc51644..fddcbc42 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -4719,6 +4719,7 @@ export default { builtinModels: { title: "기본 제공 모델", description: "기본 제공 모델은 모든 테넌트에게 표시됩니다. 민감한 정보는 숨겨지며, 편집하거나 삭제할 수 없습니다.", + descriptionAdmin: "기본 제공 모델은 모든 테넌트에게 표시됩니다. 시스템 관리자는 구성과 자격 증명을 편집할 수 있으며, 삭제는 배포 구성에서 관리됩니다.", viewGuide: "기본 제공 모델 관리 가이드 보기", }, builtinTag: "기본제공", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 2e63d888..56b61d80 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -4373,6 +4373,7 @@ export default { builtinModels: { title: 'Встроенные модели', description: 'Встроенные модели видны всем тенантам. Конфиденциальная информация скрыта, их нельзя редактировать или удалять.', + descriptionAdmin: 'Встроенные модели видны всем тенантам. Системные администраторы могут изменять конфигурацию и учетные данные; удаление управляется конфигурацией развертывания.', viewGuide: 'Посмотреть руководство по управлению встроенными моделями' }, builtinTag: 'Встроенная', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 90161263..acac6652 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -4725,6 +4725,7 @@ export default { builtinModels: { title: "内置模型", description: "内置模型对所有租户可见,敏感信息会被隐藏,且不可编辑或删除。", + descriptionAdmin: "内置模型对所有租户可见。系统管理员可编辑配置和凭据;删除仍由部署配置管理。", viewGuide: "查看内置模型管理指南", }, builtinTag: "内置", diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vue index e55a3a23..afb70a96 100644 --- a/frontend/src/views/settings/ModelSettings.vue +++ b/frontend/src/views/settings/ModelSettings.vue @@ -22,7 +22,11 @@

{{ $t('modelSettings.builtinModels.title') }}

-

{{ $t('modelSettings.builtinModels.description') }}

+

+ {{ $t(authStore.isSystemAdmin + ? 'modelSettings.builtinModels.descriptionAdmin' + : 'modelSettings.builtinModels.description') }} +

{{ $t('modelSettings.builtinModels.viewGuide') }} @@ -64,7 +68,7 @@

{{ modelDisplayName(model) }}

- +
{ showDialog.value = true } -// 可点击打开编辑抽屉:管理员 + 非内置模型 -const isModelCardClickable = (model: any) => - authStore.hasRole('admin') && !model.isBuiltin +// Tenant Admin+ manages tenant models; only SystemAdmin manages shared +// built-in models. The backend repeats this distinction authoritatively. +const canEditModel = (model: any) => + model.isBuiltin ? authStore.isSystemAdmin : authStore.hasRole('admin') -const canManageModel = (model: any) => +const isModelCardClickable = (model: any) => canEditModel(model) + +const canManageModel = (model: any) => canEditModel(model) + +// Built-in lifecycle remains deployment-managed (YAML / SQL). The UI only +// exposes configuration and credential editing to SystemAdmin. +const canDeleteModel = (model: any) => authStore.hasRole('admin') && !model.isBuiltin const onModelCardClick = (event: Event, type: ModelType, model: any) => { @@ -331,11 +343,11 @@ const onModelCardClick = (event: Event, type: ModelType, model: any) => { // 编辑模型 const editModel = (type: ModelType, model: any) => { - if (model.isBuiltin) { + if (model.isBuiltin && !authStore.isSystemAdmin) { MessagePlugin.warning(t('modelSettings.toasts.builtinCannotEdit')) return } - if (!authStore.hasRole('admin')) { + if (!model.isBuiltin && !authStore.hasRole('admin')) { return } currentModelType.value = type @@ -492,6 +504,12 @@ const getModelOptions = (type: ModelType, model: any) => { const options: any[] = [] if (model.isBuiltin) { + if (authStore.isSystemAdmin) { + options.push({ + content: t('common.edit'), + value: `edit-${type}-${model.id}` + }) + } return options } diff --git a/internal/application/service/model.go b/internal/application/service/model.go index 78a8f9d0..00a106ae 100644 --- a/internal/application/service/model.go +++ b/internal/application/service/model.go @@ -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 } diff --git a/internal/application/service/model_builtin_management_test.go b/internal/application/service/model_builtin_management_test.go new file mode 100644 index 00000000..57b720aa --- /dev/null +++ b/internal/application/service/model_builtin_management_test.go @@ -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 = © + 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 = © + 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) + }) +} diff --git a/internal/application/service/model_delete_test.go b/internal/application/service/model_delete_test.go index fea92be9..ad66d4f9 100644 --- a/internal/application/service/model_delete_test.go +++ b/internal/application/service/model_delete_test.go @@ -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) diff --git a/internal/handler/dto/model.go b/internal/handler/dto/model.go index c523fd94..4ebc9c76 100644 --- a/internal/handler/dto/model.go +++ b/internal/handler/dto/model.go @@ -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 != ""}, diff --git a/internal/handler/dto/model_test.go b/internal/handler/dto/model_test.go index 6206bf12..33aaa677 100644 --- a/internal/handler/dto/model_test.go +++ b/internal/handler/dto/model_test.go @@ -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", diff --git a/internal/handler/model.go b/internal/handler/model.go index 45f9909b..e5a6d26e 100644 --- a/internal/handler/model.go +++ b/internal/handler/model.go @@ -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 diff --git a/internal/handler/model_credentials.go b/internal/handler/model_credentials.go index b08caa00..fd1f9a00 100644 --- a/internal/handler/model_credentials.go +++ b/internal/handler/model_credentials.go @@ -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, diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.go index d4fdaec9..8c1622af 100644 --- a/internal/middleware/rbac.go +++ b/internal/middleware/rbac.go @@ -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). diff --git a/internal/middleware/rbac_test.go b/internal/middleware/rbac_test.go index 24268735..5610acc5 100644 --- a/internal/middleware/rbac_test.go +++ b/internal/middleware/rbac_test.go @@ -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. diff --git a/internal/router/rbac.go b/internal/router/rbac.go index c95e0526..18f906a5 100644 --- a/internal/router/rbac.go +++ b/internal/router/rbac.go @@ -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) } diff --git a/internal/router/router.go b/internal/router/router.go index e86f92c3..ca2111d5 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -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) } } diff --git a/internal/types/builtin_models_config.go b/internal/types/builtin_models_config.go index 4b678df0..7f1d508e 100644 --- a/internal/types/builtin_models_config.go +++ b/internal/types/builtin_models_config.go @@ -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. diff --git a/internal/types/builtin_models_config_test.go b/internal/types/builtin_models_config_test.go index 79f2e14e..3d799aeb 100644 --- a/internal/types/builtin_models_config_test.go +++ b/internal/types/builtin_models_config_test.go @@ -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")