diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.ts index d59ce730..d7929b47 100644 --- a/frontend/src/api/tenant/index.ts +++ b/frontend/src/api/tenant/index.ts @@ -53,7 +53,7 @@ export interface APIPrincipalTestToken { // - 'chat': run the conversation flow (sessions + agent listing + self identity) // - 'read_agents': list/read agents without chat or authoring // - 'ingest': write content into allowed knowledge bases (docs/chunks/FAQ/tags/wiki) -// - 'manage_kbs': manage existing knowledge-base metadata/configuration +// - 'manage_kbs': manage the KB lifecycle (create/copy/duplicate/update/delete + config) // - 'manage_agents': create/update/delete/copy agents // - 'message_history': search/read tenant chat-history metadata // - 'manage_models': manage tenant model definitions, checks, and credentials diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 48580bde..82b48260 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -6225,7 +6225,7 @@ export default { capabilityIngest: 'Write KB content', capabilityIngestHint: 'Let this key write content into its allowed knowledge bases (upload documents, edit chunks/FAQ/tags/wiki). It cannot create knowledge bases or agents, cannot clear a knowledge base, and stays bounded to the selected knowledge bases.', capabilityManageKbs: 'Manage knowledge bases', - capabilityManageKbsHint: 'Let this key update or delete existing knowledge bases and change their initialization/configuration within the selected scope. It does not create new knowledge bases.', + capabilityManageKbsHint: 'Let this key manage the full knowledge-base lifecycle: create, copy, update, and delete knowledge bases and change their initialization/configuration. Operations on existing knowledge bases (copy/update/delete) stay bounded by the selected scope; creating a new knowledge base is unrestricted (the new KB belongs to this space).', capabilityManageAgents: 'Manage agents', capabilityManageAgentsHint: 'Let this key create, update, delete and copy agents. Agent config can carry sensitive model/MCP bindings, so this is off by default — enable only when needed.', capabilityMessageHistory: 'Message history', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index c55fdbf9..10a7b6b1 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -6229,7 +6229,7 @@ export default { capabilityIngest: "지식베이스 콘텐츠 쓰기", capabilityIngestHint: "허용된 지식베이스에 콘텐츠를 작성할 수 있습니다(문서 업로드, 청크/FAQ/태그/wiki 편집). 지식베이스나 에이전트를 새로 만들 수 없고, 지식베이스를 비울 수 없으며, 선택한 지식베이스 범위로 제한됩니다.", capabilityManageKbs: "지식베이스 관리", - capabilityManageKbsHint: "선택한 범위 안에서 기존 지식베이스를 수정 또는 삭제하고 초기화/설정을 변경할 수 있습니다. 새 지식베이스 생성은 허용하지 않습니다.", + capabilityManageKbsHint: "지식베이스 전체 수명 주기를 관리할 수 있습니다: 생성, 복사, 수정, 삭제 및 초기화/설정 변경. 기존 지식베이스에 대한 작업(복사/수정/삭제)은 선택한 범위로 제한되며, 새 지식베이스 생성은 제한되지 않습니다(새 지식베이스는 이 스페이스에 속함).", capabilityManageAgents: "에이전트 관리", capabilityManageAgentsHint: "에이전트를 생성, 수정, 삭제, 복사할 수 있습니다. 에이전트 설정에는 모델/MCP 등 민감한 바인딩이 포함될 수 있으므로 기본적으로 꺼져 있으며 필요할 때만 켜세요.", capabilityMessageHistory: "메시지 기록", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 2fa99311..45d1a923 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -6050,7 +6050,7 @@ export default { capabilityIngest: 'Запись в базы знаний', capabilityIngestHint: 'Позволяет ключу записывать содержимое в разрешённые базы знаний (загрузка документов, редактирование фрагментов/FAQ/тегов/wiki). Нельзя создавать базы знаний или агентов, нельзя очищать базу знаний; действие ограничено выбранными базами знаний.', capabilityManageKbs: 'Управление базами знаний', - capabilityManageKbsHint: 'Позволяет обновлять или удалять существующие базы знаний и менять их конфигурацию в выбранной области. Не разрешает создавать новые базы знаний.', + capabilityManageKbsHint: 'Позволяет управлять всем жизненным циклом баз знаний: создавать, копировать, обновлять и удалять базы знаний, а также менять их инициализацию/конфигурацию. Операции над существующими базами знаний (копирование/обновление/удаление) по-прежнему ограничены выбранной областью; создание новой базы знаний не ограничено (новая база знаний принадлежит этому пространству).', capabilityManageAgents: 'Управление агентами', capabilityManageAgentsHint: 'Позволяет создавать, изменять, удалять и копировать агентов. Конфигурация агента может содержать чувствительные привязки моделей/MCP, поэтому по умолчанию отключено — включайте только при необходимости.', capabilityMessageHistory: 'История сообщений', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 9c67662b..b2630d9d 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -6250,7 +6250,7 @@ export default { capabilityIngest: "写入知识库内容", capabilityIngestHint: "允许向授权范围内的知识库写入内容(上传文档、编辑分块/FAQ/标签/wiki);不能新建知识库、不能新建智能体、不能清空知识库,且仅限所选知识库范围。", capabilityManageKbs: "管理知识库", - capabilityManageKbsHint: "允许在所选知识库范围内修改或删除已有知识库,并调整初始化/配置信息;不允许新建知识库。", + capabilityManageKbsHint: "允许管理知识库全生命周期:新建、复制、修改、删除知识库并调整初始化/配置信息。针对已有知识库的操作(复制/更新/删除)仍受所选知识库范围限制;新建不受限(新知识库归本空间)。", capabilityManageAgents: "管理智能体", capabilityManageAgentsHint: "允许创建、修改、删除、复制智能体。智能体配置可能含模型/MCP 等敏感绑定,默认关闭,按需开启。", capabilityMessageHistory: "消息历史", diff --git a/internal/router/router.go b/internal/router/router.go index 4e050502..2a0a1d44 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -404,26 +404,38 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG // RegisterKnowledgeBaseRoutes 注册知识库相关的路由 func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeBaseHandler, g *rbacGuards) { - // 知识库路由组。Scoped API key 需要 retrieve 能力读取(限 KB 范围);KB 内容写入 - // 由 RegisterKnowledgeRoutes/FAQ/Tag/Wiki 等子路由的 ingest 能力控制; - // KB 自身的元数据/生命周期管理需要 full access 或 manage_kbs。创建/拷贝 - // KB 没有单个目标 KB 可约束,因此不对 scoped key 开放(capability 无法 - // 把它约束到某个 KB 上);但 full-access key 是空间级全权,与它已能 - // 更新/删除/管理 KB 对齐,允许其创建 KB,消除"能删不能建"的不一致。 + // 知识库路由组。API-key 可达性按能力分两档,全部通过 apiKeyGroup 声明, + // 不要再用裸 kbgrp.Handle 注册(那会绕过网关、对所有 key 静默默认拒绝): + // + // 1. 读取(list/detail/search/progress/move-targets)—— retrieve OR full-access(kb) + // 2. KB 生命周期管理(create/copy/duplicate/update/delete) + // —— manage_kbs OR full-access(kbManagement) + // + // 第 2 档整条 KB 生命周期共用同一策略:manage_kbs 是「管理知识库」capability, + // 建/拷/改/删都是它的分内事。KB 的 allow-list 仍在下游生效——copy/duplicate/ + // update/delete 的目标 KB 会被 allow-list 兜住;create 无源可约束,限定 allow-list + // 的 key 建出的新 KB 落在其 allow-list 之外(同租户、无越权,只是建完自己管不到), + // 空 allow-list 的 key 则是全租户 KB 管理、新建天然在范围内。KB 内容写入(文档/ + // 分块/FAQ/Tag/Wiki)由对应子路由的 ingest 能力控制,不在本组。 kbgrp := r.Group("/knowledge-bases") kb := g.apiKeyGroup(kbgrp, apiKeyRetrieve(apiKeyFullAccess())) kbManagement := kb.With(apiKeyManageKnowledgeBases(apiKeyFullAccess())) { - // 创建知识库 — Contributor+ for JWT callers; full-access API keys may - // create KBs (scoped keys stay default-deny: no KB to bound against). - kb.With(apiKeyFullAccess()).POST("", g.Contributor(), handler.CreateKnowledgeBase) + // 创建知识库 — JWT Contributor+;API key 需 manage_kbs 或 full-access。 + kbManagement.POST("", g.Contributor(), handler.CreateKnowledgeBase) // 获取知识库列表 — Viewer+ for JWT callers; retrieve-capable API keys pass via the gate. kb.GET("", g.Viewer(), handler.ListKnowledgeBases) // 获取知识库详情 — Viewer+ 且对 KB 有 read 权限 kb.GET("/:id", g.Viewer(), g.KBAccessRead("id"), handler.GetKnowledgeBase) - // 更新知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限 + // 更新/删除知识库 — 两层正交鉴权,缺一不可: + // OwnedKBOrAdmin 管「租户内」归属:非创建者的 Contributor 改不了 + // 同事的 KB(跨租户 KB 在此走 lookup=NotFound → 交给 + // 下游处理,不在此拦)。 + // KBAccessWrite 管「跨租户」访问级:自有 KB 或被组织共享(editor)。 + // handler 内再按 permission/所有者租户做最终判定 —— 尤其 DeleteKnowledgeBase + // 以调用者「自身」租户(c.Keys,未被 KBAccess 改写)校验 kb.TenantID, + // 把删除锁死为「所有者租户 + Admin」,共享 editor 无法删除源 KB。 kbManagement.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase) - // 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限 kbManagement.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase) // 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限 // Pin state is now per-(user, kb) (migration 000050). Anyone with @@ -437,11 +449,16 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB // POST is preferred; GET with JSON body is kept for backward compatibility (#1727). kb.POST("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch) kb.GET("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch) - // 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权) - kbgrp.POST("/copy", g.Contributor(), handler.CopyKnowledgeBase) - // 创建知识库副本 — Contributor+ 且对源 KB 有 read 权限;只创建新的 KB 设置记录,不复制内容/索引/分享。 - kbgrp.POST("/:id/duplicate", g.Contributor(), g.KBAccessRead("id"), handler.DuplicateKnowledgeBase) - // 获取知识库复制进度 — Viewer+ + // 拷贝知识库 — 产出新 KB,与 create 同档:JWT Contributor+,API key 需 manage_kbs 或 full-access。 + // 源 KB 通过 body 里的 source_id 传入(非 :id 路径参数),无法套用基于路径参数 + // 的 KBAccessRead,故源/目标 KB 的租户归属与 allow-list 校验在 handler 内完成 + // (requireTenantAPIKeyKnowledgeBases 会把 source_id/target_id 兜进 allow-list)。 + // 副本归调用者所有,不需要原 KB 的所有权。 + kbManagement.POST("/copy", g.Contributor(), handler.CopyKnowledgeBase) + // 创建知识库副本 — 产出新 KB,与 create 同档:JWT Contributor+,API key 需 manage_kbs 或 full-access; + // 且对源 KB 有 read 权限(KBAccessRead 会对限定 key 兜住源 KB)。只创建新的 KB 设置记录,不复制内容/索引/分享。 + kbManagement.POST("/:id/duplicate", g.Contributor(), g.KBAccessRead("id"), handler.DuplicateKnowledgeBase) + // 获取知识库复制进度 — Viewer+;只读,retrieve OR full-access 均可轮询(租户自查)。 kb.GET("/copy/progress/:task_id", g.Viewer(), handler.GetKBCloneProgress) // 获取可移动目标知识库列表 — Viewer+ 且对 KB 有 read 权限 kb.GET("/:id/move-targets", g.Viewer(), g.KBAccessRead("id"), handler.ListMoveTargets) diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go index ef8169a9..250aba53 100644 --- a/internal/router/router_api_key_capabilities_test.go +++ b/internal/router/router_api_key_capabilities_test.go @@ -182,44 +182,38 @@ func TestKnowledgeBaseManagementRoutesDeclareManageKBsCapability(t *testing.T) { } } -func TestKnowledgeBaseCreateRouteRequiresFullAccessForAPIKeys(t *testing.T) { - gin.SetMode(gin.TestMode) - g := &rbacGuards{} - v1 := gin.New().Group("/api/v1") - - RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g) - - // Creating a KB is open to full-access keys (tenant-wide authority), - // matching KB update/delete, but carries no capability so scoped keys - // stay denied. - policy := mustLookupAPIKeyPolicy(t, g, http.MethodPost, "/api/v1/knowledge-bases") - if !policy.RequireFullAccess { - t.Fatal("KB create should require full access for API keys") - } - if len(policy.Capabilities) != 0 { - t.Fatalf("KB create must not be granted by any capability: %#v", policy.Capabilities) - } -} - -func TestKnowledgeBaseCopyRoutesRemainDefaultDenyForAPIKeys(t *testing.T) { +func TestKnowledgeBaseLifecycleRoutesDeclareManageCapability(t *testing.T) { gin.SetMode(gin.TestMode) g := &rbacGuards{} v1 := gin.New().Group("/api/v1") RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g) + // The whole KB lifecycle (create/copy/duplicate/update/delete) shares one + // policy tier: manage_kbs OR full-access. create/copy/duplicate produce a + // new KB but are still KB-management operations, so manage_kbs admits them + // (the allow-list bounds copy/duplicate/update/delete downstream; ingest + // must never grant any of these). cases := []struct { method string path string }{ + {http.MethodPost, "/api/v1/knowledge-bases"}, {http.MethodPost, "/api/v1/knowledge-bases/copy"}, {http.MethodPost, "/api/v1/knowledge-bases/:id/duplicate"}, } for _, tc := range cases { t.Run(tc.method+" "+tc.path, func(t *testing.T) { - if _, ok := g.apiKeyAuthorizer.Lookup(tc.method, tc.path); ok { - t.Fatalf("route should remain default-deny for API keys: %s %s", tc.method, tc.path) + policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path) + if !policy.RequireFullAccess { + t.Fatal("policy should require full access without a matching capability") + } + if !policyHasCapability(policy, types.APIKeyCapabilityManageKnowledgeBases) { + t.Fatalf("policy capabilities = %#v, want manage_kbs", policy.Capabilities) + } + if policyHasCapability(policy, types.APIKeyCapabilityIngest) { + t.Fatalf("KB lifecycle route must not be granted by ingest: %#v", policy.Capabilities) } }) } diff --git a/internal/types/tenant_api_key.go b/internal/types/tenant_api_key.go index e0033ba9..9d517709 100644 --- a/internal/types/tenant_api_key.go +++ b/internal/types/tenant_api_key.go @@ -60,10 +60,16 @@ const ( // bases or agents, nor destructive KB clears, and the key's // knowledge_base_ids allow-list still bounds every write. APIKeyCapabilityIngest APIKeyCapability = "ingest" - // APIKeyCapabilityManageKnowledgeBases lets a scoped key manage existing - // knowledge-base metadata/configuration within its allowed KB scope. It is - // separate from ingest: uploading or editing KB contents does not imply - // permission to rename, reconfigure, or delete the KB itself. + // APIKeyCapabilityManageKnowledgeBases lets a scoped key manage the full + // knowledge-base lifecycle: create, copy, duplicate, rename/reconfigure, + // and delete. For operations that target an existing KB (copy/duplicate + // source, update, delete) the key's allowed KB scope still bounds which + // KBs it may touch; create has no source to bound against, so a + // scope-restricted key may add a new KB to its tenant (same-tenant, no + // cross-tenant reach — the new KB simply falls outside the key's + // allow-list and stays unmanageable by it). It is separate from ingest: + // uploading or editing KB contents does not imply permission to manage + // the KB itself. APIKeyCapabilityManageKnowledgeBases APIKeyCapability = "manage_kbs" // APIKeyCapabilityManageAgents lets a key create/read/update/delete/copy // agents. Agent config can carry sensitive model/MCP bindings, so this is