Add API key member and space capabilities

This commit is contained in:
wizardchen
2026-07-07 11:47:10 +08:00
committed by lyingbug
parent d60614475e
commit 974231190c
11 changed files with 164 additions and 16 deletions
+4
View File
@@ -63,6 +63,8 @@ export interface APIPrincipalTestToken {
// - 'manage_vector_stores': manage vector stores and parser/storage checks
// - 'manage_web_search': manage web-search providers
// - 'run_evaluations': run/read evaluation jobs
// - 'manage_members': manage tenant members and invitations
// - 'manage_spaces': manage organization/space collaboration
// - 'manage_tenant_settings': read/update tenant integration settings (API principal mode, headers, tenant KV)
export type TenantAPIKeyCapability =
| 'retrieve'
@@ -79,6 +81,8 @@ export type TenantAPIKeyCapability =
| 'manage_vector_stores'
| 'manage_web_search'
| 'run_evaluations'
| 'manage_members'
| 'manage_spaces'
| 'manage_tenant_settings'
export interface TenantAPIKey {
+5
View File
@@ -5786,6 +5786,7 @@ export default {
apiKeyCapabilities: 'Capabilities',
apiKeyCapabilityGroupKnowledge: 'Knowledge-base data',
apiKeyCapabilityGroupAutomation: 'Agents and integrations',
apiKeyCapabilityGroupCollaboration: 'Members and spaces',
apiKeyCapabilityGroupTenant: 'Tenant configuration',
apiKeyCapabilitySelectGroup: 'Select all',
apiKeyCapabilityClearGroup: 'Clear',
@@ -5819,6 +5820,10 @@ export default {
capabilityManageWebSearchHint: 'Manage web-search provider configurations, credentials, and connection tests.',
capabilityRunEvaluations: 'Run evaluations',
capabilityRunEvaluationsHint: 'Run evaluation jobs and read evaluation results.',
capabilityManageMembers: 'Manage members',
capabilityManageMembersHint: 'List and manage tenant members, roles, invitations, and invite links. Does not include API key management, tenant deletion, or ownership transfer.',
capabilityManageSpaces: 'Manage spaces',
capabilityManageSpacesHint: 'Manage organization spaces, join flows, space membership, invitations, and shared-space visibility. Does not grant KB or agent share management.',
capabilityManageTenantSettings: 'Manage tenant settings',
capabilityManageTenantSettingsHint: 'Read and update tenant-level integration settings such as API end-user identity mode, request header configuration, and tenant KV settings. Does not include API key management, member management, tenant deletion, or ownership transfer.',
apiKeyKnowledgeScope: 'Knowledge bases',
+5
View File
@@ -5797,6 +5797,7 @@ export default {
apiKeyCapabilities: "사용 가능 기능",
apiKeyCapabilityGroupKnowledge: "지식베이스 데이터",
apiKeyCapabilityGroupAutomation: "에이전트 및 통합",
apiKeyCapabilityGroupCollaboration: "멤버 및 공간",
apiKeyCapabilityGroupTenant: "테넌트 설정",
apiKeyCapabilitySelectGroup: "전체 선택",
apiKeyCapabilityClearGroup: "비우기",
@@ -5830,6 +5831,10 @@ export default {
capabilityManageWebSearchHint: "웹 검색 공급자 설정, 자격 증명 및 연결 테스트를 관리합니다.",
capabilityRunEvaluations: "평가 실행",
capabilityRunEvaluationsHint: "평가 작업을 실행하고 결과를 읽을 수 있습니다.",
capabilityManageMembers: "멤버 관리",
capabilityManageMembersHint: "테넌트 멤버, 역할, 초대 및 초대 링크를 조회하고 관리할 수 있습니다. API Key 관리, 테넌트 삭제 또는 소유권 이전은 포함하지 않습니다.",
capabilityManageSpaces: "공간 관리",
capabilityManageSpacesHint: "조직/공간, 가입 흐름, 공간 멤버, 초대 및 공유 공간 표시를 관리할 수 있습니다. 지식베이스 또는 에이전트 공유 관리는 부여하지 않습니다.",
capabilityManageTenantSettings: "테넌트 설정 관리",
capabilityManageTenantSettingsHint: "API 최종 사용자 식별 모드, 요청 헤더 설정, 테넌트 KV 설정 등 테넌트 수준 통합 설정을 읽고 업데이트합니다. API Key 관리, 멤버 관리, 테넌트 삭제 또는 소유권 이전은 포함하지 않습니다.",
apiKeyKnowledgeScope: "지식베이스 범위",
+5
View File
@@ -5618,6 +5618,7 @@ export default {
apiKeyCapabilities: 'Возможности',
apiKeyCapabilityGroupKnowledge: 'Данные баз знаний',
apiKeyCapabilityGroupAutomation: 'Агенты и интеграции',
apiKeyCapabilityGroupCollaboration: 'Участники и пространства',
apiKeyCapabilityGroupTenant: 'Настройки арендатора',
apiKeyCapabilitySelectGroup: 'Выбрать всё',
apiKeyCapabilityClearGroup: 'Очистить',
@@ -5651,6 +5652,10 @@ export default {
capabilityManageWebSearchHint: 'Управление провайдерами веб-поиска, учётными данными и проверками подключения.',
capabilityRunEvaluations: 'Запуск оценок',
capabilityRunEvaluationsHint: 'Запуск задач оценки и чтение результатов.',
capabilityManageMembers: 'Управление участниками',
capabilityManageMembersHint: 'Просмотр и управление участниками арендатора, ролями, приглашениями и ссылками-приглашениями. Не включает управление API Key, удаление арендатора или передачу владения.',
capabilityManageSpaces: 'Управление пространствами',
capabilityManageSpacesHint: 'Управление организациями/пространствами, вступлением, участниками, приглашениями и видимостью общих пространств. Не даёт управление шарингом баз знаний или агентов.',
capabilityManageTenantSettings: 'Управление настройками арендатора',
capabilityManageTenantSettingsHint: 'Чтение и обновление интеграционных настроек арендатора: режим идентификации конечного пользователя API, настройки заголовков запросов и tenant KV. Не включает управление API Key, участниками, удаление арендатора или передачу владения.',
apiKeyKnowledgeScope: 'Базы знаний',
+5
View File
@@ -5799,6 +5799,7 @@ export default {
apiKeyCapabilities: "可用能力",
apiKeyCapabilityGroupKnowledge: "知识库数据",
apiKeyCapabilityGroupAutomation: "智能体与集成",
apiKeyCapabilityGroupCollaboration: "成员与空间",
apiKeyCapabilityGroupTenant: "租户配置",
apiKeyCapabilitySelectGroup: "全选",
apiKeyCapabilityClearGroup: "清空",
@@ -5832,6 +5833,10 @@ export default {
capabilityManageWebSearchHint: "允许管理联网搜索供应商配置、凭据和连接测试。",
capabilityRunEvaluations: "运行评测",
capabilityRunEvaluationsHint: "允许运行评测任务并读取评测结果。",
capabilityManageMembers: "管理成员",
capabilityManageMembersHint: "允许查看和管理租户成员、角色、邀请和邀请链接;不包含 API Key 管理、租户删除或所有权转移。",
capabilityManageSpaces: "管理空间",
capabilityManageSpacesHint: "允许管理组织空间、加入流程、空间成员、邀请和共享空间可见性;不授予知识库或智能体分享管理权限。",
capabilityManageTenantSettings: "管理租户设置",
capabilityManageTenantSettingsHint: "允许读取和更新租户级集成设置,例如 API 终端用户身份模式、请求头配置、租户 KV 配置等;不包含 API Key 管理、成员管理、租户删除或所有权转移。",
apiKeyKnowledgeScope: "知识库范围",
@@ -636,6 +636,8 @@ const API_KEY_CAPABILITIES: TenantAPIKeyCapability[] = [
'manage_web_search',
'manage_channels',
'run_evaluations',
'manage_members',
'manage_spaces',
'manage_tenant_settings',
]
@@ -671,6 +673,14 @@ const apiKeyCapabilityGroups: ApiKeyCapabilityGroup[] = [
{ value: 'manage_datasources', labelKey: 'integrations.api.capabilityManageDatasources', hintKey: 'integrations.api.capabilityManageDatasourcesHint' },
],
},
{
key: 'collaboration',
labelKey: 'integrations.api.apiKeyCapabilityGroupCollaboration',
capabilities: [
{ value: 'manage_members', labelKey: 'integrations.api.capabilityManageMembers', hintKey: 'integrations.api.capabilityManageMembersHint' },
{ value: 'manage_spaces', labelKey: 'integrations.api.capabilityManageSpaces', hintKey: 'integrations.api.capabilityManageSpacesHint' },
],
},
{
key: 'tenant',
labelKey: 'integrations.api.apiKeyCapabilityGroupTenant',
@@ -766,6 +776,8 @@ function keyCapabilityLabels(key: TenantAPIKey): string[] {
manage_vector_stores: t('integrations.api.capabilityManageVectorStores'),
manage_web_search: t('integrations.api.capabilityManageWebSearch'),
run_evaluations: t('integrations.api.capabilityRunEvaluations'),
manage_members: t('integrations.api.capabilityManageMembers'),
manage_spaces: t('integrations.api.capabilityManageSpaces'),
manage_tenant_settings: t('integrations.api.capabilityManageTenantSettings'),
}
return (key.capabilities ?? [])
+8
View File
@@ -300,6 +300,14 @@ func apiKeyRunEvaluations(base middleware.APIKeyRoutePolicy) middleware.APIKeyRo
return base.WithCapability(types.APIKeyCapabilityRunEvaluations)
}
func apiKeyManageMembers(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
return base.WithCapability(types.APIKeyCapabilityManageMembers)
}
func apiKeyManageSpaces(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
return base.WithCapability(types.APIKeyCapabilityManageSpaces)
}
func apiKeyManageTenantSettings(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
return base.WithCapability(types.APIKeyCapabilityManageTenantSettings)
}
+16 -15
View File
@@ -610,9 +610,10 @@ func RegisterTenantRoutes(
g.apiKeyRoute(tenantRoutes, http.MethodPut, "/kv/:key", apiKeyManageTenantSettings(apiKeyFullAccess()), g.Admin(), handler.UpdateTenantKV)
// Per-tenant endpoints share PathTenantMatch at the group level.
// None of the /tenants/:id/* endpoints are declared for API keys,
// so scoped keys are denied by default — tenant lifecycle, member
// management and key/principal management are JWT-only.
// Most /tenants/:id/* endpoints stay undeclared for API keys by
// default — tenant lifecycle and key/principal management require
// full tenant access or JWT ownership. Member/invitation management
// opts in below through the manage_members capability.
tenantByID := tenantRoutes.Group("/:id", g.PathTenantMatch())
{
tenantByID.GET("", g.Viewer(), handler.GetTenant)
@@ -632,10 +633,10 @@ func RegisterTenantRoutes(
// their own; the service still rejects when it would leave
// the tenant without an Owner.
if memberHandler != nil {
tenantByID.GET("/members", g.Viewer(), memberHandler.ListMembers)
tenantByID.POST("/members", g.Owner(), memberHandler.AddMember)
tenantByID.PUT("/members/:user_id", g.Owner(), memberHandler.UpdateMemberRole)
tenantByID.DELETE("/members/:user_id", g.Owner(), memberHandler.RemoveMember)
g.apiKeyRoute(tenantByID, http.MethodGet, "/members", apiKeyManageMembers(apiKeyFullAccess()), g.Viewer(), memberHandler.ListMembers)
g.apiKeyRoute(tenantByID, http.MethodPost, "/members", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.AddMember)
g.apiKeyRoute(tenantByID, http.MethodPut, "/members/:user_id", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.UpdateMemberRole)
g.apiKeyRoute(tenantByID, http.MethodDelete, "/members/:user_id", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), memberHandler.RemoveMember)
tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant)
}
@@ -649,14 +650,14 @@ func RegisterTenantRoutes(
// mirrors memberHandler above for environments built
// without the invitation dependency wired.
if invitationHandler != nil {
tenantByID.GET("/invitations", g.Viewer(), invitationHandler.ListTenantInvitations)
tenantByID.POST("/invitations", g.Owner(), invitationHandler.CreateInvitation)
tenantByID.DELETE("/invitations/:inv_id", g.Owner(), invitationHandler.RevokeInvitation)
g.apiKeyRoute(tenantByID, http.MethodGet, "/invitations", apiKeyManageMembers(apiKeyFullAccess()), g.Viewer(), invitationHandler.ListTenantInvitations)
g.apiKeyRoute(tenantByID, http.MethodPost, "/invitations", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), invitationHandler.CreateInvitation)
g.apiKeyRoute(tenantByID, http.MethodDelete, "/invitations/:inv_id", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), invitationHandler.RevokeInvitation)
// Share-link create lives under /invite-links so the URL
// reads as "create a link" rather than another flavour
// of /invitations; the underlying row still lives in the
// tenant_invitations table and shows up in the GET above.
tenantByID.POST("/invite-links", g.Owner(), invitationHandler.CreateInviteLink)
g.apiKeyRoute(tenantByID, http.MethodPost, "/invite-links", apiKeyManageMembers(apiKeyFullAccess()), g.Owner(), invitationHandler.CreateInviteLink)
}
// Audit log feed (PR 6 of #1303). Admin+ so denied-action
@@ -1092,7 +1093,7 @@ func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler,
// RegisterOrganizationRoutes registers organization and sharing routes
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler, g *rbacGuards) {
// Organization routes
orgs := g.apiKeyGroup(r.Group("/organizations"), apiKeyFullAccess())
orgs := g.apiKeyGroup(r.Group("/organizations"), apiKeyManageSpaces(apiKeyFullAccess()))
{
// Create organization (Admin+ in caller's tenant only)
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
@@ -1202,13 +1203,13 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
}
// Shared knowledge bases route — Viewer+
g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyManageSpaces(apiKeyFullAccess()), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
// Shared agents route — Viewer+
g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedAgents)
g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyManageSpaces(apiKeyFullAccess()), g.Viewer(), orgHandler.ListSharedAgents)
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyFullAccess(), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyManageSpaces(apiKeyFullAccess()), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
}
// RegisterEmbedPublicRoutes registers anonymous embed endpoints secured by publish tokens.
@@ -293,6 +293,94 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
}
}
func TestTenantMemberRoutesDeclareManageMembersCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterTenantRoutes(v1, &handler.TenantHandler{}, &handler.TenantMemberHandler{}, &handler.TenantInvitationHandler{}, nil, g)
cases := []struct {
method string
path string
}{
{http.MethodGet, "/api/v1/tenants/:id/members"},
{http.MethodPost, "/api/v1/tenants/:id/members"},
{http.MethodPut, "/api/v1/tenants/:id/members/:user_id"},
{http.MethodDelete, "/api/v1/tenants/:id/members/:user_id"},
{http.MethodGet, "/api/v1/tenants/:id/invitations"},
{http.MethodPost, "/api/v1/tenants/:id/invitations"},
{http.MethodDelete, "/api/v1/tenants/:id/invitations/:inv_id"},
{http.MethodPost, "/api/v1/tenants/:id/invite-links"},
}
for _, tc := range cases {
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
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.APIKeyCapabilityManageMembers) {
t.Fatalf("policy capabilities = %#v, want manage_members", policy.Capabilities)
}
})
}
if _, ok := g.apiKeyAuthorizer.Lookup(http.MethodPost, "/api/v1/tenants/:id/leave"); ok {
t.Fatal("tenant leave route should remain default-deny for API keys")
}
}
func TestOrganizationRoutesDeclareManageSpacesCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterOrganizationRoutes(v1, &handler.OrganizationHandler{}, g)
cases := []struct {
method string
path string
}{
{http.MethodPost, "/api/v1/organizations"},
{http.MethodGet, "/api/v1/organizations"},
{http.MethodPost, "/api/v1/organizations/join"},
{http.MethodGet, "/api/v1/organizations/search"},
{http.MethodPut, "/api/v1/organizations/:id"},
{http.MethodPost, "/api/v1/organizations/:id/invite-code"},
{http.MethodGet, "/api/v1/organizations/:id/members"},
{http.MethodPut, "/api/v1/organizations/:id/members/:tenant_id"},
{http.MethodGet, "/api/v1/shared-knowledge-bases"},
{http.MethodGet, "/api/v1/shared-agents"},
{http.MethodPost, "/api/v1/shared-agents/disabled"},
}
for _, tc := range cases {
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
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.APIKeyCapabilityManageSpaces) {
t.Fatalf("policy capabilities = %#v, want manage_spaces", policy.Capabilities)
}
})
}
defaultDeny := []struct {
method string
path string
}{
{http.MethodPost, "/api/v1/knowledge-bases/:id/shares"},
{http.MethodPost, "/api/v1/agents/:id/shares"},
}
for _, tc := range defaultDeny {
if _, ok := g.apiKeyAuthorizer.Lookup(tc.method, tc.path); ok {
t.Fatalf("resource share route should remain default-deny for API keys: %s %s", tc.method, tc.path)
}
}
}
func TestChunkerPreviewRouteRequiresRetrieveOrIngestCapability(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
+13
View File
@@ -97,6 +97,15 @@ const (
// APIKeyCapabilityRunEvaluations lets a key run and inspect evaluation
// jobs without full tenant ownership.
APIKeyCapabilityRunEvaluations APIKeyCapability = "run_evaluations"
// APIKeyCapabilityManageMembers lets a key list and manage tenant
// members and invitations. It does not include API key management,
// tenant deletion, or ownership transfer.
APIKeyCapabilityManageMembers APIKeyCapability = "manage_members"
// APIKeyCapabilityManageSpaces lets a key manage organization/space
// collaboration surfaces such as space membership and join flows. It does
// not grant KB/agent share management, which still depends on resource
// ownership and remains JWT-only/default-deny for API keys.
APIKeyCapabilityManageSpaces APIKeyCapability = "manage_spaces"
// APIKeyCapabilityManageTenantSettings lets a key read and update
// tenant-scoped integration settings exposed under /tenants, such as API
// principal mode, request headers, and tenant KV. It does not include API
@@ -136,6 +145,10 @@ func NormalizeAPIKeyCapability(c APIKeyCapability) APIKeyCapability {
return APIKeyCapabilityManageWebSearch
case APIKeyCapabilityRunEvaluations:
return APIKeyCapabilityRunEvaluations
case APIKeyCapabilityManageMembers:
return APIKeyCapabilityManageMembers
case APIKeyCapabilityManageSpaces:
return APIKeyCapabilityManageSpaces
case APIKeyCapabilityManageTenantSettings:
return APIKeyCapabilityManageTenantSettings
default:
+3 -1
View File
@@ -80,10 +80,12 @@ func TestNormalizeAPIKeyCapabilities(t *testing.T) {
"manage_kbs",
"message_history",
"manage_mcp_services",
"manage_members",
"manage_spaces",
"bogus",
"",
})
want := []string{"retrieve", "chat", "read_agents", "manage_kbs", "message_history", "manage_mcp_services"}
want := []string{"retrieve", "chat", "read_agents", "manage_kbs", "message_history", "manage_mcp_services", "manage_members", "manage_spaces"}
if len(got) != len(want) {
t.Fatalf("normalized = %#v, want %#v", got, want)
}