Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

Refine scoped API key capabilities

wizardchen2c6f082062e7
diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.ts
index 09431ec42..994a12000 100644
--- a/frontend/src/api/tenant/index.ts
+++ b/frontend/src/api/tenant/index.ts
@@ -48,14 +48,46 @@ export interface APIPrincipalTestToken {
external_user_id: string
}
-export type TenantAPIKeyRole = 'viewer' | 'contributor' | 'admin' | 'owner'
+// Bounded per-key grants for non-full-access API keys.
+// - 'retrieve': read/search knowledge-base data within scope
+// - '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_agents': create/update/delete/copy agents
+// - 'message_history': search/read tenant chat-history metadata
+// - 'manage_models': manage tenant model definitions, checks, and credentials
+// - 'manage_mcp_services': manage MCP services, credentials, tool policies, and OAuth state
+// - 'manage_datasources': manage data-source connectors and sync jobs
+// - 'manage_channels': manage embed and IM channels
+// - 'manage_vector_stores': manage vector stores and parser/storage checks
+// - 'manage_web_search': manage web-search providers
+// - 'run_evaluations': run/read evaluation jobs
+// - 'manage_tenant_settings': read/update tenant integration settings (API principal mode, headers, tenant KV)
+export type TenantAPIKeyCapability =
+ | 'retrieve'
+ | 'chat'
+ | 'read_agents'
+ | 'ingest'
+ | 'manage_kbs'
+ | 'manage_agents'
+ | 'message_history'
+ | 'manage_models'
+ | 'manage_mcp_services'
+ | 'manage_datasources'
+ | 'manage_channels'
+ | 'manage_vector_stores'
+ | 'manage_web_search'
+ | 'run_evaluations'
+ | 'manage_tenant_settings'
export interface TenantAPIKey {
id: number
name: string
api_key: string
- role: TenantAPIKeyRole
+ full_access: boolean
knowledge_base_ids: string[]
+ capabilities?: TenantAPIKeyCapability[]
last_used_at?: string
expires_at?: string
created_at: string
@@ -67,8 +99,9 @@ export interface CreatedTenantAPIKey extends TenantAPIKey {
export interface CreateTenantAPIKeyPayload {
name: string
- role: TenantAPIKeyRole
+ full_access?: boolean
knowledge_base_ids?: string[]
+ capabilities?: TenantAPIKeyCapability[]
expires_at_unix?: number
}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 6d32ed0c1..380957da4 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5759,13 +5759,15 @@ export default {
apiKeys: 'API Keys',
apiKeysDesc: 'Create separate keys per integration and restrict operation permissions plus knowledge-base access.',
createApiKey: 'Create API Key',
- createApiKeyDialogDesc: 'Set the access role and available knowledge bases.',
+ createApiKeyDialogDesc: 'Choose capabilities and the knowledge-base scope this key may use.',
noApiKeys: 'No API keys',
apiKeyName: 'Name',
apiKeyValue: 'API Key',
apiKeyNamePlaceholder: 'Example: MCP read-only access',
apiKeyNameRequired: 'Enter an API key name',
toggleApiKeyVisible: 'Show or hide API key',
+ apiKeyAccessMode: 'Access mode',
+ apiKeyScopedAccess: 'Scoped access',
apiKeyAccessRole: "Access role",
apiKeyAccessType: "Access type",
apiKeyAccessTypeHint: "\"Knowledge base\" operates within the KB scope at the permission level below; \"Tenant full\" additionally unlocks every tenant-level API such as models and data sources.",
@@ -5780,10 +5782,48 @@ export default {
accessRoleViewerDesc: "Query, search, and chat without modifying knowledge-base content.",
accessRoleContributorDesc: "Create, update, or delete knowledge-base content within the selected scope.",
accessRoleAdminDesc: "Manage knowledge bases, including destructive operations like clearing a KB, within the selected scope; no tenant-level configuration.",
- accessRoleOwnerDesc: "Full access, equivalent to a tenant owner: may call every tenant-level API (models, vector stores, data sources, channels, ...). Not limited by knowledge-base scope.",
- apiKeyKnowledgeScope: 'Knowledge bases',
+ accessRoleOwnerDesc: "Full access, equivalent to a tenant owner: may call every tenant-level API (models, vector stores, data sources, channels, ...). Not limited by knowledge-base scope.",
+ apiKeyCapabilities: 'Capabilities',
+ apiKeyCapabilityGroupKnowledge: 'Knowledge-base data',
+ apiKeyCapabilityGroupAutomation: 'Agents and integrations',
+ apiKeyCapabilityGroupTenant: 'Tenant configuration',
+ apiKeyCapabilitySelectGroup: 'Select all',
+ apiKeyCapabilityClearGroup: 'Clear',
+ capabilityTenantFull: 'Tenant full access',
+ capabilityTenantFullHint: 'Allow every tenant-level API, including models, vector stores, data sources and channels. Knowledge-base scope does not apply.',
+ capabilityRetrieve: 'Retrieve knowledge bases',
+ capabilityRetrieveHint: 'Read, query, and search data inside the selected knowledge-base scope. Does not create sessions or modify content.',
+ capabilityChat: 'Chat',
+ capabilityChatHint: 'Let this key hold conversations and manage its own sessions. Does not modify knowledge-base content.',
+ capabilityReadAgents: 'Read agents',
+ capabilityReadAgentsHint: 'List agents, read agent details, presets, and suggested questions. Does not allow chat or agent edits.',
+ 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.',
+ 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',
+ capabilityMessageHistoryHint: 'Let this key search tenant chat history and read chat-history stats. It does not grant tenant configuration access.',
+ capabilityManageModels: 'Manage models',
+ capabilityManageModelsHint: 'Manage model definitions, credentials, connectivity checks, and WeKnoraCloud credentials.',
+ capabilityManageMcpServices: 'Manage MCP services',
+ capabilityManageMcpServicesHint: 'Manage MCP services, credentials, tool approval policies, and OAuth state for this principal.',
+ capabilityManageDatasources: 'Manage data sources',
+ capabilityManageDatasourcesHint: 'Manage data-source connectors, credentials, resource selection, and sync jobs. Knowledge-base scope still applies when a source is bound to a KB.',
+ capabilityManageChannels: 'Manage channels',
+ capabilityManageChannelsHint: 'Manage agent embed channels, IM channels, and WeChat QR binding flows.',
+ capabilityManageVectorStores: 'Manage retrieval infrastructure',
+ capabilityManageVectorStoresHint: 'Manage vector-store configuration plus parser, document reader, and storage engine connectivity checks.',
+ capabilityManageWebSearch: 'Manage web search',
+ capabilityManageWebSearchHint: 'Manage web-search provider configurations, credentials, and connection tests.',
+ capabilityRunEvaluations: 'Run evaluations',
+ capabilityRunEvaluationsHint: 'Run evaluation jobs and read evaluation results.',
+ 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',
apiKeyKnowledgeScopePlaceholder: 'Leave empty to allow all knowledge bases',
- apiKeyKnowledgeScopeOwnerHint: 'Owner is a full-access key; the knowledge-base scope does not apply to it.',
+ apiKeyKnowledgeScopeOwnerHint: 'Full-access keys are not limited by knowledge-base scope.',
allKnowledgeBases: 'All knowledge bases',
createdAt: 'Created',
actions: 'Actions',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index b3bfd9b18..9937b1ac5 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5770,13 +5770,15 @@ export default {
apiKeys: "API Keys",
apiKeysDesc: "통합마다 별도 Key를 만들고 작업 권한 및 접근 가능한 지식베이스 범위를 제한합니다.",
createApiKey: "API Key 생성",
- createApiKeyDialogDesc: "접근 역할과 사용 가능한 지식베이스 범위를 설정하세요.",
+ createApiKeyDialogDesc: "이 API Key가 사용할 기능과 지식베이스 범위를 선택하세요.",
noApiKeys: "API Key 없음",
apiKeyName: "이름",
apiKeyValue: "API Key",
apiKeyNamePlaceholder: "예: MCP 읽기 전용",
apiKeyNameRequired: "API Key 이름을 입력하세요",
toggleApiKeyVisible: "API Key 표시 또는 숨기기",
+ apiKeyAccessMode: "접근 방식",
+ apiKeyScopedAccess: "범위 지정 접근",
apiKeyAccessRole: "접근 역할",
apiKeyAccessType: "접근 유형",
apiKeyAccessTypeHint: "\"지식베이스\"는 아래 권한 수준에 따라 지식베이스 범위 내에서 작동합니다. \"테넌트 전체 접근\"은 모델, 데이터 소스 등 모든 테넌트 수준 API를 추가로 사용할 수 있습니다.",
@@ -5791,10 +5793,48 @@ export default {
accessRoleViewerDesc: "조회, 검색 및 대화만 가능하며 지식베이스 내용은 수정하지 않습니다.",
accessRoleContributorDesc: "선택한 범위 내에서 지식베이스 콘텐츠를 생성, 수정 또는 삭제합니다.",
accessRoleAdminDesc: "선택한 범위 내에서 지식베이스를 관리하며, 지식베이스 비우기 등 파괴적 작업을 포함합니다. 테넌트 수준 설정은 다루지 않습니다.",
- accessRoleOwnerDesc: "전체 접근, 테넌트 소유자와 동일: 모델, 벡터 스토어, 데이터 소스, 채널 등 모든 테넌트 수준 API를 호출할 수 있으며 지식베이스 범위의 제한을 받지 않습니다.",
- apiKeyKnowledgeScope: "지식베이스 범위",
+ accessRoleOwnerDesc: "전체 접근, 테넌트 소유자와 동일: 모델, 벡터 스토어, 데이터 소스, 채널 등 모든 테넌트 수준 API를 호출할 수 있으며 지식베이스 범위의 제한을 받지 않습니다.",
+ apiKeyCapabilities: "사용 가능 기능",
+ apiKeyCapabilityGroupKnowledge: "지식베이스 데이터",
+ apiKeyCapabilityGroupAutomation: "에이전트 및 통합",
+ apiKeyCapabilityGroupTenant: "테넌트 설정",
+ apiKeyCapabilitySelectGroup: "전체 선택",
+ apiKeyCapabilityClearGroup: "비우기",
+ capabilityTenantFull: "테넌트 전체 접근",
+ capabilityTenantFullHint: "모델, 벡터 스토어, 데이터 소스, 채널 등 모든 테넌트 수준 API를 허용합니다. 지식베이스 범위는 적용되지 않습니다.",
+ capabilityRetrieve: "지식베이스 검색",
+ capabilityRetrieveHint: "선택한 지식베이스 범위 내 데이터를 읽고 조회하고 검색할 수 있습니다. 세션을 만들거나 콘텐츠를 수정하지 않습니다.",
+ capabilityChat: "대화 기능",
+ capabilityChatHint: "이 키로 대화를 시작하고 자체 세션을 관리할 수 있습니다. 지식베이스 콘텐츠는 수정하지 않습니다.",
+ capabilityReadAgents: "에이전트 읽기",
+ capabilityReadAgentsHint: "에이전트 목록, 상세 정보, 프리셋 및 추천 질문을 읽을 수 있습니다. 대화 시작이나 에이전트 수정은 허용하지 않습니다.",
+ capabilityIngest: "지식베이스 콘텐츠 쓰기",
+ capabilityIngestHint: "허용된 지식베이스에 콘텐츠를 작성할 수 있습니다(문서 업로드, 청크/FAQ/태그/wiki 편집). 지식베이스나 에이전트를 새로 만들 수 없고, 지식베이스를 비울 수 없으며, 선택한 지식베이스 범위로 제한됩니다.",
+ capabilityManageKbs: "지식베이스 관리",
+ capabilityManageKbsHint: "선택한 범위 안에서 기존 지식베이스를 수정 또는 삭제하고 초기화/설정을 변경할 수 있습니다. 새 지식베이스 생성은 허용하지 않습니다.",
+ capabilityManageAgents: "에이전트 관리",
+ capabilityManageAgentsHint: "에이전트를 생성, 수정, 삭제, 복사할 수 있습니다. 에이전트 설정에는 모델/MCP 등 민감한 바인딩이 포함될 수 있으므로 기본적으로 꺼져 있으며 필요할 때만 켜세요.",
+ capabilityMessageHistory: "메시지 기록",
+ capabilityMessageHistoryHint: "테넌트 채팅 기록 검색과 채팅 기록 통계 조회를 허용합니다. 테넌트 설정 권한은 부여하지 않습니다.",
+ capabilityManageModels: "모델 관리",
+ capabilityManageModelsHint: "모델 설정, 자격 증명, 연결 테스트 및 WeKnoraCloud 자격 증명을 관리합니다.",
+ capabilityManageMcpServices: "MCP 서비스 관리",
+ capabilityManageMcpServicesHint: "MCP 서비스, 자격 증명, 도구 승인 정책 및 이 주체의 OAuth 상태를 관리합니다.",
+ capabilityManageDatasources: "데이터 소스 관리",
+ capabilityManageDatasourcesHint: "데이터 소스 커넥터, 자격 증명, 리소스 선택 및 동기화 작업을 관리합니다. 지식베이스에 연결된 경우 범위 제한은 계속 적용됩니다.",
+ capabilityManageChannels: "채널 관리",
+ capabilityManageChannelsHint: "에이전트 임베드 채널, IM 채널 및 WeChat QR 바인딩 흐름을 관리합니다.",
+ capabilityManageVectorStores: "검색 인프라 관리",
+ capabilityManageVectorStoresHint: "벡터 스토어 설정과 파서, 문서 리더, 스토리지 엔진 연결 검사를 관리합니다.",
+ capabilityManageWebSearch: "웹 검색 관리",
+ capabilityManageWebSearchHint: "웹 검색 공급자 설정, 자격 증명 및 연결 테스트를 관리합니다.",
+ capabilityRunEvaluations: "평가 실행",
+ capabilityRunEvaluationsHint: "평가 작업을 실행하고 결과를 읽을 수 있습니다.",
+ capabilityManageTenantSettings: "테넌트 설정 관리",
+ capabilityManageTenantSettingsHint: "API 최종 사용자 식별 모드, 요청 헤더 설정, 테넌트 KV 설정 등 테넌트 수준 통합 설정을 읽고 업데이트합니다. API Key 관리, 멤버 관리, 테넌트 삭제 또는 소유권 이전은 포함하지 않습니다.",
+ apiKeyKnowledgeScope: "지식베이스 범위",
apiKeyKnowledgeScopePlaceholder: "비워 두면 모든 지식베이스 접근 허용",
- apiKeyKnowledgeScopeOwnerHint: "소유자는 전체 접근 키이므로 지식베이스 범위가 적용되지 않습니다.",
+ apiKeyKnowledgeScopeOwnerHint: "전체 접근 키는 지식베이스 범위로 제한되지 않습니다.",
allKnowledgeBases: "모든 지식베이스",
createdAt: "생성일",
actions: "작업",
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 9f3eec6b8..c08da4d5a 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5591,13 +5591,15 @@ export default {
apiKeys: 'API Keys',
apiKeysDesc: 'Создавайте отдельные ключи для интеграций и ограничивайте права операций и доступ к базам знаний.',
createApiKey: 'Создать API Key',
- createApiKeyDialogDesc: 'Укажите роль доступа и доступные базы знаний.',
+ createApiKeyDialogDesc: 'Выберите возможности ключа и доступный диапазон баз знаний.',
noApiKeys: 'Нет API keys',
apiKeyName: 'Название',
apiKeyValue: 'API Key',
apiKeyNamePlaceholder: 'Например: MCP только чтение',
apiKeyNameRequired: 'Введите название API key',
toggleApiKeyVisible: 'Показать или скрыть API key',
+ apiKeyAccessMode: 'Режим доступа',
+ apiKeyScopedAccess: 'Ограниченный доступ',
apiKeyAccessRole: 'Роль доступа',
apiKeyAccessType: 'Тип доступа',
apiKeyAccessTypeHint: '«База знаний» работает в пределах области БЗ на выбранном ниже уровне прав; «Полный доступ арендатора» дополнительно открывает все API уровня арендатора, такие как модели и источники данных.',
@@ -5612,10 +5614,48 @@ export default {
accessRoleViewerDesc: 'Запросы, поиск и диалог без изменения содержимого баз знаний.',
accessRoleContributorDesc: 'Создание, обновление или удаление записей в выбранном диапазоне баз знаний.',
accessRoleAdminDesc: 'Управление базами знаний в выбранном диапазоне, включая деструктивные операции, такие как очистка базы знаний; настройки уровня арендатора недоступны.',
- accessRoleOwnerDesc: 'Полный доступ, эквивалент владельца арендатора: доступны все API уровня арендатора (модели, векторные хранилища, источники данных, каналы, ...). Не ограничивается диапазоном баз знаний.',
- apiKeyKnowledgeScope: 'Базы знаний',
+ accessRoleOwnerDesc: 'Полный доступ, эквивалент владельца арендатора: доступны все API уровня арендатора (модели, векторные хранилища, источники данных, каналы, ...). Не ограничивается диапазоном баз знаний.',
+ apiKeyCapabilities: 'Возможности',
+ apiKeyCapabilityGroupKnowledge: 'Данные баз знаний',
+ apiKeyCapabilityGroupAutomation: 'Агенты и интеграции',
+ apiKeyCapabilityGroupTenant: 'Настройки арендатора',
+ apiKeyCapabilitySelectGroup: 'Выбрать всё',
+ apiKeyCapabilityClearGroup: 'Очистить',
+ capabilityTenantFull: 'Полный доступ арендатора',
+ capabilityTenantFullHint: 'Разрешает все API уровня арендатора, включая модели, векторные хранилища, источники данных и каналы. Диапазон баз знаний не применяется.',
+ capabilityRetrieve: 'Поиск в базах знаний',
+ capabilityRetrieveHint: 'Чтение, запросы и поиск данных в выбранном диапазоне баз знаний. Не создаёт сессии и не изменяет содержимое.',
+ capabilityChat: 'Диалог',
+ capabilityChatHint: 'Позволяет этому ключу вести диалог и управлять собственными сессиями. Не изменяет содержимое баз знаний.',
+ capabilityReadAgents: 'Чтение агентов',
+ capabilityReadAgentsHint: 'Список агентов, детали, пресеты и предлагаемые вопросы. Не разрешает диалог или изменение агентов.',
+ capabilityIngest: 'Запись в базы знаний',
+ capabilityIngestHint: 'Позволяет ключу записывать содержимое в разрешённые базы знаний (загрузка документов, редактирование фрагментов/FAQ/тегов/wiki). Нельзя создавать базы знаний или агентов, нельзя очищать базу знаний; действие ограничено выбранными базами знаний.',
+ capabilityManageKbs: 'Управление базами знаний',
+ capabilityManageKbsHint: 'Позволяет обновлять или удалять существующие базы знаний и менять их конфигурацию в выбранной области. Не разрешает создавать новые базы знаний.',
+ capabilityManageAgents: 'Управление агентами',
+ capabilityManageAgentsHint: 'Позволяет создавать, изменять, удалять и копировать агентов. Конфигурация агента может содержать чувствительные привязки моделей/MCP, поэтому по умолчанию отключено — включайте только при необходимости.',
+ capabilityMessageHistory: 'История сообщений',
+ capabilityMessageHistoryHint: 'Позволяет искать историю чатов арендатора и читать статистику истории. Не даёт доступ к настройкам арендатора.',
+ capabilityManageModels: 'Управление моделями',
+ capabilityManageModelsHint: 'Управление конфигурациями моделей, учётными данными, проверками подключения и данными WeKnoraCloud.',
+ capabilityManageMcpServices: 'Управление MCP-сервисами',
+ capabilityManageMcpServicesHint: 'Управление MCP-сервисами, учётными данными, политиками подтверждения инструментов и OAuth-состоянием этого субъекта.',
+ capabilityManageDatasources: 'Управление источниками данных',
+ capabilityManageDatasourcesHint: 'Управление коннекторами, учётными данными, выбором ресурсов и синхронизацией. Для привязанных баз знаний диапазон всё равно применяется.',
+ capabilityManageChannels: 'Управление каналами',
+ capabilityManageChannelsHint: 'Управление embed-каналами агентов, IM-каналами и привязкой WeChat через QR-код.',
+ capabilityManageVectorStores: 'Управление инфраструктурой поиска',
+ capabilityManageVectorStoresHint: 'Управление векторными хранилищами и проверками парсеров, чтения документов и storage engine.',
+ capabilityManageWebSearch: 'Управление веб-поиском',
+ capabilityManageWebSearchHint: 'Управление провайдерами веб-поиска, учётными данными и проверками подключения.',
+ capabilityRunEvaluations: 'Запуск оценок',
+ capabilityRunEvaluationsHint: 'Запуск задач оценки и чтение результатов.',
+ capabilityManageTenantSettings: 'Управление настройками арендатора',
+ capabilityManageTenantSettingsHint: 'Чтение и обновление интеграционных настроек арендатора: режим идентификации конечного пользователя API, настройки заголовков запросов и tenant KV. Не включает управление API Key, участниками, удаление арендатора или передачу владения.',
+ apiKeyKnowledgeScope: 'Базы знаний',
apiKeyKnowledgeScopePlaceholder: 'Оставьте пустым, чтобы разрешить доступ ко всем базам знаний',
- apiKeyKnowledgeScopeOwnerHint: 'Владелец — это ключ с полным доступом; диапазон баз знаний к нему не применяется.',
+ apiKeyKnowledgeScopeOwnerHint: 'Ключи с полным доступом не ограничиваются диапазоном баз знаний.',
allKnowledgeBases: 'Все базы знаний',
createdAt: 'Создано',
actions: 'Действия',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 1306688be..3de698096 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5772,13 +5772,15 @@ export default {
apiKeys: "API Keys",
apiKeysDesc: "为不同集成创建独立 Key,并限制操作权限与可访问知识库范围。",
createApiKey: "创建 API Key",
- createApiKeyDialogDesc: "设置访问角色和可用知识库范围。",
+ createApiKeyDialogDesc: "选择该 API Key 可用的能力和知识库范围。",
noApiKeys: "暂无 API Key",
apiKeyName: "名称",
apiKeyValue: "API Key",
apiKeyNamePlaceholder: "例如:MCP 只读访问",
apiKeyNameRequired: "请输入 API Key 名称",
toggleApiKeyVisible: "显示或隐藏 API Key",
+ apiKeyAccessMode: "授权方式",
+ apiKeyScopedAccess: "能力授权",
apiKeyAccessRole: "访问角色",
apiKeyAccessType: "访问类型",
apiKeyAccessTypeHint: "「知识库」按下方权限级别在知识库范围内操作;「租户完全访问」额外开放模型、数据源等全部租户级接口。",
@@ -5793,10 +5795,48 @@ export default {
accessRoleViewerDesc: "查询、检索和对话,不修改知识库内容。",
accessRoleContributorDesc: "创建、更新或删除知识库内容,受知识库范围限制。",
accessRoleAdminDesc: "知识库管理,包含清空知识库等破坏性操作,受知识库范围限制;不涉及租户级配置。",
- accessRoleOwnerDesc: "完全访问,等同租户所有者:可调用模型、向量库、数据源、渠道等全部租户级接口,不受知识库范围限制。",
- apiKeyKnowledgeScope: "知识库范围",
+ accessRoleOwnerDesc: "完全访问,等同租户所有者:可调用模型、向量库、数据源、渠道等全部租户级接口,不受知识库范围限制。",
+ apiKeyCapabilities: "可用能力",
+ apiKeyCapabilityGroupKnowledge: "知识库数据",
+ apiKeyCapabilityGroupAutomation: "智能体与集成",
+ apiKeyCapabilityGroupTenant: "租户配置",
+ apiKeyCapabilitySelectGroup: "全选",
+ apiKeyCapabilityClearGroup: "清空",
+ capabilityTenantFull: "租户完全访问",
+ capabilityTenantFullHint: "允许调用模型、向量库、数据源、渠道等全部租户级接口;知识库范围不再生效。",
+ capabilityRetrieve: "检索知识库",
+ capabilityRetrieveHint: "允许读取、查询和检索所选知识库范围内的数据;不创建会话,也不修改内容。",
+ capabilityChat: "对话能力",
+ capabilityChatHint: "允许该密钥发起对话并管理自己的会话;不修改知识库内容。",
+ capabilityReadAgents: "读取智能体",
+ capabilityReadAgentsHint: "允许列出智能体、查看智能体详情、读取智能体预设和建议问题;不允许发起对话或修改智能体。",
+ capabilityIngest: "写入知识库内容",
+ capabilityIngestHint: "允许向授权范围内的知识库写入内容(上传文档、编辑分块/FAQ/标签/wiki);不能新建知识库、不能新建智能体、不能清空知识库,且仅限所选知识库范围。",
+ capabilityManageKbs: "管理知识库",
+ capabilityManageKbsHint: "允许在所选知识库范围内修改或删除已有知识库,并调整初始化/配置信息;不允许新建知识库。",
+ capabilityManageAgents: "管理智能体",
+ capabilityManageAgentsHint: "允许创建、修改、删除、复制智能体。智能体配置可能含模型/MCP 等敏感绑定,默认关闭,按需开启。",
+ capabilityMessageHistory: "消息历史",
+ capabilityMessageHistoryHint: "允许检索租户聊天历史并读取聊天历史统计;不授予租户配置权限。",
+ capabilityManageModels: "管理模型",
+ capabilityManageModelsHint: "允许管理模型配置、模型凭据、模型连通性测试和 WeKnoraCloud 凭据。",
+ capabilityManageMcpServices: "管理 MCP 服务",
+ capabilityManageMcpServicesHint: "允许管理 MCP 服务、凭据、工具审批策略和该主体的 OAuth 授权状态。",
+ capabilityManageDatasources: "管理数据源",
+ capabilityManageDatasourcesHint: "允许管理数据源连接器、凭据、资源选择和同步任务;绑定知识库时仍受知识库范围限制。",
+ capabilityManageChannels: "管理渠道",
+ capabilityManageChannelsHint: "允许管理智能体的嵌入渠道、IM 渠道和微信扫码绑定流程。",
+ capabilityManageVectorStores: "管理检索基础设施",
+ capabilityManageVectorStoresHint: "允许管理向量库配置,以及解析器、文档读取器和存储引擎连通性检查。",
+ capabilityManageWebSearch: "管理联网搜索",
+ capabilityManageWebSearchHint: "允许管理联网搜索供应商配置、凭据和连接测试。",
+ capabilityRunEvaluations: "运行评测",
+ capabilityRunEvaluationsHint: "允许运行评测任务并读取评测结果。",
+ capabilityManageTenantSettings: "管理租户设置",
+ capabilityManageTenantSettingsHint: "允许读取和更新租户级集成设置,例如 API 终端用户身份模式、请求头配置、租户 KV 配置等;不包含 API Key 管理、成员管理、租户删除或所有权转移。",
+ apiKeyKnowledgeScope: "知识库范围",
apiKeyKnowledgeScopePlaceholder: "留空表示允许访问全部知识库",
- apiKeyKnowledgeScopeOwnerHint: "所有者为完全访问密钥,知识库范围对其不生效。",
+ apiKeyKnowledgeScopeOwnerHint: "完全访问密钥不受知识库范围限制。",
allKnowledgeBases: "全部知识库",
createdAt: "创建时间",
actions: "操作",
diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vue
index 91a3a00e0..7f97108d8 100644
--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue
+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue
@@ -114,7 +114,7 @@
<tr>
<th>{{ $t('integrations.api.apiKeyName') }}</th>
<th>{{ $t('integrations.api.apiKeyValue') }}</th>
- <th>{{ $t('integrations.api.apiKeyAccessRole') }}</th>
+ <th>{{ $t('integrations.api.apiKeyAccessMode') }}</th>
<th>{{ $t('integrations.api.apiKeyKnowledgeScope') }}</th>
<th>{{ $t('integrations.api.createdAt') }}</th>
<th class="api-key-table__actions-heading">{{ $t('integrations.api.actions') }}</th>
@@ -129,9 +129,23 @@
<code class="api-key-fingerprint">{{ formatKeyMaskedValue(key) }}</code>
</td>
<td>
- <t-tag size="small" variant="light">
- {{ formatApiKeyAccessRoleLabel(key.role) }}
- </t-tag>
+ <div class="api-key-access-cell" :title="formatApiKeyCapabilitiesTitle(key)">
+ <span
+ v-if="key.full_access"
+ class="api-key-access-mode api-key-access-mode--full"
+ >
+ {{ formatApiKeyAccessModeLabel(key) }}
+ </span>
+ <div v-if="!key.full_access" class="api-key-capability-chips">
+ <span
+ v-for="label in keyCapabilityLabels(key)"
+ :key="label"
+ class="api-key-capability-chip"
+ >
+ {{ label }}
+ </span>
+ </div>
+ </div>
</td>
<td>
<span class="api-key-knowledge-scope">
@@ -427,26 +441,22 @@
</section>
</SettingDrawer>
- <t-dialog
- v-model:visible="apiKeyDialogVisible"
- :footer="false"
- width="450px"
- dialog-class-name="api-key-create-dialog"
+ <SettingDrawer
+ :visible="apiKeyDialogVisible"
+ class="api-key-create-drawer"
+ :title="$t('integrations.api.createApiKey')"
+ :description="$t('integrations.api.createApiKeyDialogDesc')"
+ icon="lock-on"
+ width="560px"
+ :min-width="480"
+ :max-width="920"
+ storage-key="setting-drawer:width:api-key-create"
:close-on-overlay-click="false"
- destroy-on-close
+ :confirm-text="$t('integrations.api.createApiKey')"
+ :confirm-loading="apiKeyCreating"
+ @update:visible="(v: boolean) => apiKeyDialogVisible = v"
+ @confirm="createScopedAPIKey"
>
- <template #header>
- <div class="api-key-create-heading">
- <div class="api-key-create-heading-row">
- <span class="api-key-create-heading-mark">
- <t-icon name="lock-on" size="16px" aria-hidden="true" />
- </span>
- <span class="api-key-create-title">{{ $t('integrations.api.createApiKey') }}</span>
- </div>
- <p class="api-key-create-desc">{{ $t('integrations.api.createApiKeyDialogDesc') }}</p>
- </div>
- </template>
-
<div class="api-key-dialog">
<div class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
@@ -462,32 +472,63 @@
<div class="api-key-dialog-row__label">
<label>{{ $t('integrations.api.apiKeyAccessType') }}</label>
</div>
- <t-radio-group v-model="apiKeyAccessType" class="mode-radio api-key-role-radio">
- <t-radio-button value="kb">{{ $t('integrations.api.accessTypeKnowledgeBase') }}</t-radio-button>
- <t-radio-button value="tenant">{{ $t('integrations.api.accessTypeTenantFull') }}</t-radio-button>
+ <t-radio-group v-model="apiKeyAccessMode" class="mode-radio api-key-access-type-radio">
+ <t-radio-button value="scoped">{{ $t('integrations.api.apiKeyScopedAccess') }}</t-radio-button>
+ <t-radio-button value="full">{{ $t('integrations.api.capabilityTenantFull') }}</t-radio-button>
</t-radio-group>
- <p class="scope-role-hint">{{ $t('integrations.api.apiKeyAccessTypeHint') }}</p>
+ <p class="scope-hint">
+ {{
+ apiKeyFullAccessEnabled
+ ? $t('integrations.api.capabilityTenantFullHint')
+ : $t('integrations.api.apiKeyAccessTypeHint')
+ }}
+ </p>
</div>
- <div v-if="!apiKeyRoleIsOwner" class="api-key-dialog-row">
+ <div v-if="!apiKeyFullAccessEnabled" class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
- <label>{{ $t('integrations.api.apiKeyPermissionLevel') }}</label>
+ <label>{{ $t('integrations.api.apiKeyCapabilities') }}</label>
</div>
- <t-radio-group v-model="apiKeyForm.role" class="mode-radio api-key-role-radio">
- <t-radio-button value="viewer">{{ $t('integrations.api.accessRoleViewer') }}</t-radio-button>
- <t-radio-button value="contributor">{{ $t('integrations.api.accessRoleContributor') }}</t-radio-button>
- <t-radio-button value="admin">{{ $t('integrations.api.accessRoleAdmin') }}</t-radio-button>
- </t-radio-group>
- </div>
-
- <div class="api-key-dialog-row api-key-dialog-row--help">
- <div class="scope-help scope-help--role">
- <p class="scope-help__role">{{ formatApiKeyAccessRoleLabel(apiKeyForm.role) }}</p>
- <p class="scope-help__desc">{{ apiKeyFormRoleDesc }}</p>
+ <div v-if="!apiKeyFullAccessEnabled" class="api-key-capability-list">
+ <div
+ v-for="group in apiKeyCapabilityGroups"
+ :key="group.key"
+ class="api-key-capability-group"
+ >
+ <div class="api-key-capability-group__header">
+ <span>{{ $t(group.labelKey) }}</span>
+ <t-button
+ size="small"
+ variant="text"
+ @click="toggleCapabilityGroup(group, !capabilityGroupAllSelected(group))"
+ >
+ {{
+ capabilityGroupAllSelected(group)
+ ? $t('integrations.api.apiKeyCapabilityClearGroup')
+ : $t('integrations.api.apiKeyCapabilitySelectGroup')
+ }}
+ </t-button>
+ </div>
+ <div class="api-key-capability-group__items">
+ <div
+ v-for="capability in group.capabilities"
+ :key="capability.value"
+ class="api-key-capability-item"
+ >
+ <t-checkbox
+ :model-value="capabilitySelections[capability.value]"
+ @change="handleCapabilityChange(capability.value, $event)"
+ >
+ {{ $t(capability.labelKey) }}
+ </t-checkbox>
+ <p class="scope-hint">{{ $t(capability.hintKey) }}</p>
+ </div>
+ </div>
+ </div>
</div>
</div>
- <div v-if="!apiKeyRoleIsOwner" class="api-key-dialog-row">
+ <div v-if="apiKeyKnowledgeScopeApplies" class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
<label>{{ $t('integrations.api.apiKeyKnowledgeScope') }}</label>
</div>
@@ -502,18 +543,7 @@
/>
</div>
</div>
-
- <div class="api-key-create-footer">
- <div class="api-key-create-footer__actions">
- <t-button variant="outline" size="small" @click="apiKeyDialogVisible = false">
- {{ $t('common.cancel') }}
- </t-button>
- <t-button theme="primary" size="small" :loading="apiKeyCreating" @click="createScopedAPIKey">
- {{ $t('integrations.api.createApiKey') }}
- </t-button>
- </div>
- </div>
- </t-dialog>
+ </SettingDrawer>
</div>
</template>
@@ -535,7 +565,7 @@ import {
type APIPrincipalConfig,
type APIPrincipalMode,
type TenantAPIKey,
- type TenantAPIKeyRole,
+ type TenantAPIKeyCapability,
} from '@/api/tenant'
import { listKnowledgeBases } from '@/api/knowledge-base'
import { getApiBaseUrl } from '@/utils/api-base'
@@ -580,66 +610,180 @@ const form = reactive({
require_direct_header: false,
})
-type ApiKeyAccessRole = 'viewer' | 'contributor' | 'admin' | 'owner'
+type ApiKeyCapabilityOption = {
+ value: TenantAPIKeyCapability
+ labelKey: string
+ hintKey: string
+}
+type ApiKeyCapabilityGroup = {
+ key: string
+ labelKey: string
+ capabilities: ApiKeyCapabilityOption[]
+}
+
+const API_KEY_CAPABILITIES: TenantAPIKeyCapability[] = [
+ 'retrieve',
+ 'chat',
+ 'read_agents',
+ 'ingest',
+ 'manage_kbs',
+ 'message_history',
+ 'manage_agents',
+ 'manage_mcp_services',
+ 'manage_datasources',
+ 'manage_models',
+ 'manage_vector_stores',
+ 'manage_web_search',
+ 'manage_channels',
+ 'run_evaluations',
+ 'manage_tenant_settings',
+]
+
+const DEFAULT_API_KEY_CAPABILITIES = new Set<TenantAPIKeyCapability>(['retrieve', 'chat', 'read_agents'])
+const KB_SCOPED_CAPABILITIES = new Set<TenantAPIKeyCapability>([
+ 'retrieve',
+ 'chat',
+ 'ingest',
+ 'manage_kbs',
+ 'manage_agents',
+ 'manage_datasources',
+])
+
+const apiKeyCapabilityGroups: ApiKeyCapabilityGroup[] = [
+ {
+ key: 'knowledge',
+ labelKey: 'integrations.api.apiKeyCapabilityGroupKnowledge',
+ capabilities: [
+ { value: 'retrieve', labelKey: 'integrations.api.capabilityRetrieve', hintKey: 'integrations.api.capabilityRetrieveHint' },
+ { value: 'chat', labelKey: 'integrations.api.capabilityChat', hintKey: 'integrations.api.capabilityChatHint' },
+ { value: 'ingest', labelKey: 'integrations.api.capabilityIngest', hintKey: 'integrations.api.capabilityIngestHint' },
+ { value: 'manage_kbs', labelKey: 'integrations.api.capabilityManageKbs', hintKey: 'integrations.api.capabilityManageKbsHint' },
+ { value: 'message_history', labelKey: 'integrations.api.capabilityMessageHistory', hintKey: 'integrations.api.capabilityMessageHistoryHint' },
+ ],
+ },
+ {
+ key: 'automation',
+ labelKey: 'integrations.api.apiKeyCapabilityGroupAutomation',
+ capabilities: [
+ { value: 'read_agents', labelKey: 'integrations.api.capabilityReadAgents', hintKey: 'integrations.api.capabilityReadAgentsHint' },
+ { value: 'manage_agents', labelKey: 'integrations.api.capabilityManageAgents', hintKey: 'integrations.api.capabilityManageAgentsHint' },
+ { value: 'manage_mcp_services', labelKey: 'integrations.api.capabilityManageMcpServices', hintKey: 'integrations.api.capabilityManageMcpServicesHint' },
+ { value: 'manage_datasources', labelKey: 'integrations.api.capabilityManageDatasources', hintKey: 'integrations.api.capabilityManageDatasourcesHint' },
+ ],
+ },
+ {
+ key: 'tenant',
+ labelKey: 'integrations.api.apiKeyCapabilityGroupTenant',
+ capabilities: [
+ { value: 'manage_models', labelKey: 'integrations.api.capabilityManageModels', hintKey: 'integrations.api.capabilityManageModelsHint' },
+ { value: 'manage_vector_stores', labelKey: 'integrations.api.capabilityManageVectorStores', hintKey: 'integrations.api.capabilityManageVectorStoresHint' },
+ { value: 'manage_web_search', labelKey: 'integrations.api.capabilityManageWebSearch', hintKey: 'integrations.api.capabilityManageWebSearchHint' },
+ { value: 'manage_channels', labelKey: 'integrations.api.capabilityManageChannels', hintKey: 'integrations.api.capabilityManageChannelsHint' },
+ { value: 'run_evaluations', labelKey: 'integrations.api.capabilityRunEvaluations', hintKey: 'integrations.api.capabilityRunEvaluationsHint' },
+ { value: 'manage_tenant_settings', labelKey: 'integrations.api.capabilityManageTenantSettings', hintKey: 'integrations.api.capabilityManageTenantSettingsHint' },
+ ],
+ },
+]
+
+const capabilitySelections = reactive<Record<TenantAPIKeyCapability, boolean>>(
+ API_KEY_CAPABILITIES.reduce((acc, capability) => {
+ acc[capability] = DEFAULT_API_KEY_CAPABILITIES.has(capability)
+ return acc
+ }, {} as Record<TenantAPIKeyCapability, boolean>),
+)
const apiKeyForm = reactive({
name: '',
- role: 'viewer' as ApiKeyAccessRole,
knowledge_base_ids: [] as string[],
+ // Tenant-full keys already cover every capability. Scoped keys default to
+ // retrieval + chat + agent reads so a fresh integration can ask questions
+ // and present an agent picker immediately.
+ tenant_full_enabled: false,
})
-// The role picker is presented as two levels: a top-level access type
-// (knowledge-base vs. full tenant) and, for knowledge-base keys, a permission
-// level (viewer/contributor/admin). Owner is a full-access key, for which the
-// KB scope is meaningless and hidden.
-const apiKeyRoleIsOwner = computed(() => apiKeyForm.role === 'owner')
-type ApiKeyAccessType = 'kb' | 'tenant'
-const apiKeyAccessType = ref<ApiKeyAccessType>('kb')
-// Remember the last knowledge-base permission level so toggling back from
-// "tenant full" restores the user's previous choice instead of resetting.
-let lastKbRole: ApiKeyAccessRole = 'viewer'
-
-watch(apiKeyAccessType, (type) => {
- if (type === 'tenant') {
- apiKeyForm.role = 'owner'
+const apiKeyFullAccessEnabled = computed(() => apiKeyForm.tenant_full_enabled)
+const apiKeyAccessMode = computed<'scoped' | 'full'>({
+ get: () => (apiKeyForm.tenant_full_enabled ? 'full' : 'scoped'),
+ set: (value) => {
+ apiKeyForm.tenant_full_enabled = value === 'full'
+ },
+})
+const selectedCapabilityValues = computed(() => API_KEY_CAPABILITIES.filter((capability) => capabilitySelections[capability]))
+const apiKeyKnowledgeScopeApplies = computed(() => (
+ !apiKeyFullAccessEnabled.value
+ && selectedCapabilityValues.value.some((capability) => KB_SCOPED_CAPABILITIES.has(capability))
+))
+
+watch(() => apiKeyForm.tenant_full_enabled, (enabled) => {
+ if (enabled) {
apiKeyForm.knowledge_base_ids = []
- } else if (apiKeyForm.role === 'owner') {
- apiKeyForm.role = lastKbRole === 'owner' ? 'viewer' : lastKbRole
}
})
-watch(
- () => apiKeyForm.role,
- (role) => {
- if (role !== 'owner') {
- lastKbRole = role
- }
- },
-)
-
-function formatApiKeyAccessRoleLabel(role: ApiKeyAccessRole | TenantAPIKeyRole | undefined): string {
- const normalized = (role ?? 'viewer') as ApiKeyAccessRole
- const labels: Record<ApiKeyAccessRole, string> = {
- viewer: t('integrations.api.accessRoleViewer'),
- contributor: t('integrations.api.accessRoleContributor'),
- admin: t('integrations.api.accessRoleAdmin'),
- owner: t('integrations.api.accessRoleOwner'),
+watch(apiKeyKnowledgeScopeApplies, (applies) => {
+ if (!applies) {
+ apiKeyForm.knowledge_base_ids = []
}
- return labels[normalized] ?? labels.viewer
+})
+
+function selectedCapabilities(): TenantAPIKeyCapability[] {
+ return selectedCapabilityValues.value
+}
+
+function setCapabilitySelected(capability: TenantAPIKeyCapability, selected: boolean) {
+ capabilitySelections[capability] = selected
}
-const apiKeyFormRoleDesc = computed(() => {
- switch (apiKeyForm.role) {
- case 'owner':
- return t('integrations.api.accessRoleOwnerDesc')
- case 'admin':
- return t('integrations.api.accessRoleAdminDesc')
- case 'contributor':
- return t('integrations.api.accessRoleContributorDesc')
- default:
- return t('integrations.api.accessRoleViewerDesc')
+function handleCapabilityChange(capability: TenantAPIKeyCapability, checked: unknown) {
+ setCapabilitySelected(capability, Boolean(checked))
+}
+
+function capabilityGroupAllSelected(group: ApiKeyCapabilityGroup): boolean {
+ return group.capabilities.every((capability) => capabilitySelections[capability.value])
+}
+
+function toggleCapabilityGroup(group: ApiKeyCapabilityGroup, selected: boolean) {
+ group.capabilities.forEach((capability) => {
+ capabilitySelections[capability.value] = selected
+ })
+}
+
+// Full-access keys already cover every capability, so no capability badges for them.
+function keyCapabilityLabels(key: TenantAPIKey): string[] {
+ if (key.full_access) return []
+ const labels: Record<TenantAPIKeyCapability, string> = {
+ retrieve: t('integrations.api.capabilityRetrieve'),
+ chat: t('integrations.api.capabilityChat'),
+ read_agents: t('integrations.api.capabilityReadAgents'),
+ ingest: t('integrations.api.capabilityIngest'),
+ manage_kbs: t('integrations.api.capabilityManageKbs'),
+ manage_agents: t('integrations.api.capabilityManageAgents'),
+ message_history: t('integrations.api.capabilityMessageHistory'),
+ manage_models: t('integrations.api.capabilityManageModels'),
+ manage_mcp_services: t('integrations.api.capabilityManageMcpServices'),
+ manage_datasources: t('integrations.api.capabilityManageDatasources'),
+ manage_channels: t('integrations.api.capabilityManageChannels'),
+ manage_vector_stores: t('integrations.api.capabilityManageVectorStores'),
+ manage_web_search: t('integrations.api.capabilityManageWebSearch'),
+ run_evaluations: t('integrations.api.capabilityRunEvaluations'),
+ manage_tenant_settings: t('integrations.api.capabilityManageTenantSettings'),
}
-})
+ return (key.capabilities ?? [])
+ .map((c) => labels[c])
+ .filter((label): label is string => Boolean(label))
+}
+
+function formatApiKeyCapabilitiesTitle(key: TenantAPIKey): string {
+ if (key.full_access) return t('integrations.api.capabilityTenantFull')
+ const labels = keyCapabilityLabels(key)
+ return labels.length > 0 ? labels.join(' / ') : t('integrations.api.apiKeyScopedAccess')
+}
+
+function formatApiKeyAccessModeLabel(key: TenantAPIKey): string {
+ return key.full_access
+ ? t('integrations.api.capabilityTenantFull')
+ : t('integrations.api.apiKeyScopedAccess')
+}
type PlaygroundStatus = '' | 'running' | 'success' | 'failed' | 'stopped'
@@ -1170,10 +1314,11 @@ function openApiDoc() {
function openCreateAPIKeyDialog() {
apiKeyForm.name = ''
- apiKeyForm.role = 'viewer'
apiKeyForm.knowledge_base_ids = []
- apiKeyAccessType.value = 'kb'
- lastKbRole = 'viewer'
+ apiKeyForm.tenant_full_enabled = false
+ API_KEY_CAPABILITIES.forEach((capability) => {
+ capabilitySelections[capability] = DEFAULT_API_KEY_CAPABILITIES.has(capability)
+ })
apiKeyDialogVisible.value = true
void loadKnowledgeBaseOptions()
}
@@ -1187,9 +1332,11 @@ async function createScopedAPIKey() {
try {
const resp = await createTenantAPIKey(tenantId.value, {
name: apiKeyForm.name.trim(),
- role: apiKeyForm.role,
- // Owner keys are full-access; KB scoping does not apply to them.
- knowledge_base_ids: apiKeyRoleIsOwner.value ? [] : apiKeyForm.knowledge_base_ids,
+ full_access: apiKeyFullAccessEnabled.value,
+ // KB scoping only applies to capabilities that touch knowledge bases.
+ knowledge_base_ids: apiKeyKnowledgeScopeApplies.value ? apiKeyForm.knowledge_base_ids : [],
+ // Capabilities only matter below full access; full access already covers them all.
+ capabilities: apiKeyFullAccessEnabled.value ? [] : selectedCapabilities(),
})
if (!resp.success || !resp.data?.api_key) {
throw new Error(resp.message || t('integrations.api.createApiKeyFailed'))
@@ -1438,44 +1585,6 @@ onMounted(async () => {
onBeforeUnmount(stopPlayground)
</script>
-<style lang="less">
-.api-key-create-dialog {
- overflow: hidden;
- padding: 0;
- border-radius: 4px;
-}
-
-.api-key-create-dialog .t-dialog__header {
- min-height: auto;
- padding: 20px 20px 0;
-}
-
-.api-key-create-dialog .t-dialog__body {
- padding: 0 20px 20px;
-}
-
-.api-key-create-dialog .t-dialog__close {
- top: 16px;
- right: 16px;
- width: 28px;
- height: 28px;
- border-radius: 4px;
- color: var(--td-text-color-secondary);
- transition: background 0.18s ease;
-}
-
-.api-key-create-dialog .t-dialog__close:hover {
- color: var(--td-text-color-primary);
- background: var(--td-bg-color-container-hover);
-}
-
-@media (max-width: 480px) {
- .api-key-create-dialog {
- width: calc(100vw - 24px) !important;
- }
-}
-</style>
-
<style scoped lang="less">
.api-integration {
width: 100%;
@@ -1657,22 +1766,22 @@ onBeforeUnmount(stopPlayground)
th:nth-child(2),
td:nth-child(2) {
- width: 26%;
+ width: 22%;
}
th:nth-child(3),
td:nth-child(3) {
- width: 15%;
+ width: 24%;
}
th:nth-child(4),
td:nth-child(4) {
- width: 18%;
+ width: 16%;
}
th:nth-child(5),
td:nth-child(5) {
- width: 15%;
+ width: 12%;
}
th:nth-child(6),
@@ -1720,67 +1829,116 @@ onBeforeUnmount(stopPlayground)
white-space: nowrap;
}
-.api-key-knowledge-scope,
-.api-key-created-at {
- display: block;
+.api-key-access-cell {
+ display: flex;
min-width: 0;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 7px;
+}
+
+.api-key-access-mode {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ height: 24px;
+ padding: 0 9px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 6px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-primary);
+ font-size: 12px;
+ font-weight: 600;
+ line-height: 22px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
+.api-key-access-mode--full {
+ border-color: color-mix(in srgb, var(--td-brand-color) 28%, transparent);
+ background: color-mix(in srgb, var(--td-brand-color) 10%, var(--td-bg-color-container));
+ color: var(--td-brand-color);
+}
-.api-key-dialog {
+.api-key-capability-chips {
display: flex;
- flex-direction: column;
- gap: 0;
- margin-top: 16px;
- padding: 0;
- border-bottom: 1px solid var(--td-component-stroke);
+ max-width: 100%;
+ flex-wrap: wrap;
+ gap: 5px;
+}
+
+.api-key-capability-chip {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ height: 22px;
+ padding: 0 8px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--td-success-color) 10%, var(--td-bg-color-container));
+ color: var(--td-success-color);
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 20px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.api-key-create-heading {
+.api-key-capability-list {
display: flex;
flex-direction: column;
- gap: 4px;
- min-width: 0;
- padding-right: 28px;
+ gap: 12px;
}
-.api-key-create-heading-row {
+.api-key-capability-group {
display: flex;
- align-items: center;
+ flex-direction: column;
gap: 8px;
- min-width: 0;
+ padding: 10px 0 2px;
}
-.api-key-create-heading-mark {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- color: var(--td-brand-color);
- line-height: 0;
-
- :deep(.t-icon) {
- display: inline-flex;
- }
+.api-key-capability-group + .api-key-capability-group {
+ border-top: 1px solid var(--td-component-stroke);
}
-.api-key-create-title {
+.api-key-capability-group__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ min-height: 24px;
color: var(--td-text-color-primary);
- font-size: 15px;
+ font-size: 13px;
font-weight: 600;
- line-height: 22px;
- letter-spacing: 0.2px;
}
-.api-key-create-desc {
- margin: 0;
- color: var(--td-text-color-placeholder);
- font-size: 13px;
- font-weight: 400;
- line-height: 20px;
+.api-key-capability-group__items {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.api-key-capability-item .scope-hint {
+ margin-top: 2px;
+}
+
+.api-key-knowledge-scope,
+.api-key-created-at {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+
+.api-key-dialog {
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ padding: 0;
+ border-bottom: 1px solid var(--td-component-stroke);
}
.api-key-dialog-row {
@@ -1846,90 +2004,13 @@ onBeforeUnmount(stopPlayground)
}
}
-.api-key-role-radio {
- display: flex;
- width: 100%;
- max-width: 100%;
-
- :deep(.t-radio-group) {
- display: flex;
- width: 100%;
- }
-
- :deep(.t-radio-button) {
- flex: 1 1 0;
- min-width: 0;
- justify-content: center;
- }
-
- :deep(.t-radio-button__former) {
- position: absolute;
- width: 0;
- height: 0;
- margin: 0;
- padding: 0;
- }
-
- :deep(.t-radio-button__input) {
- display: none;
- }
-
- :deep(.t-radio-button__label) {
- flex: 0 1 auto;
- margin-left: 0;
- text-align: center;
- }
-}
-
-.scope-role-hint {
+.scope-hint {
margin: 8px 0 0;
color: var(--td-text-color-placeholder);
font-size: 12px;
line-height: 18px;
}
-.scope-help {
- display: flex;
- flex-direction: column;
- gap: 4px;
- padding: 8px 10px;
- border-radius: 4px;
- background: var(--td-bg-color-secondarycontainer);
-
- &--role {
- margin-top: 8px;
- }
-
- &__role {
- margin: 0;
- color: var(--td-text-color-secondary);
- font-size: 13px;
- font-weight: 600;
- line-height: 20px;
- }
-
- &__desc {
- margin: 0;
- color: var(--td-text-color-placeholder);
- font-size: 12px;
- line-height: 18px;
- }
-}
-
-.api-key-create-footer {
- display: flex;
- align-items: center;
- justify-content: flex-end;
- padding-top: 14px;
-}
-
-.api-key-create-footer__actions {
- display: flex;
- flex: 0 0 auto;
- align-items: center;
- gap: 8px;
-}
-
.principal-section {
display: flex;
flex-direction: column;
diff --git a/internal/application/repository/agent_share.go b/internal/application/repository/agent_share.go
index b9fd2189d..0babd89bc 100644
--- a/internal/application/repository/agent_share.go
+++ b/internal/application/repository/agent_share.go
@@ -192,18 +192,20 @@ func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, te
// source_tenant_id == excludeTenantID. Single query.
func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
var share types.AgentShare
- err := r.db.WithContext(ctx).
+ tx := r.db.WithContext(ctx).
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
Where("agent_shares.agent_id = ?", agentID).
Where("otm.tenant_id = ?", tenantID).
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
Where("agent_shares.deleted_at IS NULL").
- First(&share).Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrAgentShareNotFound
- }
- return nil, err
+ Order("agent_shares.id").
+ Limit(1).
+ Find(&share)
+ if tx.Error != nil {
+ return nil, tx.Error
+ }
+ if tx.RowsAffected == 0 {
+ return nil, ErrAgentShareNotFound
}
return &share, nil
}
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index f9ddad463..cf6712351 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -243,7 +243,12 @@ func (s *sessionService) buildAgentConfig(
s.configureSkillsFromAgent(ctx, agentConfig, customAgent)
// Resolve knowledge bases using shared helper
- agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs = s.resolveKnowledgeBases(ctx, req)
+ kbIDs, knowledgeIDs, err := s.resolveKnowledgeBases(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+ agentConfig.KnowledgeBases = kbIDs
+ agentConfig.KnowledgeIDs = knowledgeIDs
// Use custom agent's allowed tools if specified, otherwise use defaults
if len(customAgent.Config.AllowedTools) > 0 {
diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go
index 8cd257d4d..72903b724 100644
--- a/internal/application/service/session_knowledge_qa.go
+++ b/internal/application/service/session_knowledge_qa.go
@@ -45,7 +45,10 @@ func (s *sessionService) KnowledgeQA(
ctx = setupCtx
// Resolve knowledge bases using shared helper
- knowledgeBaseIDs, knowledgeIDs := s.resolveKnowledgeBases(ctx, req)
+ knowledgeBaseIDs, knowledgeIDs, err := s.resolveKnowledgeBases(ctx, req)
+ if err != nil {
+ return err
+ }
// Resolve chat model ID using shared helper
chatModelID, err := s.resolveChatModelID(ctx, req, knowledgeBaseIDs, knowledgeIDs)
diff --git a/internal/application/service/session_qa_api_key_scope_test.go b/internal/application/service/session_qa_api_key_scope_test.go
new file mode 100644
index 000000000..c37a2a8a0
--- /dev/null
+++ b/internal/application/service/session_qa_api_key_scope_test.go
@@ -0,0 +1,57 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+func TestResolveKnowledgeBasesFiltersImplicitAgentDefaultsForRestrictedAPIKey(t *testing.T) {
+ ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
+ KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
+ })
+ svc := &sessionService{}
+
+ kbIDs, knowledgeIDs, err := svc.resolveKnowledgeBases(ctx, &types.QARequest{
+ Session: &types.Session{TenantID: 10000},
+ CustomAgent: &types.CustomAgent{
+ TenantID: 10000,
+ Config: types.CustomAgentConfig{
+ KBSelectionMode: "selected",
+ KnowledgeBases: []string{"kb-allowed", "kb-blocked"},
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("resolveKnowledgeBases returned error: %v", err)
+ }
+ if len(kbIDs) != 1 || kbIDs[0] != "kb-allowed" {
+ t.Fatalf("kbIDs = %#v, want only kb-allowed", kbIDs)
+ }
+ if len(knowledgeIDs) != 0 {
+ t.Fatalf("knowledgeIDs = %#v, want empty", knowledgeIDs)
+ }
+}
+
+func TestResolveKnowledgeBasesRejectsExplicitOutOfScopeKBForRestrictedAPIKey(t *testing.T) {
+ ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
+ KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
+ })
+ svc := &sessionService{}
+
+ _, _, err := svc.resolveKnowledgeBases(ctx, &types.QARequest{
+ Session: &types.Session{TenantID: 10000},
+ KnowledgeBaseIDs: []string{"kb-blocked"},
+ CustomAgent: &types.CustomAgent{
+ TenantID: 10000,
+ Config: types.CustomAgentConfig{
+ KBSelectionMode: "selected",
+ KnowledgeBases: []string{"kb-allowed", "kb-blocked"},
+ },
+ },
+ })
+ if err == nil {
+ t.Fatal("expected forbidden for explicit out-of-scope knowledge_base_ids")
+ }
+}
diff --git a/internal/application/service/session_qa_helpers.go b/internal/application/service/session_qa_helpers.go
index f020b2990..65c8c72f1 100644
--- a/internal/application/service/session_qa_helpers.go
+++ b/internal/application/service/session_qa_helpers.go
@@ -21,9 +21,10 @@ import (
func (s *sessionService) resolveKnowledgeBases(
ctx context.Context,
req *types.QARequest,
-) (kbIDs []string, knowledgeIDs []string) {
+) (kbIDs []string, knowledgeIDs []string, err error) {
kbIDs = req.KnowledgeBaseIDs
knowledgeIDs = req.KnowledgeIDs
+ requestedKBIDs := append([]string(nil), req.KnowledgeBaseIDs...)
customAgent := req.CustomAgent
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0 || len(req.TagScopes) > 0
@@ -47,7 +48,15 @@ func (s *sessionService) resolveKnowledgeBases(
} else if customAgent != nil {
kbIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, req.Session.TenantID)
}
- return kbIDs, knowledgeIDs
+
+ if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, requestedKBIDs, req.KnowledgeIDs); err != nil {
+ return nil, nil, err
+ }
+ kbIDs, err = types.FilterKnowledgeBasesForTenantAPIKeyScope(ctx, requestedKBIDs, kbIDs)
+ if err != nil {
+ return nil, nil, err
+ }
+ return kbIDs, knowledgeIDs, nil
}
func (s *sessionService) restrictTagScopesToAgentScope(
diff --git a/internal/application/service/tenant_api_key.go b/internal/application/service/tenant_api_key.go
index ffd17aa8b..f3d7faf78 100644
--- a/internal/application/service/tenant_api_key.go
+++ b/internal/application/service/tenant_api_key.go
@@ -50,12 +50,14 @@ func (s *tenantAPIKeyService) CreateAPIKey(
Name: name,
KeyHash: hashTenantAPIKey(token),
APIKey: token,
- Role: types.NormalizeTenantAPIKeyRole(req.Role),
+ FullAccess: req.FullAccess,
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
+ Capabilities: types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities)),
ExpiresAt: req.ExpiresAt,
}
- if key.Role == "" {
- key.Role = types.TenantRoleViewer
+ if key.FullAccess {
+ key.KnowledgeBaseIDs = nil
+ key.Capabilities = nil
}
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
return nil, err
diff --git a/internal/application/service/tenant_api_key_test.go b/internal/application/service/tenant_api_key_test.go
index ae8d35bb2..862dea5b9 100644
--- a/internal/application/service/tenant_api_key_test.go
+++ b/internal/application/service/tenant_api_key_test.go
@@ -26,7 +26,6 @@ func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "integration",
- Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
@@ -135,11 +134,11 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
token := "sk-legacy-token-value"
legacy := &types.TenantAPIKey{
- TenantID: 7,
- Name: "legacy",
- KeyHash: "migrated-tenant-7",
- APIKey: token,
- Role: types.TenantRoleOwner,
+ TenantID: 7,
+ Name: "legacy",
+ KeyHash: "migrated-tenant-7",
+ APIKey: token,
+ FullAccess: true,
}
if err := repo.CreateAPIKey(ctx, legacy); err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
@@ -168,7 +167,6 @@ func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "integration",
- Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
@@ -189,7 +187,6 @@ func TestTenantAPIKeyServiceAuthenticateThrottlesLastUsedUpdates(t *testing.T) {
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "integration",
- Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go
index 16ccd51df..b2f83eb7f 100644
--- a/internal/handler/custom_agent.go
+++ b/internal/handler/custom_agent.go
@@ -43,10 +43,10 @@ func NewCustomAgentHandler(
// CreateAgentRequest defines the request body for creating an agent
type CreateAgentRequest struct {
- Name string `json:"name" binding:"required"`
- Description string `json:"description"`
- Avatar string `json:"avatar"`
- Config types.CustomAgentConfig `json:"config"`
+ Name string `json:"name" binding:"required"`
+ Description string `json:"description"`
+ Avatar string `json:"avatar"`
+ Config types.CustomAgentConfig `json:"config"`
}
// UpdateAgentRequest defines the request body for updating an agent
@@ -81,6 +81,10 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
+ if err := authorizeAgentKnowledgeScope(ctx, req.Config); err != nil {
+ c.Error(err)
+ return
+ }
// Build agent object
agent := &types.CustomAgent{
@@ -146,6 +150,10 @@ func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
c.Error(errors.NewNotFoundError("Agent not found"))
return
}
+ if appErr, ok := err.(*errors.AppError); ok {
+ c.Error(appErr)
+ return
+ }
c.Error(errors.NewInternalServerError(err.Error()))
return
}
@@ -311,6 +319,10 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
+ if err := authorizeAgentKnowledgeScope(ctx, req.Config); err != nil {
+ c.Error(err)
+ return
+ }
// Build agent object
agent := &types.CustomAgent{
@@ -444,6 +456,23 @@ func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
}
logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
+ sourceAgent, err := h.service.GetAgentByID(ctx, id)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "agent_id": id,
+ })
+ switch err {
+ case service.ErrAgentNotFound:
+ c.Error(errors.NewNotFoundError("Agent not found"))
+ default:
+ c.Error(errors.NewInternalServerError(err.Error()))
+ }
+ return
+ }
+ if err := authorizeAgentKnowledgeScope(ctx, sourceAgent.Config); err != nil {
+ c.Error(err)
+ return
+ }
// Copy the agent
copiedAgent, err := h.service.CopyAgent(ctx, id)
@@ -587,6 +616,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
c.Error(errors.NewNotFoundError("Agent not found"))
return
}
+ if appErr, ok := err.(*errors.AppError); ok {
+ c.Error(appErr)
+ return
+ }
c.Error(errors.NewInternalServerError(err.Error()))
return
}
@@ -598,3 +631,23 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
},
})
}
+
+func authorizeAgentKnowledgeScope(ctx context.Context, cfg types.CustomAgentConfig) error {
+ scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
+ if !ok || !scope.IsKnowledgeBaseRestricted() {
+ return nil
+ }
+ switch strings.ToLower(strings.TrimSpace(cfg.KBSelectionMode)) {
+ case "none":
+ return nil
+ case "all":
+ return errors.NewForbiddenError("API key scope does not allow agents that use all knowledge bases")
+ case "selected":
+ return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, cfg.KnowledgeBases...)
+ default:
+ if len(cfg.KnowledgeBases) == 0 {
+ return nil
+ }
+ return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, cfg.KnowledgeBases...)
+ }
+}
diff --git a/internal/handler/custom_agent_api_key_scope_test.go b/internal/handler/custom_agent_api_key_scope_test.go
new file mode 100644
index 000000000..458ea7f85
--- /dev/null
+++ b/internal/handler/custom_agent_api_key_scope_test.go
@@ -0,0 +1,49 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+type suggestedQuestionsAgentService struct {
+ interfaces.CustomAgentService
+ err error
+}
+
+func (s *suggestedQuestionsAgentService) GetSuggestedQuestions(
+ context.Context,
+ string,
+ []string,
+ []string,
+ []string,
+ int,
+) ([]types.SuggestedQuestion, error) {
+ return nil, s.err
+}
+
+func TestGetSuggestedQuestionsPreservesAppErrorStatus(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(middleware.ErrorHandler())
+
+ h := &CustomAgentHandler{service: &suggestedQuestionsAgentService{
+ err: apperrors.NewForbiddenError("API key scope does not allow one or more knowledge bases"),
+ }}
+ r.GET("/agents/:id/suggested-questions", h.GetSuggestedQuestions)
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/agents/agent-1/suggested-questions?knowledge_base_ids=kb-blocked", nil)
+ r.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusForbidden, rec.Body.String())
+ }
+}
diff --git a/internal/handler/datasource.go b/internal/handler/datasource.go
index d34294663..56e386b7b 100644
--- a/internal/handler/datasource.go
+++ b/internal/handler/datasource.go
@@ -54,6 +54,9 @@ func (h *DataSourceHandler) getOwnedKnowledgeBase(
if kb.TenantID != tenantID {
return nil, http.StatusForbidden, "access denied"
}
+ if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
+ return nil, http.StatusForbidden, err.Error()
+ }
return kb, http.StatusOK, ""
}
@@ -170,11 +173,6 @@ func (h *DataSourceHandler) ListDataSources(c *gin.Context) {
c.JSON(status, gin.H{"error": msg})
return
}
- if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
- c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
- return
- }
-
dataSources, err := h.service.ListDataSources(ctx, kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list data sources"})
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index bc721932f..6ce1e4ee3 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -136,8 +136,9 @@ type apiPrincipalTestTokenResponse struct {
type tenantAPIKeyCreateRequest struct {
Name string `json:"name"`
- Role string `json:"role"`
+ FullAccess bool `json:"full_access"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
+ Capabilities []string `json:"capabilities"`
ExpiresAt *int64 `json:"expires_at_unix"`
}
@@ -145,8 +146,9 @@ type tenantAPIKeyResponse struct {
ID uint64 `json:"id"`
Name string `json:"name"`
APIKey string `json:"api_key"`
- Role types.TenantRole `json:"role"`
+ FullAccess bool `json:"full_access"`
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
+ Capabilities types.StringArray `json:"capabilities"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
@@ -576,10 +578,6 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
c.Error(err)
return
}
- role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role)))
- if role == "" {
- role = types.TenantRoleViewer
- }
var expiresAt *time.Time
if req.ExpiresAt != nil {
t := time.Unix(*req.ExpiresAt, 0)
@@ -592,8 +590,9 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: id,
Name: req.Name,
- Role: role,
+ FullAccess: req.FullAccess,
KnowledgeBaseIDs: req.KnowledgeBaseIDs,
+ Capabilities: req.Capabilities,
ExpiresAt: expiresAt,
})
if err != nil {
@@ -636,8 +635,9 @@ func tenantAPIKeyForResponse(key *types.TenantAPIKey) tenantAPIKeyResponse {
ID: key.ID,
Name: key.Name,
APIKey: key.APIKey,
- Role: types.NormalizeTenantAPIKeyRole(key.Role),
+ FullAccess: key.FullAccess,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
+ Capabilities: types.NormalizeAPIKeyCapabilities(key.Capabilities),
LastUsedAt: key.LastUsedAt,
ExpiresAt: key.ExpiresAt,
CreatedAt: key.CreatedAt,
@@ -653,8 +653,16 @@ func validateTenantAPIKeyRequest(
if strings.TrimSpace(req.Name) == "" {
return errors.NewValidationError("name is required")
}
- if role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role))); req.Role != "" && role == "" {
- return errors.NewValidationError("role must be one of viewer, contributor, admin, or owner")
+ if req.FullAccess {
+ return nil
+ }
+ for _, cap := range req.Capabilities {
+ if strings.TrimSpace(cap) == "" {
+ continue
+ }
+ if types.NormalizeAPIKeyCapability(types.APIKeyCapability(cap)) == "" {
+ return errors.NewValidationError("capabilities contains an unknown capability")
+ }
}
for _, kbID := range req.KnowledgeBaseIDs {
kbID = strings.TrimSpace(kbID)
diff --git a/internal/logger/logger_test.go b/internal/logger/logger_test.go
index b92517c1d..e2fa92e67 100644
--- a/internal/logger/logger_test.go
+++ b/internal/logger/logger_test.go
@@ -183,7 +183,6 @@ func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
want := types.TenantAPIKeyScope{
KeyID: 7,
- Role: types.TenantRoleViewer,
KnowledgeBaseIDs: types.StringArray{"kb-1"},
}
ctx := types.WithTenantAPIKeyScope(context.Background(), want)
diff --git a/internal/middleware/api_key_gate.go b/internal/middleware/api_key_gate.go
index dc8216b42..ec6559e5d 100644
--- a/internal/middleware/api_key_gate.go
+++ b/internal/middleware/api_key_gate.go
@@ -21,20 +21,32 @@ var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidde
// default (fail-closed), which removes the old "remember to add APIKeyDeny"
// footgun.
type APIKeyRoutePolicy struct {
- // MinRole is the minimum tenant role an API key needs for this route.
- //
- // Data-plane routes (knowledge bases and their content) use Viewer /
- // Contributor / Admin; for those, safe reads (GET/HEAD/OPTIONS) only
- // require Viewer while writes require the declared role. Tenant-level
- // infrastructure routes (models, vector stores, MCP, data sources,
- // channels, tenant KV, ...) use Owner, which is required for EVERY
- // method — reading tenant configuration is itself a privileged action.
- //
- // KB scoping is NOT enforced here: a key's knowledge_base_ids allow-list
- // is a pure data filter applied by the KBAccess guards and the handler
- // scope checks on data-plane routes. Tenant-level routes are simply
- // gated behind the Owner role instead of being reachable by a narrow key.
- MinRole types.TenantRole
+ // RequireFullAccess admits only full-access tenant API keys unless one of
+ // the listed capabilities also matches. Routes with neither full-access
+ // requirement nor capabilities are open to any valid API key.
+ RequireFullAccess bool
+
+ // Capabilities is an any-of allow-list for scoped API keys. A capability
+ // never widens which knowledge bases a key may touch; KB scoping is
+ // enforced downstream by KBAccess guards and handler scope checks.
+ Capabilities []types.APIKeyCapability
+}
+
+// WithCapability returns a copy of the policy that additionally admits keys
+// carrying capability c. Multiple calls accumulate (any-of semantics);
+// duplicates are ignored.
+func (p APIKeyRoutePolicy) WithCapability(c types.APIKeyCapability) APIKeyRoutePolicy {
+ for _, existing := range p.Capabilities {
+ if existing == c {
+ return p
+ }
+ }
+ // Copy the slice so mutating the returned policy never aliases the
+ // receiver's backing array.
+ next := make([]types.APIKeyCapability, len(p.Capabilities), len(p.Capabilities)+1)
+ copy(next, p.Capabilities)
+ p.Capabilities = append(next, c)
+ return p
}
// APIKeyRouteAuthorizer is the registry of per-route API-key policies. It is
@@ -116,23 +128,18 @@ func (a *APIKeyRouteAuthorizer) authorize(scope types.TenantAPIKeyScope, method,
if !ok {
return errTenantAPIKeyScopeForbidden
}
- role := scope.Role
- if role == "" {
- role = types.TenantRoleViewer
+ if scope.FullAccess {
+ return nil
}
- required := policy.MinRole
- if required == "" {
- required = types.TenantRoleViewer
- }
- // Data-plane safe reads only need a Viewer floor. Tenant-level (Owner)
- // routes require the full role even for reads, so they are never lowered.
- if isSafeHTTPMethod(method) && required != types.TenantRoleOwner {
- required = types.TenantRoleViewer
+ for _, cap := range policy.Capabilities {
+ if cap != "" && scope.HasCapability(cap) {
+ return nil
+ }
}
- if !role.HasPermission(required) {
- return errTenantAPIKeyScopeForbidden
+ if !policy.RequireFullAccess && len(policy.Capabilities) == 0 {
+ return nil
}
- return nil
+ return errTenantAPIKeyScopeForbidden
}
// DenyAPIKeyPrincipal returns a middleware that rejects any X-API-Key
@@ -154,15 +161,6 @@ func DenyAPIKeyPrincipal() gin.HandlerFunc {
}
}
-func isSafeHTTPMethod(method string) bool {
- switch method {
- case http.MethodGet, http.MethodHead, http.MethodOptions:
- return true
- default:
- return false
- }
-}
-
// normalizeRoutePath collapses duplicate slashes and trims a trailing slash so
// helper-built paths (BasePath()+rel) match gin's c.FullPath() exactly.
func normalizeRoutePath(p string) string {
diff --git a/internal/middleware/api_key_gate_test.go b/internal/middleware/api_key_gate_test.go
index 3e6fb1821..6ddd4aada 100644
--- a/internal/middleware/api_key_gate_test.go
+++ b/internal/middleware/api_key_gate_test.go
@@ -11,20 +11,16 @@ import (
func newTestAuthorizer() *APIKeyRouteAuthorizer {
a := NewAPIKeyRouteAuthorizer()
- // Data-plane routes (Viewer read, Contributor write, Admin destructive)
- // plus one tenant-level Owner route.
- a.Register(http.MethodGet, "/api/v1/knowledge-bases/:id", policyMinRole(types.TenantRoleViewer))
- a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file", policyMinRole(types.TenantRoleContributor))
- a.Register(http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge", policyMinRole(types.TenantRoleAdmin))
- a.Register(http.MethodGet, "/api/v1/models", policyMinRole(types.TenantRoleOwner))
- a.Register(http.MethodPut, "/api/v1/tenants/kv/:key", policyMinRole(types.TenantRoleOwner))
+ a.Register(http.MethodGet, "/api/v1/auth/me", APIKeyRoutePolicy{})
+ a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityIngest))
+ a.Register(http.MethodGet, "/api/v1/models",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageModels))
+ a.Register(http.MethodPut, "/api/v1/tenants/kv/:key",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageTenantSettings))
return a
}
-func policyMinRole(r types.TenantRole) APIKeyRoutePolicy {
- return APIKeyRoutePolicy{MinRole: r}
-}
-
// runGate exercises the gate middleware with a given scope, method and route
// full-path, returning whether the request was allowed to proceed.
func runGate(t *testing.T, a *APIKeyRouteAuthorizer, scope *types.TenantAPIKeyScope, method, fullPath string) bool {
@@ -56,8 +52,6 @@ func concretePath(tmpl string) string {
return "/api/v1/knowledge-bases/kb-1"
case "/api/v1/knowledge-bases/:id/knowledge/file":
return "/api/v1/knowledge-bases/kb-1/knowledge/file"
- case "/api/v1/knowledge-bases/:id/knowledge":
- return "/api/v1/knowledge-bases/kb-1/knowledge"
case "/api/v1/tenants/kv/:key":
return "/api/v1/tenants/kv/some-key"
default:
@@ -67,7 +61,7 @@ func concretePath(tmpl string) string {
func TestGateJWTPassesThrough(t *testing.T) {
a := newTestAuthorizer()
- // No scope => JWT principal => always allowed, even on an Owner route.
+ // No scope => JWT principal => always allowed, even on a full-access route.
if !runGate(t, a, nil, http.MethodGet, "/api/v1/models") {
t.Fatal("JWT principal must pass the gate")
}
@@ -75,11 +69,11 @@ func TestGateJWTPassesThrough(t *testing.T) {
func TestGateDefaultDeny(t *testing.T) {
a := newTestAuthorizer()
- owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
+ full := &types.TenantAPIKeyScope{FullAccess: true}
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(func(c *gin.Context) {
- c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *owner))
+ c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *full))
c.Next()
})
engine.Use(a.Middleware())
@@ -87,54 +81,80 @@ func TestGateDefaultDeny(t *testing.T) {
w := httptest.NewRecorder()
engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/agents", nil))
if w.Code != http.StatusForbidden {
- t.Fatalf("undeclared route should default-deny even an Owner key: status=%d", w.Code)
+ t.Fatalf("undeclared route should default-deny even a full-access key: status=%d", w.Code)
}
}
-func TestGateDataPlaneRoleLadder(t *testing.T) {
+func TestGateAnyPolicyAllowsScopedKey(t *testing.T) {
a := newTestAuthorizer()
- viewer := &types.TenantAPIKeyScope{Role: types.TenantRoleViewer}
- contributor := &types.TenantAPIKeyScope{Role: types.TenantRoleContributor}
- admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
+ scoped := &types.TenantAPIKeyScope{}
- // Safe read: any data-plane key (Viewer) passes.
- if !runGate(t, a, viewer, http.MethodGet, "/api/v1/knowledge-bases/:id") {
- t.Fatal("viewer key should read a declared KB route")
- }
- // Contributor write.
- if runGate(t, a, viewer, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
- t.Fatal("viewer key must not perform a contributor write")
- }
- if !runGate(t, a, contributor, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
- t.Fatal("contributor key should perform a contributor write")
- }
- // Admin destructive.
- if runGate(t, a, contributor, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
- t.Fatal("contributor key must not perform an admin destructive op")
- }
- if !runGate(t, a, admin, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
- t.Fatal("admin key should perform an admin destructive op")
+ if !runGate(t, a, scoped, http.MethodGet, "/api/v1/auth/me") {
+ t.Fatal("scoped key should call a declared route with an empty policy")
}
}
-func TestGateTenantRoutesRequireOwner(t *testing.T) {
+func TestGateFullAccessAndCapabilityPolicies(t *testing.T) {
a := newTestAuthorizer()
- admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
- owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
+ scoped := &types.TenantAPIKeyScope{}
+ full := &types.TenantAPIKeyScope{FullAccess: true}
+ ingest := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"ingest"}}
+ models := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_models"}}
- // Even a safe GET on a tenant-level route requires Owner (no Viewer floor).
- if runGate(t, a, admin, http.MethodGet, "/api/v1/models") {
- t.Fatal("admin key must NOT read a tenant-level route")
+ if runGate(t, a, scoped, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
+ t.Fatal("plain scoped key must not write content")
}
- if !runGate(t, a, owner, http.MethodGet, "/api/v1/models") {
- t.Fatal("owner key should read a tenant-level route")
+ if !runGate(t, a, full, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
+ t.Fatal("full-access key should write content")
}
- // Unsafe tenant write also requires Owner.
- if runGate(t, a, admin, http.MethodPut, "/api/v1/tenants/kv/:key") {
- t.Fatal("admin key must NOT write a tenant-level route")
+ if !runGate(t, a, ingest, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
+ t.Fatal("ingest capability should write content")
}
- if !runGate(t, a, owner, http.MethodPut, "/api/v1/tenants/kv/:key") {
- t.Fatal("owner key should write a tenant-level route")
+ if runGate(t, a, ingest, http.MethodGet, "/api/v1/models") {
+ t.Fatal("ingest capability must not read model management routes")
+ }
+ if !runGate(t, a, models, http.MethodGet, "/api/v1/models") {
+ t.Fatal("manage_models capability should read model management routes")
+ }
+}
+
+func TestGateAnyOfCapabilities(t *testing.T) {
+ a := NewAPIKeyRouteAuthorizer()
+ a.Register(http.MethodPost, "/api/v1/sessions",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityChat))
+ a.Register(http.MethodGet, "/api/v1/agents",
+ APIKeyRoutePolicy{RequireFullAccess: true}.
+ WithCapability(types.APIKeyCapabilityChat).
+ WithCapability(types.APIKeyCapabilityManageAgents))
+ a.Register(http.MethodPost, "/api/v1/agents",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageAgents))
+ a.Register(http.MethodPut, "/api/v1/knowledge-bases/:id",
+ APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageKnowledgeBases))
+
+ chat := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"chat"}}
+ manage := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_agents"}}
+ manageKBs := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_kbs"}}
+
+ // Either capability satisfies the any-of read route.
+ if !runGate(t, a, chat, http.MethodGet, "/api/v1/agents") {
+ t.Fatal("chat should read agents (any-of)")
+ }
+ if !runGate(t, a, manage, http.MethodGet, "/api/v1/agents") {
+ t.Fatal("manage_agents should read agents (any-of)")
+ }
+ // Only manage_agents may author agents.
+ if runGate(t, a, chat, http.MethodPost, "/api/v1/agents") {
+ t.Fatal("chat must not author agents")
+ }
+ if !runGate(t, a, manage, http.MethodPost, "/api/v1/agents") {
+ t.Fatal("manage_agents should author agents")
+ }
+ // Only manage_kbs may manage KB metadata/config.
+ if runGate(t, a, manage, http.MethodPut, "/api/v1/knowledge-bases/:id") {
+ t.Fatal("manage_agents must not manage knowledge bases")
+ }
+ if !runGate(t, a, manageKBs, http.MethodPut, "/api/v1/knowledge-bases/:id") {
+ t.Fatal("manage_kbs should manage knowledge bases")
}
}
@@ -143,11 +163,11 @@ func TestGateKBScopeDoesNotBlockDataPlane(t *testing.T) {
// A KB-restricted key is NOT blocked by the gate on data-plane routes;
// its KB allow-list is enforced downstream by KBAccess/handler checks.
restricted := &types.TenantAPIKeyScope{
- Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-1"},
+ Capabilities: types.StringArray{"ingest"},
}
if !runGate(t, a, restricted, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
- t.Fatal("KB-restricted contributor key should pass the gate on a data-plane write")
+ t.Fatal("KB-restricted ingest key should pass the gate on a data-plane write")
}
}
@@ -176,8 +196,8 @@ func runDenyAPIKey(t *testing.T, scope *types.TenantAPIKeyScope) (reached bool,
// engine-root routes (outside /api/v1) that rely on RequireRole must not be
// reachable by API-key principals, since RequireRole short-circuits them.
func TestDenyAPIKeyPrincipalBlocksAPIKeys(t *testing.T) {
- // Even an Owner-role API key must be rejected outright.
- reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{Role: types.TenantRoleOwner})
+ // Even a full-access API key must be rejected outright.
+ reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{FullAccess: true})
if reached {
t.Fatal("API-key principal must not reach a DenyAPIKeyPrincipal-guarded handler")
}
diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go
index 460ed640d..2ae4715c0 100644
--- a/internal/middleware/auth.go
+++ b/internal/middleware/auth.go
@@ -250,8 +250,8 @@ func authenticateAPIKeyRequest(
if c.IsAborted() {
return false
}
- // Per-route API-key authorization (role + KB scope + default-deny) is
- // enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
+ // Per-route API-key authorization (full access + capabilities + KB scope)
+ // is enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
// Key-management and any other undeclared route is denied there.
return true
}
@@ -299,25 +299,26 @@ func attachAPIKeyAuthContext(
return
}
c.Set(types.PrincipalContextKey.String(), principal)
- apiKeyRole := types.TenantRoleViewer
- if key != nil {
- apiKeyRole = types.NormalizeTenantAPIKeyRole(key.Role)
- if apiKeyRole == "" {
- apiKeyRole = types.TenantRoleViewer
- }
- }
- c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
+ // This role context exists only for legacy guard compatibility after
+ // RequireRole short-circuits API-key principals. The API key's real
+ // authority is FullAccess + Capabilities + KnowledgeBaseIDs.
+ apiKeyTenantRoleContext := types.TenantRoleViewer
+ if key != nil && key.FullAccess {
+ apiKeyTenantRoleContext = types.TenantRoleOwner
+ }
+ c.Set(types.TenantRoleContextKey.String(), apiKeyTenantRoleContext)
c.Set(types.SystemAdminContextKey.String(), false)
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
ctx = types.WithPrincipal(ctx, principal)
- ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyRole)
+ ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyTenantRoleContext)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
if key != nil {
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
KeyID: key.ID,
- Role: apiKeyRole,
+ FullAccess: key.FullAccess,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
+ Capabilities: key.Capabilities,
})
}
c.Request = c.Request.WithContext(ctx)
diff --git a/internal/middleware/rbac_api_key_shortcircuit_test.go b/internal/middleware/rbac_api_key_shortcircuit_test.go
index c1852a7e2..b4a3876fd 100644
--- a/internal/middleware/rbac_api_key_shortcircuit_test.go
+++ b/internal/middleware/rbac_api_key_shortcircuit_test.go
@@ -12,9 +12,9 @@ import (
)
// apiKeyRBACHarness seeds an API-key scope (as attachAPIKeyAuthContext would)
-// plus a deliberately-insufficient TenantRole, then runs the guard. It
-// asserts the JWT guard short-circuits for API-key principals so that
-// per-route API-key authorization is left entirely to the APIKeyGate.
+// plus a deliberately-insufficient TenantRole, then runs the guard. It asserts
+// the JWT guard short-circuits for API-key principals so that per-route
+// API-key authorization is left entirely to the APIKeyGate.
func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw gin.HandlerFunc) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
@@ -32,10 +32,10 @@ func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw
}
func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
- // Viewer-role API key against an Admin gate would 403 under the JWT
+ // Scoped API key against an Admin gate would 403 under the JWT
// ladder; the short-circuit lets it through (the gate handles it).
w := apiKeyRBACHarness(
- types.TenantAPIKeyScope{Role: types.TenantRoleViewer},
+ types.TenantAPIKeyScope{},
types.TenantRoleViewer,
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)),
)
@@ -46,7 +46,7 @@ func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
w := apiKeyRBACHarness(
- types.TenantAPIKeyScope{Role: types.TenantRoleOwner},
+ types.TenantAPIKeyScope{FullAccess: true},
types.TenantRoleOwner,
RequireSystemAdmin(cfgRBAC(true)),
)
@@ -55,24 +55,27 @@ func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
}
}
-// TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor is the core
-// regression for review #1: a Contributor API key writing to a KB it does not
+// TestRequireOwnershipOrRole_ShortCircuitsAPIKey is the core regression for
+// review #1: an API key writing to a KB it does not
// "own" (synthetic system user never matches creator_id) must not be 403'd by
// the OwnedKBOrAdmin guard when EnableRBAC=true. The lookup deliberately
// returns a foreign creator to prove the guard never runs it.
-func TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor(t *testing.T) {
+func TestRequireOwnershipOrRole_ShortCircuitsAPIKey(t *testing.T) {
lookupCalled := false
lookup := func(_ *gin.Context) (string, error) {
lookupCalled = true
return "some-other-human-user", nil
}
w := apiKeyRBACHarness(
- types.TenantAPIKeyScope{Role: types.TenantRoleContributor, KnowledgeBaseIDs: types.StringArray{"kb-1"}},
+ types.TenantAPIKeyScope{
+ KnowledgeBaseIDs: types.StringArray{"kb-1"},
+ Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
+ },
types.TenantRoleContributor,
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
)
if w.Code != http.StatusOK {
- t.Fatalf("Contributor API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
+ t.Fatalf("API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
}
if lookupCalled {
t.Fatal("ownership lookup must not run for API-key principals")
diff --git a/internal/router/rbac.go b/internal/router/rbac.go
index 0e9b02c5f..5368b3ac2 100644
--- a/internal/router/rbac.go
+++ b/internal/router/rbac.go
@@ -215,32 +215,93 @@ func (g *rbacGuards) Owner() gin.HandlerFunc {
// it and denies any undeclared route by default. JWT sessions ignore all of
// this (they short-circuit the gate).
//
-// Policy constructors. A single dimension — the minimum role — decides
-// access; the key's knowledge_base_ids allow-list is a pure data filter
-// applied downstream (KBAccess guards + handler scope checks), never here.
-//
-// - apiKeyViewer : data-plane reads/searches (Viewer floor).
-// - apiKeyContributor : data-plane content writes (Contributor+).
-// - apiKeyAdmin : destructive data-plane ops, e.g. clearing a KB (Admin+).
-// - apiKeyOwner : tenant-level infrastructure (models, vector stores,
-// MCP, data sources, channels, tenant KV, ...). Requires the Owner role
-// for EVERY method, mirroring the original full-access tenant key. A key
-// below Owner can only ever touch knowledge-base data.
+// Policy constructors. API keys do not reuse tenant-member roles: a key is
+// either full-access, or it carries explicit capabilities. KB allow-lists are
+// pure data filters applied downstream by KBAccess guards and handlers.
+
+func apiKeyAny() middleware.APIKeyRoutePolicy {
+ return middleware.APIKeyRoutePolicy{}
+}
+
+func apiKeyFullAccess() middleware.APIKeyRoutePolicy {
+ return middleware.APIKeyRoutePolicy{RequireFullAccess: true}
+}
+
+// apiKeyRetrieve grants read/search access to knowledge-base data.
+func apiKeyRetrieve(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityRetrieve)
+}
+
+// apiKeyChat layers the "chat" capability on top of a base policy: keys that
+// carry the chat capability can use the conversation flow (sessions, agent
+// listing) without full tenant access.
+func apiKeyChat(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityChat)
+}
+
+// apiKeyReadAgents layers the "read_agents" capability on top of a base
+// policy so scoped integrations can inspect available agents without chat or
+// authoring permissions.
+func apiKeyReadAgents(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityReadAgents)
+}
+
+// apiKeyIngest layers the "ingest" capability on top of a base policy so a
+// scoped key can write content into its allowed knowledge bases (documents,
+// chunks, FAQ, tags, wiki).
+func apiKeyIngest(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityIngest)
+}
+
+// apiKeyManageKnowledgeBases layers the "manage_kbs" capability on top of a
+// base policy so a scoped key can manage existing KB metadata/config within
+// its KB allow-list.
+func apiKeyManageKnowledgeBases(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageKnowledgeBases)
+}
+
+// apiKeyManageAgents layers the "manage_agents" capability on top of a base policy.
+func apiKeyManageAgents(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageAgents)
+}
+
+// apiKeyMessageHistory layers the "message_history" capability on top of a
+// base policy so an explicitly granted key can search or inspect tenant chat
+// history without being promoted to full Owner.
+func apiKeyMessageHistory(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityMessageHistory)
+}
+
+func apiKeyManageModels(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageModels)
+}
+
+func apiKeyManageMCPServices(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageMCPServices)
+}
+
+func apiKeyManageDataSources(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageDataSources)
+}
+
+func apiKeyManageChannels(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageChannels)
+}
-func apiKeyViewer() middleware.APIKeyRoutePolicy {
- return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleViewer}
+func apiKeyManageVectorStores(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageVectorStores)
}
-func apiKeyContributor() middleware.APIKeyRoutePolicy {
- return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleContributor}
+func apiKeyManageWebSearch(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageWebSearch)
}
-func apiKeyAdmin() middleware.APIKeyRoutePolicy {
- return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleAdmin}
+func apiKeyRunEvaluations(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityRunEvaluations)
}
-func apiKeyOwner() middleware.APIKeyRoutePolicy {
- return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleOwner}
+func apiKeyManageTenantSettings(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
+ return base.WithCapability(types.APIKeyCapabilityManageTenantSettings)
}
// apiKeyRouteGroup wraps a *gin.RouterGroup so route registration also records
diff --git a/internal/router/rbac_selfcheck_test.go b/internal/router/rbac_selfcheck_test.go
index afa10b1e8..9bc89787d 100644
--- a/internal/router/rbac_selfcheck_test.go
+++ b/internal/router/rbac_selfcheck_test.go
@@ -20,14 +20,14 @@ func TestAssertAPIKeyPoliciesMatchRoutes_TrailingSlash(t *testing.T) {
// Register through the apiKey helpers using both "" and "/" rel plus a
// nested path, mirroring real route declarations.
- empty := g.apiKeyGroup(v1.Group("/knowledge-bases"), apiKeyViewer())
+ empty := g.apiKeyGroup(v1.Group("/knowledge-bases"), apiKeyAny())
empty.GET("", noop)
- slash := g.apiKeyGroup(v1.Group("/evaluation"), apiKeyOwner())
+ slash := g.apiKeyGroup(v1.Group("/evaluation"), apiKeyFullAccess())
slash.POST("/", noop)
slash.GET("/", noop)
- g.apiKeyRoute(v1, http.MethodGet, "/tenants", apiKeyOwner(), noop)
+ g.apiKeyRoute(v1, http.MethodGet, "/tenants", apiKeyFullAccess(), noop)
// Must not panic: every declared policy resolves to a real route despite
// the trailing-slash difference on /evaluation.
@@ -42,7 +42,7 @@ func TestAssertAPIKeyPoliciesMatchRoutes_Missing(t *testing.T) {
g := &rbacGuards{}
// Declare a policy for a path that is never registered on the engine.
- g.ensureAPIKeyAuthorizer().Register(http.MethodPost, "/api/v1/does-not-exist", apiKeyOwner())
+ g.ensureAPIKeyAuthorizer().Register(http.MethodPost, "/api/v1/does-not-exist", apiKeyFullAccess())
defer func() {
if recover() == nil {
diff --git a/internal/router/router.go b/internal/router/router.go
index 74aad8bb1..45c1b77d6 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -209,7 +209,7 @@ func NewRouter(params RouterParams) *gin.Engine {
// so that sub-groups inherit it.
v1.Use(rbacGuards.apiKeyAuthorizer.Middleware())
- RegisterAuthRoutes(v1, params.AuthHandler)
+ RegisterAuthRoutes(v1, params.AuthHandler, rbacGuards)
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.TenantInvitationHandler, params.AuditLogHandler, rbacGuards)
RegisterMyInvitationRoutes(v1, params.TenantInvitationHandler)
RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards)
@@ -258,7 +258,7 @@ func NewRouter(params RouterParams) *gin.Engine {
// has not yet expired are kept out by the role check, matching the
// rest of the RBAC matrix in this file.
func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
- g.apiKeyRoute(r, http.MethodPost, "/chunker/preview", apiKeyViewer(), g.Viewer(), handler.PreviewChunking)
+ g.apiKeyRoute(r, http.MethodPost, "/chunker/preview", apiKeyAny(), g.Viewer(), handler.PreviewChunking)
}
// RegisterChunkRoutes 注册分块相关的路由
@@ -268,13 +268,15 @@ func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
// shared with RegisterKnowledgeRoutes via OwnedChunkKBOrAdmin so the
// same "creator-of-the-KB OR Admin+" rule applies to chunk edits.
func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *rbacGuards) {
- // 分块路由组。API key 策略:内容级写入 Contributor+ 且限定 KB 范围。
- chunks := g.apiKeyGroup(r.Group("/chunks"), apiKeyContributor())
+ // 分块路由组。Scoped API key 需要 ingest 能力写内容,retrieve 能力读内容;
+ // 两者仍受 KB 白名单约束。
+ chunks := g.apiKeyGroup(r.Group("/chunks"), apiKeyIngest(apiKeyFullAccess()))
+ chunkRead := chunks.With(apiKeyRetrieve(apiKeyFullAccess()))
{
// 获取分块列表 — Viewer+ 且对父 KB 有 read 权限(own / shared / via shared agent)
- chunks.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
+ chunkRead.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
// 通过chunk_id获取单个chunk(不需要knowledge_id) — Viewer+ 且对父 KB 有 read 权限
- chunks.GET("/by-id/:id", g.Viewer(), g.KBAccessReadFromChunkIDParam("id"), handler.GetChunkByIDOnly)
+ chunkRead.GET("/by-id/:id", g.Viewer(), g.KBAccessReadFromChunkIDParam("id"), handler.GetChunkByIDOnly)
// 删除分块 — KB owner OR Admin+,且对父 KB 有 write 权限
chunks.DELETE("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("knowledge_id"), handler.DeleteChunk)
// 删除知识下的所有分块 — KB owner OR Admin+,且对父 KB 有 write 权限
@@ -301,40 +303,44 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
// Cross-:id batch operations stay Contributor-gated — they don't have
// a single owning KB to check against.
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
- // 知识库下的知识路由组(URL :id is the KB id)。API key 默认 Contributor+ 且限 KB 范围。
- kb := g.apiKeyGroup(r.Group("/knowledge-bases/:id/knowledge"), apiKeyContributor())
+ // 知识库下的知识路由组(URL :id is the KB id)。Scoped API key 需要
+ // ingest 能力才能写内容,且仍受 KB 范围限制;清空 KB 只允许 full-access key。
+ kb := g.apiKeyGroup(r.Group("/knowledge-bases/:id/knowledge"), apiKeyIngest(apiKeyFullAccess()))
+ kbRead := kb.With(apiKeyRetrieve(apiKeyFullAccess()))
{
kb.POST("/file", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromFile)
kb.POST("/url", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromURL)
kb.POST("/manual", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateManualKnowledge)
- kb.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
+ kbRead.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
// Clearing all contents under a KB is a destructive op; gate
// behind Admin instead of Contributor.
- kb.With(apiKeyAdmin()).DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
+ kb.With(apiKeyFullAccess()).DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
}
// 知识路由组(URL :id is a knowledge id; the guard walks it to the parent KB)
kgrp := r.Group("/knowledge")
- k := g.apiKeyGroup(kgrp, apiKeyContributor())
+ k := g.apiKeyGroup(kgrp, apiKeyIngest(apiKeyFullAccess()))
+ kRead := k.With(apiKeyRetrieve(apiKeyFullAccess()))
{
// Cross-knowledge endpoints (no :id) can't be gated on a single
// KB — they accept arbitrary knowledge IDs and the handler must
- // fan out the access check itself. So /batch and /search keep
- // the role-only floor; /move and /batch-delete stay Contributor.
- k.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
- k.GET("/:id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledge)
- k.GET("/:id/stages", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
- k.GET("/:id/spans", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
+ // fan out the access check itself. /batch and /search are read
+ // routes; /move and /batch-delete stay JWT Contributor-gated and are
+ // not declared for API keys.
+ kRead.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
+ kRead.GET("/:id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledge)
+ kRead.GET("/:id/stages", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
+ kRead.GET("/:id/spans", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
k.DELETE("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.DeleteKnowledge)
k.PUT("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateKnowledge)
k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateManualKnowledge)
k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.ReparseKnowledge)
k.POST("/:id/cancel-parse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.CancelKnowledgeParse)
- k.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile)
- k.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile)
+ kRead.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile)
+ kRead.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile)
k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateImageInfo)
- k.GET("/search", g.Viewer(), handler.SearchKnowledge)
- k.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
+ kRead.GET("/search", g.Viewer(), handler.SearchKnowledge)
+ kRead.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
// Batch / cross-KB write ops stay Contributor-gated for JWT and are
// NOT declared for API keys (default-deny): they fan out to arbitrary
// KBs with no single owning KB to bound a key's scope against.
@@ -358,14 +364,15 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
// 等价于修改 KB 内容,必须遵循 KB 的"creator OR Admin+"矩阵 ——
// 跟 chunks / wiki pages 保持一致。Viewer+ 可以读,Contributor 不能
// 改不属于自己的 KB 的 FAQ。
- faq := g.apiKeyGroup(r.Group("/knowledge-bases/:id/faq"), apiKeyContributor())
+ faq := g.apiKeyGroup(r.Group("/knowledge-bases/:id/faq"), apiKeyIngest(apiKeyFullAccess()))
+ faqRead := faq.With(apiKeyRetrieve(apiKeyFullAccess()))
{
// KBAccessRead/Write resolve own/shared/agent-visible access and
// rewrite the request's tenant context — handler no longer
// carries an effectiveCtxForKB helper.
- faq.GET("/entries", g.Viewer(), g.KBAccessRead("id"), handler.ListEntries)
- faq.GET("/entries/export", g.Viewer(), g.KBAccessRead("id"), handler.ExportEntries)
- faq.GET("/entries/:entry_id", g.Viewer(), g.KBAccessRead("id"), handler.GetEntry)
+ faqRead.GET("/entries", g.Viewer(), g.KBAccessRead("id"), handler.ListEntries)
+ faqRead.GET("/entries/export", g.Viewer(), g.KBAccessRead("id"), handler.ExportEntries)
+ faqRead.GET("/entries/:entry_id", g.Viewer(), g.KBAccessRead("id"), handler.GetEntry)
faq.POST("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpsertEntries)
faq.POST("/entry", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateEntry)
faq.PUT("/entries/:entry_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntry)
@@ -374,9 +381,9 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryFieldsBatch)
faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryTagBatch)
faq.DELETE("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteEntries)
- // Search is a read: Viewer keys may call it even though the group
- // default is Contributor (POST is otherwise an unsafe method).
- faq.With(apiKeyViewer()).POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ)
+ // Search is a read route: scoped API keys may call it with retrieve
+ // even though POST is otherwise an unsafe method.
+ faqRead.POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ)
// FAQ import result display status
faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateLastImportResultDisplayStatus)
}
@@ -389,21 +396,24 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
// RegisterKnowledgeBaseRoutes 注册知识库相关的路由
func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeBaseHandler, g *rbacGuards) {
- // 知识库路由组。API key 默认可读(Viewer,限 KB 范围);写入 Contributor+;
- // 创建/拷贝 KB 不对 API key 开放(注册在原始 group 上,默认拒绝)。
+ // 知识库路由组。Scoped API key 需要 retrieve 能力读取(限 KB 范围);KB 内容写入
+ // 由 RegisterKnowledgeRoutes/FAQ/Tag/Wiki 等子路由的 ingest 能力控制;
+ // KB 自身的元数据/生命周期管理需要 full access 或 manage_kbs。创建/拷贝
+ // KB 没有单个目标 KB 可约束,继续不对 scoped API key 开放。
kbgrp := r.Group("/knowledge-bases")
- kb := g.apiKeyGroup(kbgrp, apiKeyViewer())
+ kb := g.apiKeyGroup(kbgrp, apiKeyRetrieve(apiKeyFullAccess()))
+ kbManagement := kb.With(apiKeyManageKnowledgeBases(apiKeyFullAccess()))
{
- // 创建知识库 — Contributor+ (no :id, role-only floor); API keys may not create KBs.
+ // 创建知识库 — Contributor+ for JWT callers; API keys may not create KBs.
kbgrp.POST("", g.Contributor(), handler.CreateKnowledgeBase)
- // 获取知识库列表 — Viewer+ (no :id, role-only floor)
+ // 获取知识库列表 — 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 权限
- kb.With(apiKeyContributor()).PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
+ kbManagement.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
- kb.With(apiKeyContributor()).DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
+ 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
// at least Viewer-level read access to the KB — including users
@@ -411,7 +421,7 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
// no edit permission is required. The OwnedKBOrAdmin guard was
// removed accordingly. The route still requires KB read access
// so callers can't poke at KBs they can't see.
- kb.With(apiKeyContributor()).PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
+ kb.PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
// 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)
@@ -437,13 +447,14 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
// Tags 是 KB 的子资源 — 创建/编辑/删除标签会改变 KB 内容的检索分类
// 行为,应该与 KB 主体的"creator OR Admin+"矩阵一致,避免一个无
// 关 Contributor 在他人 KB 里乱建/删标签影响 KB owner 的内容组织。
- kbTags := g.apiKeyGroup(r.Group("/knowledge-bases/:id/tags"), apiKeyContributor())
+ kbTags := g.apiKeyGroup(r.Group("/knowledge-bases/:id/tags"), apiKeyIngest(apiKeyFullAccess()))
+ kbTagsRead := kbTags.With(apiKeyRetrieve(apiKeyFullAccess()))
{
// KBAccessRead/Write resolve own/shared/agent-visible access and
// rewrite the request's tenant context to the effective tenant
// for the duration of the handler — so the handler no longer
// needs its own effectiveCtxForKB helper.
- kbTags.GET("", g.Viewer(), g.KBAccessRead("id"), tagHandler.ListTags)
+ kbTagsRead.GET("", g.Viewer(), g.KBAccessRead("id"), tagHandler.ListTags)
kbTags.POST("", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.CreateTag)
kbTags.PUT("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.UpdateTag)
kbTags.DELETE("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.DeleteTag)
@@ -458,14 +469,20 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
// reach the endpoints at all once RBAC is on.
func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler, g *rbacGuards) {
// Message history is tenant-wide and not attributable to a KB, so it is
- // a tenant-level (Owner) surface for API keys — only a full-access key
- // may read or delete it.
- messages := g.apiKeyGroup(r.Group("/messages"), apiKeyOwner())
+ // a full-access surface for API keys by default. The narrow
+ // exceptions are explicit capabilities:
+ // - chat: load/delete messages inside the caller's own session, where
+ // ownership is enforced by the message service.
+ // - message_history: search/read tenant chat-history metadata without
+ // granting every other full-access API.
+ messages := g.apiKeyGroup(r.Group("/messages"), apiKeyFullAccess())
+ chatMessages := messages.With(apiKeyChat(apiKeyFullAccess()))
+ historyMessages := messages.With(apiKeyMessageHistory(apiKeyFullAccess()))
{
- messages.POST("/search", g.Viewer(), handler.SearchMessages)
- messages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
- messages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
- messages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage)
+ historyMessages.POST("/search", g.Viewer(), handler.SearchMessages)
+ historyMessages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
+ chatMessages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
+ chatMessages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage)
}
}
@@ -477,7 +494,10 @@ func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler,
// per-session ownership in the middleware layer the same way KB/agent
// routes do today.
func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
- sessions := g.apiKeyGroup(r.Group("/sessions", g.Viewer()), apiKeyContributor())
+ // Sessions are per-user chat state, not knowledge-base content. The
+ // chat capability lets a scoped key run the full conversation flow
+ // (create/manage its own sessions) without full tenant access.
+ sessions := g.apiKeyGroup(r.Group("/sessions", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
{
sessions.POST("", handler.CreateSession)
sessions.DELETE("/batch", handler.BatchDeleteSessions)
@@ -503,19 +523,21 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbac
// surfaces; Viewer+ is sufficient because per-session/per-agent
// authorisation is enforced inside the handlers.
func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
- knowledgeChat := g.apiKeyGroup(r.Group("/knowledge-chat", g.Viewer()), apiKeyViewer())
+ // These POST routes append messages and run generation, so a scoped key
+ // needs the explicit chat capability unless it has full tenant access.
+ knowledgeChat := g.apiKeyGroup(r.Group("/knowledge-chat", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
{
knowledgeChat.POST("/:session_id", handler.KnowledgeQA)
}
// Agent-based chat
- agentChat := g.apiKeyGroup(r.Group("/agent-chat", g.Viewer()), apiKeyViewer())
+ agentChat := g.apiKeyGroup(r.Group("/agent-chat", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
{
agentChat.POST("/:session_id", handler.AgentQA)
}
// 新增知识检索接口,不需要session_id
- knowledgeSearch := g.apiKeyGroup(r.Group("/knowledge-search", g.Viewer()), apiKeyViewer())
+ knowledgeSearch := g.apiKeyGroup(r.Group("/knowledge-search", g.Viewer()), apiKeyRetrieve(apiKeyFullAccess()))
{
knowledgeSearch.POST("", handler.SearchKnowledge)
}
@@ -577,15 +599,15 @@ func RegisterTenantRoutes(
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
// 创建租户不对 API key 开放(注册在原始 group,默认拒绝)。
tenantRoutes.POST("", handler.CreateTenant)
- g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyOwner(), handler.ListTenants)
+ g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyManageTenantSettings(apiKeyFullAccess()), handler.ListTenants)
// Generic KV configuration management (tenant-level). Tenant ID
// is obtained from authentication context; the URL :key is a
// config key, not a tenant ID, so these stay outside the
- // PathTenantMatch group. Tenant-level surface: only a full-access
- // (Owner) API key may read or write it.
- g.apiKeyRoute(tenantRoutes, http.MethodGet, "/kv/:key", apiKeyOwner(), g.Viewer(), handler.GetTenantKV)
- g.apiKeyRoute(tenantRoutes, http.MethodPut, "/kv/:key", apiKeyOwner(), g.Admin(), handler.UpdateTenantKV)
+ // PathTenantMatch group. Tenant-level surface: full-access keys may
+ // call it, and scoped keys need manage_tenant_settings.
+ g.apiKeyRoute(tenantRoutes, http.MethodGet, "/kv/:key", apiKeyManageTenantSettings(apiKeyFullAccess()), g.Viewer(), handler.GetTenantKV)
+ 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,
@@ -659,7 +681,7 @@ func RegisterModelRoutes(
g *rbacGuards,
) {
// 模型路由组。租户级基础设施:仅完全访问(Owner)API key 可访问。
- models := g.apiKeyGroup(r.Group("/models"), apiKeyOwner())
+ models := g.apiKeyGroup(r.Group("/models"), apiKeyManageModels(apiKeyFullAccess()))
{
// 获取模型厂商列表 — Viewer+
models.GET("/providers", g.Viewer(), handler.ListModelProviders)
@@ -686,7 +708,7 @@ func RegisterModelRoutes(
// tenant; gate to Admin+ until product asks for a finer-grained
// matrix.
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler, g *rbacGuards) {
- evaluationRoutes := g.apiKeyGroup(r.Group("/evaluation"), apiKeyOwner())
+ evaluationRoutes := g.apiKeyGroup(r.Group("/evaluation"), apiKeyRunEvaluations(apiKeyFullAccess()))
{
evaluationRoutes.POST("", g.Admin(), handler.Evaluation)
evaluationRoutes.GET("", g.Viewer(), handler.GetEvaluationResult)
@@ -720,7 +742,7 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
}
// RegisterAuthRoutes registers authentication routes
-func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
+func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler, g *rbacGuards) {
r.POST("/auth/register", handler.Register)
// Share-link surfaces are unauthenticated and accept a plaintext
// token from the caller; rate-limit by IP to bound brute-force /
@@ -740,7 +762,10 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/refresh", handler.RefreshToken)
r.GET("/auth/validate", handler.ValidateToken)
r.POST("/auth/logout", handler.Logout)
- r.GET("/auth/me", handler.GetCurrentUser)
+ // auth/me returns only the caller's own identity/profile, so it is safe
+ // for any valid API key. Chat clients / MCP call it to discover "who am I";
+ // leaving it default-deny was why scoped keys got a 403 here.
+ g.apiKeyRoute(r, http.MethodGet, "/auth/me", apiKeyAny(), handler.GetCurrentUser)
r.PUT("/auth/me/preferences", handler.UpdateMyPreferences)
r.POST("/auth/change-password", handler.ChangePassword)
}
@@ -749,35 +774,35 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
// 初始化接口
// GetCurrentConfigByKB 是只读,Viewer+ 即可(KB 受限 key 可读其范围内的 KB)。
g.apiKeyRoute(r, http.MethodGet, "/initialization/config/:kbId",
- apiKeyViewer(), g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
+ apiKeyRetrieve(apiKeyFullAccess()), g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵 + KBAccessWrite
//(API-key 主体短路 Owned* 守卫,KB allow-list 只能靠 KBAccess 兜底)。
g.apiKeyRoute(r, http.MethodPost, "/initialization/initialize/:kbId",
- apiKeyContributor(), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.InitializeByKB)
+ apiKeyManageKnowledgeBases(apiKeyFullAccess()), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.InitializeByKB)
g.apiKeyRoute(r, http.MethodPut, "/initialization/config/:kbId",
- apiKeyContributor(), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.UpdateKBConfig)
+ apiKeyManageKnowledgeBases(apiKeyFullAccess()), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.UpdateKBConfig)
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
// 会改租户级模型配置或拉远端模型;JWT 侧只读探测 Viewer+、变更 Admin+。
- // 对 API key 均为租户级:仅完全访问(Owner)key 可用。
- g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/status", apiKeyOwner(), g.Viewer(), handler.CheckOllamaStatus)
- g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/models", apiKeyOwner(), g.Viewer(), handler.ListOllamaModels)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/check", apiKeyOwner(), g.Admin(), handler.CheckOllamaModels)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/download", apiKeyOwner(), g.Admin(), handler.DownloadOllamaModel)
- g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/progress/:taskId", apiKeyOwner(), g.Viewer(), handler.GetDownloadProgress)
- g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/tasks", apiKeyOwner(), g.Viewer(), handler.ListDownloadTasks)
+ // 对 API key 均为租户级:full-access key 可用,scoped key 需要 manage_models。
+ g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/status", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.CheckOllamaStatus)
+ g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/models", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.ListOllamaModels)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckOllamaModels)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/download", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.DownloadOllamaModel)
+ g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/progress/:taskId", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.GetDownloadProgress)
+ g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/tasks", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.ListDownloadTasks)
// 远程API相关接口
- g.apiKeyRoute(r, http.MethodPost, "/initialization/remote/check", apiKeyOwner(), g.Admin(), handler.CheckRemoteModel)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/embedding/test", apiKeyOwner(), g.Admin(), handler.TestEmbeddingModel)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/rerank/check", apiKeyOwner(), g.Admin(), handler.CheckRerankModel)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/asr/check", apiKeyOwner(), g.Admin(), handler.CheckASRModel)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/multimodal/test", apiKeyOwner(), g.Admin(), handler.TestMultimodalFunction)
-
- g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/text-relation", apiKeyOwner(), g.Admin(), handler.ExtractTextRelations)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-tag", apiKeyOwner(), g.Admin(), handler.FabriTag)
- g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-text", apiKeyOwner(), g.Admin(), handler.FabriText)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/remote/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckRemoteModel)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/embedding/test", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.TestEmbeddingModel)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/rerank/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckRerankModel)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/asr/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckASRModel)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/multimodal/test", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.TestMultimodalFunction)
+
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/text-relation", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.ExtractTextRelations)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-tag", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.FabriTag)
+ g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-text", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.FabriText)
}
// RegisterSystemRoutes registers system information routes
@@ -788,7 +813,7 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
// remote services with tenant credentials and could trigger network
// fanout, so they're Admin+.
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
- systemRoutes := g.apiKeyGroup(r.Group("/system"), apiKeyOwner())
+ systemRoutes := g.apiKeyGroup(r.Group("/system"), apiKeyManageVectorStores(apiKeyFullAccess()))
{
systemRoutes.GET("/info", g.Viewer(), handler.GetSystemInfo)
systemRoutes.GET("/parser-engines", g.Viewer(), handler.ListParserEngines)
@@ -881,7 +906,7 @@ func RegisterMCPServiceRoutes(
// redirect carries no WeKnora bearer — the single-use state authenticates.
r.GET("/mcp-oauth/callback", oauthHandler.Callback)
- mcpServices := g.apiKeyGroup(r.Group("/mcp-services"), apiKeyOwner())
+ mcpServices := g.apiKeyGroup(r.Group("/mcp-services"), apiKeyManageMCPServices(apiKeyFullAccess()))
{
// Create MCP service — Admin+
mcpServices.POST("", g.Admin(), handler.CreateMCPService)
@@ -953,7 +978,7 @@ func RegisterWebSearchProviderRoutes(
credHandler *handler.WebSearchProviderCredentialsHandler,
g *rbacGuards,
) {
- providers := g.apiKeyGroup(r.Group("/web-search-providers"), apiKeyOwner())
+ providers := g.apiKeyGroup(r.Group("/web-search-providers"), apiKeyManageWebSearch(apiKeyFullAccess()))
{
// List available provider types (metadata for UI forms) — Viewer+
providers.GET("/types", g.Viewer(), h.ListProviderTypes)
@@ -979,7 +1004,7 @@ func RegisterWebSearchProviderRoutes(
// writes (and connection tests, which probe external systems with stored
// credentials) are Admin+.
func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler, g *rbacGuards) {
- stores := g.apiKeyGroup(r.Group("/vector-stores"), apiKeyOwner())
+ stores := g.apiKeyGroup(r.Group("/vector-stores"), apiKeyManageVectorStores(apiKeyFullAccess()))
{
// List available engine types (metadata for UI forms) — Viewer+
stores.GET("/types", g.Viewer(), h.ListStoreTypes)
@@ -1003,27 +1028,35 @@ func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler
// (IsBuiltin=true) have an empty creator and are always Admin+. Reads
// are Viewer+, copy is Contributor+ (the copy is owned by the caller).
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler, g *rbacGuards) {
- agents := g.apiKeyGroup(r.Group("/agents"), apiKeyOwner())
+ agents := g.apiKeyGroup(r.Group("/agents"), apiKeyFullAccess())
+ // agentsRead are the agent read endpoints. They stay full-access only for
+ // plain scoped keys (agent config can carry sensitive model/MCP bindings),
+ // but read_agents, chat, or manage_agents may read them.
+ agentsRead := agents.With(apiKeyReadAgents(apiKeyManageAgents(apiKeyChat(apiKeyFullAccess()))))
+ // agentsWrite are the agent authoring endpoints. Owner by default, but a
+ // key granted manage_agents may author agents without full Owner.
+ agentsWrite := agents.With(apiKeyManageAgents(apiKeyFullAccess()))
{
// Get placeholder definitions (must be before /:id to avoid conflict) — Viewer+
- agents.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
+ agentsRead.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
// List smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom) — Viewer+
- agents.GET("/type-presets", g.Viewer(), agentHandler.GetAgentTypePresets)
+ agentsRead.GET("/type-presets", g.Viewer(), agentHandler.GetAgentTypePresets)
// Create custom agent — Contributor+
- agents.POST("", g.Contributor(), agentHandler.CreateAgent)
+ agentsWrite.POST("", g.Contributor(), agentHandler.CreateAgent)
// List all agents (including built-in) — Viewer+
- agents.GET("", g.Viewer(), agentHandler.ListAgents)
+ agentsRead.GET("", g.Viewer(), agentHandler.ListAgents)
// Get agent by ID — Viewer+
- agents.GET("/:id", g.Viewer(), agentHandler.GetAgent)
+ agentsRead.GET("/:id", g.Viewer(), agentHandler.GetAgent)
// Update agent — creator OR Admin+
- agents.PUT("/:id", g.OwnedAgentOrAdmin(), agentHandler.UpdateAgent)
+ agentsWrite.PUT("/:id", g.OwnedAgentOrAdmin(), agentHandler.UpdateAgent)
// Delete agent — creator OR Admin+
- agents.DELETE("/:id", g.OwnedAgentOrAdmin(), agentHandler.DeleteAgent)
+ agentsWrite.DELETE("/:id", g.OwnedAgentOrAdmin(), agentHandler.DeleteAgent)
// Copy agent — Contributor+ (copy is owned by the caller)
- agents.POST("/:id/copy", g.Contributor(), agentHandler.CopyAgent)
+ agentsWrite.POST("/:id/copy", g.Contributor(), agentHandler.CopyAgent)
}
// Registered outside the group to avoid Gin route conflict with /agents/:id/shares in organization routes
- g.apiKeyRoute(r, http.MethodGet, "/agents/:id/suggested-questions", apiKeyOwner(), g.Viewer(), agentHandler.GetSuggestedQuestions)
+ g.apiKeyRoute(r, http.MethodGet, "/agents/:id/suggested-questions",
+ apiKeyReadAgents(apiKeyManageAgents(apiKeyChat(apiKeyFullAccess()))), g.Viewer(), agentHandler.GetSuggestedQuestions)
}
// RegisterUserFavoriteRoutes wires the per-user starred-resource endpoints.
@@ -1059,7 +1092,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"), apiKeyOwner())
+ orgs := g.apiKeyGroup(r.Group("/organizations"), apiKeyFullAccess())
{
// Create organization (Admin+ in caller's tenant only)
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
@@ -1169,13 +1202,13 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
}
// Shared knowledge bases route — Viewer+
- g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyOwner(), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
+ g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
// Shared agents route — Viewer+
- g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyOwner(), g.Viewer(), orgHandler.ListSharedAgents)
+ g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedAgents)
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
- g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyOwner(), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
+ g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyFullAccess(), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
}
// RegisterEmbedPublicRoutes registers anonymous embed endpoints secured by publish tokens.
@@ -1219,12 +1252,12 @@ func RegisterEmbedChannelRoutes(r *gin.RouterGroup, embedHandler *handler.EmbedC
if embedHandler == nil {
return
}
- agentEmbed := g.apiKeyGroup(r.Group("/agents/:id/embed-channels"), apiKeyOwner())
+ agentEmbed := g.apiKeyGroup(r.Group("/agents/:id/embed-channels"), apiKeyManageChannels(apiKeyFullAccess()))
{
agentEmbed.POST("", g.Admin(), embedHandler.CreateEmbedChannel)
agentEmbed.GET("", g.Viewer(), embedHandler.ListEmbedChannels)
}
- channels := g.apiKeyGroup(r.Group("/embed-channels"), apiKeyOwner())
+ channels := g.apiKeyGroup(r.Group("/embed-channels"), apiKeyManageChannels(apiKeyFullAccess()))
{
channels.GET("", g.Viewer(), embedHandler.ListAllEmbedChannels)
channels.GET("/:channel_id", g.Viewer(), embedHandler.GetEmbedChannel)
@@ -1253,14 +1286,14 @@ func RegisterIMRoutes(r *gin.Engine, imHandler *handler.IMHandler) {
// (which can hijack a personal WeChat session) is Admin+.
func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g *rbacGuards) {
// Channel CRUD under agents
- agentChannels := g.apiKeyGroup(r.Group("/agents/:id/im-channels"), apiKeyOwner())
+ agentChannels := g.apiKeyGroup(r.Group("/agents/:id/im-channels"), apiKeyManageChannels(apiKeyFullAccess()))
{
agentChannels.POST("", g.Admin(), imHandler.CreateIMChannel)
agentChannels.GET("", g.Viewer(), imHandler.ListIMChannels)
}
// Channel operations by channel ID
- channels := g.apiKeyGroup(r.Group("/im-channels"), apiKeyOwner())
+ channels := g.apiKeyGroup(r.Group("/im-channels"), apiKeyManageChannels(apiKeyFullAccess()))
{
channels.GET("", g.Viewer(), imHandler.ListAllIMChannels)
channels.PUT("/:id", g.Admin(), imHandler.UpdateIMChannel)
@@ -1270,7 +1303,7 @@ func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g
// WeChat QR code login (requires authentication) — Admin+: a successful
// scan binds a personal WeChat account to the tenant.
- wechatGroup := g.apiKeyGroup(r.Group("/wechat"), apiKeyOwner())
+ wechatGroup := g.apiKeyGroup(r.Group("/wechat"), apiKeyManageChannels(apiKeyFullAccess()))
{
wechatGroup.POST("/qrcode", g.Admin(), imHandler.WeChatGetQRCode)
wechatGroup.POST("/qrcode/status", g.Admin(), imHandler.WeChatPollQRCodeStatus)
@@ -1738,7 +1771,7 @@ func RegisterDataSourceRoutes(
g *rbacGuards,
) {
// Data source routes
- ds := g.apiKeyGroup(r.Group("/datasource"), apiKeyOwner())
+ ds := g.apiKeyGroup(r.Group("/datasource"), apiKeyManageDataSources(apiKeyFullAccess()))
{
// Get available connector types — Viewer+
ds.GET("/types", g.Viewer(), handler.GetAvailableConnectors)
@@ -1780,8 +1813,8 @@ func RegisterDataSourceRoutes(
// management endpoints. SaveCredentials persists external SaaS keys
// for the tenant (Admin+), Status is a low-risk readiness probe (Viewer+).
func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler, g *rbacGuards) {
- g.apiKeyRoute(r, http.MethodPost, "/weknoracloud/credentials", apiKeyOwner(), g.Admin(), handler.SaveCredentials)
- g.apiKeyRoute(r, http.MethodGet, "/models/weknoracloud/status", apiKeyOwner(), g.Viewer(), handler.Status)
+ g.apiKeyRoute(r, http.MethodPost, "/weknoracloud/credentials", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.SaveCredentials)
+ g.apiKeyRoute(r, http.MethodGet, "/models/weknoracloud/status", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.Status)
}
// RegisterWikiPageRoutes registers wiki page related routes.
@@ -1794,38 +1827,39 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
// :kb_id resolves directly to the owning KB so a Contributor who owns
// the KB can manage its wiki, while a non-owner Contributor gets 403.
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) {
- wiki := g.apiKeyGroup(r.Group("/knowledgebase/:kb_id/wiki"), apiKeyContributor())
+ wiki := g.apiKeyGroup(r.Group("/knowledgebase/:kb_id/wiki"), apiKeyIngest(apiKeyFullAccess()))
+ wikiRead := wiki.With(apiKeyRetrieve(apiKeyFullAccess()))
{
// Page CRUD
- wiki.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
+ wikiRead.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
wiki.POST("/pages", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.CreatePage)
wiki.PUT("/move-page", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.MovePage)
- wiki.GET("/pages/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetPage)
+ wikiRead.GET("/pages/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetPage)
wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdatePage)
wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.DeletePage)
// Folder tree (directory nodes)
- wiki.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
+ wikiRead.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
wiki.POST("/folders", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.CreateFolder)
wiki.PUT("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdateFolder)
wiki.DELETE("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.DeleteFolder)
// Special pages
- wiki.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)
- wiki.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)
+ wikiRead.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)
+ wikiRead.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)
// Graph and stats
- wiki.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)
- wiki.GET("/stats", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetStats)
+ wikiRead.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)
+ wikiRead.GET("/stats", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetStats)
// Search and maintenance
- wiki.GET("/search", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.SearchPages)
+ wikiRead.GET("/search", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.SearchPages)
wiki.POST("/rebuild-links", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.RebuildLinks)
- wiki.GET("/lint", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.Lint)
+ wikiRead.GET("/lint", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.Lint)
wiki.POST("/auto-fix", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.AutoFix)
// Issues
- wiki.GET("/issues", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListIssues)
+ wikiRead.GET("/issues", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListIssues)
wiki.PUT("/issues/:issue_id/status", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdateIssueStatus)
}
}
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
new file mode 100644
index 000000000..db7d5a6de
--- /dev/null
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -0,0 +1,317 @@
+package router
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/handler"
+ sessionhandler "github.com/Tencent/WeKnora/internal/handler/session"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/gin-gonic/gin"
+)
+
+func TestConversationRoutesDeclareChatCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterSessionRoutes(v1, &sessionhandler.Handler{}, g)
+ RegisterChatRoutes(v1, &sessionhandler.Handler{}, g)
+ RegisterMessageRoutes(v1, &handler.MessageHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodPost, "/api/v1/sessions"},
+ {http.MethodPost, "/api/v1/knowledge-chat/:session_id"},
+ {http.MethodPost, "/api/v1/agent-chat/:session_id"},
+ {http.MethodGet, "/api/v1/messages/:session_id/load"},
+ {http.MethodDelete, "/api/v1/messages/:session_id/:id"},
+ }
+
+ 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.APIKeyCapabilityChat) {
+ t.Fatalf("policy capabilities = %#v, want chat", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestMessageHistoryRoutesDeclareMessageHistoryCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterMessageRoutes(v1, &handler.MessageHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodPost, "/api/v1/messages/search"},
+ {http.MethodGet, "/api/v1/messages/chat-history-stats"},
+ }
+
+ 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.APIKeyCapabilityMessageHistory) {
+ t.Fatalf("policy capabilities = %#v, want message_history", policy.Capabilities)
+ }
+ if policyHasCapability(policy, types.APIKeyCapabilityChat) {
+ t.Fatalf("message-history route must not be granted by chat: %#v", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestAgentReadRoutesDeclareReadAgentsCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterCustomAgentRoutes(v1, &handler.CustomAgentHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodGet, "/api/v1/agents/placeholders"},
+ {http.MethodGet, "/api/v1/agents/type-presets"},
+ {http.MethodGet, "/api/v1/agents"},
+ {http.MethodGet, "/api/v1/agents/:id"},
+ {http.MethodGet, "/api/v1/agents/:id/suggested-questions"},
+ }
+
+ 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.APIKeyCapabilityReadAgents) {
+ t.Fatalf("policy capabilities = %#v, want read_agents", policy.Capabilities)
+ }
+ if !policyHasCapability(policy, types.APIKeyCapabilityChat) {
+ t.Fatalf("policy capabilities = %#v, want chat for conversation clients", policy.Capabilities)
+ }
+ if !policyHasCapability(policy, types.APIKeyCapabilityManageAgents) {
+ t.Fatalf("policy capabilities = %#v, want manage_agents for authoring clients", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestAgentWriteRoutesRequireManageAgentsCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterCustomAgentRoutes(v1, &handler.CustomAgentHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodPost, "/api/v1/agents"},
+ {http.MethodPut, "/api/v1/agents/:id"},
+ {http.MethodDelete, "/api/v1/agents/:id"},
+ {http.MethodPost, "/api/v1/agents/:id/copy"},
+ }
+
+ 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.APIKeyCapabilityManageAgents) {
+ t.Fatalf("policy capabilities = %#v, want manage_agents", policy.Capabilities)
+ }
+ if policyHasCapability(policy, types.APIKeyCapabilityReadAgents) {
+ t.Fatalf("agent write route must not be granted by read_agents: %#v", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestKnowledgeBaseManagementRoutesDeclareManageKBsCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
+ RegisterInitializationRoutes(v1, &handler.InitializationHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodPut, "/api/v1/knowledge-bases/:id"},
+ {http.MethodDelete, "/api/v1/knowledge-bases/:id"},
+ {http.MethodPost, "/api/v1/initialization/initialize/:kbId"},
+ {http.MethodPut, "/api/v1/initialization/config/:kbId"},
+ }
+
+ 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.APIKeyCapabilityManageKnowledgeBases) {
+ t.Fatalf("policy capabilities = %#v, want manage_kbs", policy.Capabilities)
+ }
+ if policyHasCapability(policy, types.APIKeyCapabilityIngest) {
+ t.Fatalf("KB management route must not be granted by ingest: %#v", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestKnowledgeBaseCreateAndCopyRemainDefaultDenyForAPIKeys(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodPost, "/api/v1/knowledge-bases"},
+ {http.MethodPost, "/api/v1/knowledge-bases/copy"},
+ }
+
+ 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)
+ }
+ })
+ }
+}
+
+func TestKnowledgeReadRoutesDeclareRetrieveCapability(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
+ RegisterKnowledgeRoutes(v1, &handler.KnowledgeHandler{}, g)
+ RegisterFAQRoutes(v1, &handler.FAQHandler{}, g)
+ RegisterKnowledgeTagRoutes(v1, &handler.TagHandler{}, g)
+ RegisterChatRoutes(v1, &sessionhandler.Handler{}, g)
+ RegisterInitializationRoutes(v1, &handler.InitializationHandler{}, g)
+ RegisterWikiPageRoutes(v1, &handler.WikiPageHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ }{
+ {http.MethodGet, "/api/v1/knowledge-bases"},
+ {http.MethodGet, "/api/v1/knowledge-bases/:id"},
+ {http.MethodPost, "/api/v1/knowledge-bases/:id/hybrid-search"},
+ {http.MethodGet, "/api/v1/knowledge-bases/:id/knowledge"},
+ {http.MethodGet, "/api/v1/knowledge/:id"},
+ {http.MethodPost, "/api/v1/knowledge-bases/:id/faq/search"},
+ {http.MethodGet, "/api/v1/knowledge-bases/:id/tags"},
+ {http.MethodPost, "/api/v1/knowledge-search"},
+ {http.MethodGet, "/api/v1/initialization/config/:kbId"},
+ {http.MethodGet, "/api/v1/knowledgebase/:kb_id/wiki/pages"},
+ }
+
+ 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.APIKeyCapabilityRetrieve) {
+ t.Fatalf("policy capabilities = %#v, want retrieve", policy.Capabilities)
+ }
+ })
+ }
+}
+
+func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterTenantRoutes(v1, &handler.TenantHandler{}, nil, nil, nil, g)
+ RegisterModelRoutes(v1, &handler.ModelHandler{}, &handler.ModelCredentialsHandler{}, g)
+ RegisterEvaluationRoutes(v1, &handler.EvaluationHandler{}, g)
+ RegisterSystemRoutes(v1, &handler.SystemHandler{}, g)
+ RegisterMCPServiceRoutes(v1, &handler.MCPServiceHandler{}, &handler.MCPCredentialsHandler{}, &handler.MCPOAuthHandler{}, g)
+ RegisterWebSearchProviderRoutes(v1, &handler.WebSearchProviderHandler{}, &handler.WebSearchProviderCredentialsHandler{}, g)
+ RegisterVectorStoreRoutes(v1, &handler.VectorStoreHandler{}, g)
+ RegisterEmbedChannelRoutes(v1, &handler.EmbedChannelHandler{}, g)
+ RegisterIMChannelRoutes(v1, &handler.IMHandler{}, g)
+ RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
+ RegisterWeKnoraCloudRoutes(v1, &handler.WeKnoraCloudHandler{}, g)
+
+ cases := []struct {
+ method string
+ path string
+ cap types.APIKeyCapability
+ }{
+ {http.MethodGet, "/api/v1/tenants", types.APIKeyCapabilityManageTenantSettings},
+ {http.MethodGet, "/api/v1/models", types.APIKeyCapabilityManageModels},
+ {http.MethodPost, "/api/v1/evaluation", types.APIKeyCapabilityRunEvaluations},
+ {http.MethodGet, "/api/v1/system/info", types.APIKeyCapabilityManageVectorStores},
+ {http.MethodGet, "/api/v1/mcp-services", types.APIKeyCapabilityManageMCPServices},
+ {http.MethodGet, "/api/v1/web-search-providers", types.APIKeyCapabilityManageWebSearch},
+ {http.MethodGet, "/api/v1/vector-stores", types.APIKeyCapabilityManageVectorStores},
+ {http.MethodGet, "/api/v1/embed-channels", types.APIKeyCapabilityManageChannels},
+ {http.MethodGet, "/api/v1/im-channels", types.APIKeyCapabilityManageChannels},
+ {http.MethodGet, "/api/v1/datasource", types.APIKeyCapabilityManageDataSources},
+ {http.MethodGet, "/api/v1/models/weknoracloud/status", types.APIKeyCapabilityManageModels},
+ }
+
+ 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, tc.cap) {
+ t.Fatalf("policy capabilities = %#v, want %s", policy.Capabilities, tc.cap)
+ }
+ })
+ }
+}
+
+func mustLookupAPIKeyPolicy(
+ t *testing.T,
+ g *rbacGuards,
+ method string,
+ path string,
+) middleware.APIKeyRoutePolicy {
+ t.Helper()
+ policy, ok := g.apiKeyAuthorizer.Lookup(method, path)
+ if !ok {
+ t.Fatalf("missing API-key policy for %s %s", method, path)
+ }
+ return policy
+}
+
+func policyHasCapability(policy middleware.APIKeyRoutePolicy, cap types.APIKeyCapability) bool {
+ for _, got := range policy.Capabilities {
+ if got == cap {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/router/router_api_key_management_test.go b/internal/router/router_api_key_management_test.go
index fc71bd232..1d3718ae9 100644
--- a/internal/router/router_api_key_management_test.go
+++ b/internal/router/router_api_key_management_test.go
@@ -12,7 +12,7 @@ import (
// TestAPIKeyGateDeniesTenantKeyManagementPaths guards the default-deny
// contract: tenant lifecycle, key management and API-principal config routes
-// are registered without apiKeyRoute/apiKeyGroup, so even an Owner-role API
+// are registered without apiKeyRoute/apiKeyGroup, so even a full-access API
// key must receive 403 from the gate before JWT-only handlers run.
func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -20,7 +20,7 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
gate := middleware.NewAPIKeyRouteAuthorizer()
engine := gin.New()
engine.Use(func(c *gin.Context) {
- scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
+ scope := types.TenantAPIKeyScope{FullAccess: true}
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope))
c.Next()
})
@@ -66,17 +66,17 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
}
// TestAPIKeyGateAllowsDeclaredTenantKVRead confirms the gate still permits
-// routes that are explicitly declared for Owner API keys (sanity check).
+// routes that are explicitly declared for full-access API keys (sanity check).
func TestAPIKeyGateAllowsDeclaredTenantKVRead(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
- g.apiKeyRoute(v1.Group("/tenants"), http.MethodGet, "/kv/:key", apiKeyOwner(), reachedOK)
+ g.apiKeyRoute(v1.Group("/tenants"), http.MethodGet, "/kv/:key", apiKeyFullAccess(), reachedOK)
engine := gin.New()
engine.Use(func(c *gin.Context) {
- scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
+ scope := types.TenantAPIKeyScope{FullAccess: true}
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope))
c.Next()
})
diff --git a/internal/router/router_files_test.go b/internal/router/router_files_test.go
index 3d5ff16fe..77ae1a1c7 100644
--- a/internal/router/router_files_test.go
+++ b/internal/router/router_files_test.go
@@ -168,7 +168,7 @@ func TestServeFilesRejectsAPIKeyPrincipal(t *testing.T) {
filePath := "local://42/docs/example.txt"
req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(filePath), nil)
ctx := context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42})
- ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{Role: types.TenantRoleOwner})
+ ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{FullAccess: true})
req = req.WithContext(ctx)
recorder := httptest.NewRecorder()
diff --git a/internal/router/router_wiki_test.go b/internal/router/router_wiki_test.go
index e3769c5b4..567c3b708 100644
--- a/internal/router/router_wiki_test.go
+++ b/internal/router/router_wiki_test.go
@@ -66,9 +66,8 @@ func newKBRouteTestEngine(
role := types.TenantRoleViewer
if apiKeyScope != nil {
ctx = types.WithTenantAPIKeyScope(ctx, *apiKeyScope)
- role = apiKeyScope.Role
- if role == "" {
- role = types.TenantRoleViewer
+ if apiKeyScope.FullAccess {
+ role = types.TenantRoleOwner
}
}
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
@@ -142,8 +141,8 @@ func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {
func TestInitializationWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
kbLookup := tenantKBLookupFixture()
scope := &types.TenantAPIKeyScope{
- Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
+ Capabilities: types.StringArray{string(types.APIKeyCapabilityManageKnowledgeBases)},
}
engine := newKBRouteTestEngine(t, 1, kbLookup, scope, func(r *gin.RouterGroup, guards *rbacGuards) {
RegisterInitializationRoutes(r, &handler.InitializationHandler{}, guards)
@@ -172,8 +171,8 @@ func TestInitializationWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
func TestWikiWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
kbLookup := tenantKBLookupFixture()
scope := &types.TenantAPIKeyScope{
- Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
+ Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
}
engine := newKBRouteTestEngine(t, 1, kbLookup, scope, func(r *gin.RouterGroup, guards *rbacGuards) {
RegisterWikiPageRoutes(r, &handler.WikiPageHandler{}, guards)
diff --git a/internal/types/interfaces/tenant.go b/internal/types/interfaces/tenant.go
index ee5c0d3c6..6bfa698e7 100644
--- a/internal/types/interfaces/tenant.go
+++ b/internal/types/interfaces/tenant.go
@@ -65,8 +65,9 @@ type TenantRepository interface {
type TenantAPIKeyCreateRequest struct {
TenantID uint64
Name string
- Role types.TenantRole
+ FullAccess bool
KnowledgeBaseIDs []string
+ Capabilities []string
ExpiresAt *time.Time
}
diff --git a/internal/types/tenant_api_key.go b/internal/types/tenant_api_key.go
index dee6cc957..d33043dbd 100644
--- a/internal/types/tenant_api_key.go
+++ b/internal/types/tenant_api_key.go
@@ -20,19 +20,148 @@ type TenantAPIKey struct {
Name string `json:"name" gorm:"type:varchar(128);not null"`
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
- Role TenantRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
+ FullAccess bool `json:"full_access" gorm:"not null;default:false"`
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
- LastUsedAt *time.Time `json:"last_used_at,omitempty"`
- ExpiresAt *time.Time `json:"expires_at,omitempty"`
- RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ // Capabilities are bounded grants for non-full-access keys. Each
+ // capability maps to an integration persona (retrieval, chat, ingest,
+ // tenant infrastructure management, and history access). KB scoping
+ // (KnowledgeBaseIDs) still applies on top where a route targets knowledge
+ // bases.
+ Capabilities StringArray `json:"capabilities" gorm:"type:jsonb;not null;default:'[]'"`
+ LastUsedAt *time.Time `json:"last_used_at,omitempty"`
+ ExpiresAt *time.Time `json:"expires_at,omitempty"`
+ RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
}
func (TenantAPIKey) TableName() string {
return "tenant_api_keys"
}
+// APIKeyCapability is a bounded grant on a tenant API key. See
+// TenantAPIKey.Capabilities.
+type APIKeyCapability string
+
+const (
+ // APIKeyCapabilityRetrieve lets a key read and search knowledge-base data
+ // within its allowed KB scope without granting chat or content writes.
+ APIKeyCapabilityRetrieve APIKeyCapability = "retrieve"
+ // APIKeyCapabilityChat lets a scoped key run the conversation flow
+ // (sessions + agent listing + self identity) without granting broader
+ // tenant management access.
+ APIKeyCapabilityChat APIKeyCapability = "chat"
+ // APIKeyCapabilityReadAgents lets a scoped key list and inspect agents
+ // without allowing chat sessions or agent authoring.
+ APIKeyCapabilityReadAgents APIKeyCapability = "read_agents"
+ // APIKeyCapabilityIngest lets a key write content into its allowed
+ // knowledge bases (upload documents, edit chunks/FAQ/tags/wiki). It only
+ // lifts the content-write routes: it never allows creating new knowledge
+ // 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 APIKeyCapability = "manage_kbs"
+ // APIKeyCapabilityManageAgents lets a key create/read/update/delete/copy
+ // agents. Agent config can carry sensitive model/MCP bindings, so this is
+ // opt-in and off by default.
+ APIKeyCapabilityManageAgents APIKeyCapability = "manage_agents"
+ // APIKeyCapabilityMessageHistory lets a key search and inspect the
+ // tenant-level chat-history knowledge base without granting full Owner
+ // access. It is separate from chat: chat only covers the caller's own
+ // live conversation flow, while message_history can expose historical
+ // messages across the tenant.
+ APIKeyCapabilityMessageHistory APIKeyCapability = "message_history"
+ // APIKeyCapabilityManageModels lets a key manage tenant model
+ // definitions, credentials, model checks, and WeKnoraCloud credentials.
+ APIKeyCapabilityManageModels APIKeyCapability = "manage_models"
+ // APIKeyCapabilityManageMCPServices lets a key manage tenant MCP service
+ // definitions, credentials, tool policies, and per-principal OAuth state.
+ APIKeyCapabilityManageMCPServices APIKeyCapability = "manage_mcp_services"
+ // APIKeyCapabilityManageDataSources lets a key manage data-source
+ // connectors and sync jobs. KB scoping applies to data sources bound to a
+ // knowledge base.
+ APIKeyCapabilityManageDataSources APIKeyCapability = "manage_datasources"
+ // APIKeyCapabilityManageChannels lets a key manage embed and IM channel
+ // integrations for agents.
+ APIKeyCapabilityManageChannels APIKeyCapability = "manage_channels"
+ // APIKeyCapabilityManageVectorStores lets a key manage retrieval
+ // infrastructure such as vector stores, parser engines, and storage checks.
+ APIKeyCapabilityManageVectorStores APIKeyCapability = "manage_vector_stores"
+ // APIKeyCapabilityManageWebSearch lets a key manage tenant web-search
+ // provider configurations and credentials.
+ APIKeyCapabilityManageWebSearch APIKeyCapability = "manage_web_search"
+ // APIKeyCapabilityRunEvaluations lets a key run and inspect evaluation
+ // jobs without full tenant ownership.
+ APIKeyCapabilityRunEvaluations APIKeyCapability = "run_evaluations"
+ // 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
+ // key management, member management, tenant deletion, or ownership transfer.
+ APIKeyCapabilityManageTenantSettings APIKeyCapability = "manage_tenant_settings"
+)
+
+// NormalizeAPIKeyCapability maps an input capability string to a known
+// capability, returning "" for anything unrecognised so callers can drop it.
+func NormalizeAPIKeyCapability(c APIKeyCapability) APIKeyCapability {
+ switch APIKeyCapability(strings.ToLower(strings.TrimSpace(string(c)))) {
+ case APIKeyCapabilityRetrieve:
+ return APIKeyCapabilityRetrieve
+ case APIKeyCapabilityChat:
+ return APIKeyCapabilityChat
+ case APIKeyCapabilityReadAgents:
+ return APIKeyCapabilityReadAgents
+ case APIKeyCapabilityIngest:
+ return APIKeyCapabilityIngest
+ case APIKeyCapabilityManageKnowledgeBases:
+ return APIKeyCapabilityManageKnowledgeBases
+ case APIKeyCapabilityManageAgents:
+ return APIKeyCapabilityManageAgents
+ case APIKeyCapabilityMessageHistory:
+ return APIKeyCapabilityMessageHistory
+ case APIKeyCapabilityManageModels:
+ return APIKeyCapabilityManageModels
+ case APIKeyCapabilityManageMCPServices:
+ return APIKeyCapabilityManageMCPServices
+ case APIKeyCapabilityManageDataSources:
+ return APIKeyCapabilityManageDataSources
+ case APIKeyCapabilityManageChannels:
+ return APIKeyCapabilityManageChannels
+ case APIKeyCapabilityManageVectorStores:
+ return APIKeyCapabilityManageVectorStores
+ case APIKeyCapabilityManageWebSearch:
+ return APIKeyCapabilityManageWebSearch
+ case APIKeyCapabilityRunEvaluations:
+ return APIKeyCapabilityRunEvaluations
+ case APIKeyCapabilityManageTenantSettings:
+ return APIKeyCapabilityManageTenantSettings
+ default:
+ return ""
+ }
+}
+
+// NormalizeAPIKeyCapabilities dedups and drops unknown capabilities.
+func NormalizeAPIKeyCapabilities(in StringArray) StringArray {
+ out := make(StringArray, 0, len(in))
+ seen := map[string]struct{}{}
+ for _, item := range in {
+ norm := NormalizeAPIKeyCapability(APIKeyCapability(item))
+ if norm == "" {
+ continue
+ }
+ s := string(norm)
+ if _, ok := seen[s]; ok {
+ continue
+ }
+ seen[s] = struct{}{}
+ out = append(out, s)
+ }
+ return out
+}
+
func (k *TenantAPIKey) BeforeSave(tx *gorm.DB) error {
if key := utils.GetAESKey(); key != nil && k.APIKey != "" {
encrypted, err := utils.EncryptAESGCM(k.APIKey, key)
@@ -59,8 +188,9 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
// TenantAPIKeyScope is the request-context projection used by middleware.
type TenantAPIKeyScope struct {
KeyID uint64
- Role TenantRole
+ FullAccess bool
KnowledgeBaseIDs StringArray
+ Capabilities StringArray
}
func WithTenantAPIKeyScope(ctx context.Context, scope TenantAPIKeyScope) context.Context {
@@ -81,29 +211,24 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
return TenantAPIKeyScope{
KeyID: s.KeyID,
- Role: NormalizeTenantAPIKeyRole(s.Role),
+ FullAccess: s.FullAccess,
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
+ Capabilities: NormalizeAPIKeyCapabilities(s.Capabilities),
}
}
-// NormalizeTenantAPIKeyRole maps stored/API role strings to tenant RBAC roles.
-func NormalizeTenantAPIKeyRole(role TenantRole) TenantRole {
- switch strings.ToLower(strings.TrimSpace(string(role))) {
- case string(TenantRoleOwner):
- return TenantRoleOwner
- case string(TenantRoleAdmin):
- return TenantRoleAdmin
- case string(TenantRoleContributor):
- return TenantRoleContributor
- case string(TenantRoleViewer), "":
- return TenantRoleViewer
- default:
- return ""
+// HasCapability reports whether the scope carries the given additive grant.
+func (s TenantAPIKeyScope) HasCapability(c APIKeyCapability) bool {
+ c = NormalizeAPIKeyCapability(c)
+ if c == "" {
+ return false
}
-}
-
-func (s TenantAPIKeyScope) TenantRole() TenantRole {
- return s.Normalize().Role
+ for _, item := range NormalizeAPIKeyCapabilities(s.Capabilities) {
+ if item == string(c) {
+ return true
+ }
+ }
+ return false
}
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
@@ -167,7 +292,7 @@ func AuthorizeTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) e
if !ok || !scope.IsKnowledgeBaseRestricted() {
return nil
}
- if !scope.AllowsKnowledgeBases(kbIDs) {
+ if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
}
return nil
@@ -184,7 +309,7 @@ func AuthorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs, knowledge
if len(knowledgeIDs) > 0 {
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
}
- if !scope.AllowsKnowledgeBases(kbIDs) {
+ if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
}
return nil
diff --git a/internal/types/tenant_api_key_scope_test.go b/internal/types/tenant_api_key_scope_test.go
index a683de9db..849e5be4f 100644
--- a/internal/types/tenant_api_key_scope_test.go
+++ b/internal/types/tenant_api_key_scope_test.go
@@ -15,6 +15,16 @@ func TestAuthorizeTenantAPIKeyKnowledgeTargetsRejectsKnowledgeIDs(t *testing.T)
}
}
+func TestAuthorizeTenantAPIKeyKnowledgeTargetsAllowsUnspecifiedTargets(t *testing.T) {
+ ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
+ KnowledgeBaseIDs: StringArray{"kb-1"},
+ })
+ err := AuthorizeTenantAPIKeyKnowledgeTargets(ctx, nil, nil)
+ if err != nil {
+ t.Fatalf("expected unspecified targets to be allowed, got %v", err)
+ }
+}
+
func TestAuthorizeTenantAPIKeyOptionalTagIDsRejectsTags(t *testing.T) {
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
KnowledgeBaseIDs: StringArray{"kb-1"},
@@ -47,3 +57,39 @@ func TestFilterKnowledgeBasesForTenantAPIKeyScopeRejectsExplicitOutOfScope(t *te
t.Fatal("expected forbidden for explicit out-of-scope kb_ids")
}
}
+
+func TestScopeHasCapability(t *testing.T) {
+ s := TenantAPIKeyScope{Capabilities: StringArray{"chat"}}
+ if !s.HasCapability(APIKeyCapabilityChat) {
+ t.Fatal("expected chat capability to be present")
+ }
+ if (TenantAPIKeyScope{}).HasCapability(APIKeyCapabilityChat) {
+ t.Fatal("empty scope must not report chat capability")
+ }
+ // Unknown capability is never satisfied.
+ if s.HasCapability(APIKeyCapability("bogus")) {
+ t.Fatal("unknown capability must not be satisfied")
+ }
+}
+
+func TestNormalizeAPIKeyCapabilities(t *testing.T) {
+ got := NormalizeAPIKeyCapabilities(StringArray{
+ " Retrieve ",
+ "chat",
+ "read_agents",
+ "manage_kbs",
+ "message_history",
+ "manage_mcp_services",
+ "bogus",
+ "",
+ })
+ want := []string{"retrieve", "chat", "read_agents", "manage_kbs", "message_history", "manage_mcp_services"}
+ if len(got) != len(want) {
+ t.Fatalf("normalized = %#v, want %#v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("normalized = %#v, want %#v", got, want)
+ }
+ }
+}
diff --git a/internal/types/tenant_api_key_test.go b/internal/types/tenant_api_key_test.go
index 48cb5e191..63c98096e 100644
--- a/internal/types/tenant_api_key_test.go
+++ b/internal/types/tenant_api_key_test.go
@@ -2,39 +2,31 @@ package types
import "testing"
-func TestTenantAPIKeyScopeNormalizeDefaultsEmptyRoleToViewer(t *testing.T) {
- scope := TenantAPIKeyScope{Role: ""}.Normalize()
- if scope.Role != TenantRoleViewer {
- t.Fatalf("normalized role = %q, want viewer", scope.Role)
+func TestTenantAPIKeyScopeNormalizePreservesFullAccess(t *testing.T) {
+ scope := TenantAPIKeyScope{FullAccess: true}.Normalize()
+ if !scope.FullAccess {
+ t.Fatal("normalized scope lost full access")
}
}
-func TestNormalizeTenantAPIKeyRole(t *testing.T) {
- tests := []struct {
- name string
- in TenantRole
- want TenantRole
- }{
- {name: "viewer", in: TenantRoleViewer, want: TenantRoleViewer},
- {name: "contributor", in: TenantRoleContributor, want: TenantRoleContributor},
- {name: "admin", in: TenantRoleAdmin, want: TenantRoleAdmin},
- {name: "owner", in: TenantRoleOwner, want: TenantRoleOwner},
- {name: "empty defaults viewer", in: "", want: TenantRoleViewer},
- {name: "invalid", in: "superuser", want: ""},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := NormalizeTenantAPIKeyRole(tt.in)
- if got != tt.want {
- t.Fatalf("NormalizeTenantAPIKeyRole(%q) = %q, want %q", tt.in, got, tt.want)
- }
- })
+func TestTenantAPIKeyScopeNormalizeDefaultsToScopedAccess(t *testing.T) {
+ scope := TenantAPIKeyScope{}.Normalize()
+ if scope.FullAccess {
+ t.Fatal("empty scope must not become full access")
}
}
-func TestTenantAPIKeyScopeTenantRole(t *testing.T) {
- got := TenantAPIKeyScope{Role: TenantRoleContributor}.TenantRole()
- if got != TenantRoleContributor {
- t.Fatalf("TenantRole() = %q, want contributor", got)
+func TestTenantAPIKeyScopeNormalizeDropsInvalidCapabilities(t *testing.T) {
+ scope := TenantAPIKeyScope{
+ Capabilities: StringArray{"chat", "bogus", "retrieve", "chat"},
+ }.Normalize()
+ want := StringArray{"chat", "retrieve"}
+ if len(scope.Capabilities) != len(want) {
+ t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
+ }
+ for i := range want {
+ if scope.Capabilities[i] != want[i] {
+ t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
+ }
}
}
diff --git a/internal/types/tenant_member.go b/internal/types/tenant_member.go
index 7562c77b7..8022b0a1f 100644
--- a/internal/types/tenant_member.go
+++ b/internal/types/tenant_member.go
@@ -17,7 +17,7 @@ type TenantRole string
const (
// TenantRoleOwner has full control over the tenant, including tenant
- // deletion, ownership transfer, and rotating the tenant API key.
+ // deletion, ownership transfer, and managing tenant API keys.
TenantRoleOwner TenantRole = "owner"
// TenantRoleAdmin manages users, integrations, and tenant-scoped
// configuration such as model providers, vector stores, MCP services
diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql
index 08941aab1..11dd6c080 100644
--- a/migrations/sqlite/000000_init.up.sql
+++ b/migrations/sqlite/000000_init.up.sql
@@ -756,7 +756,7 @@ CREATE TABLE IF NOT EXISTS tenant_api_keys (
name TEXT NOT NULL,
key_hash TEXT NOT NULL UNIQUE,
api_key TEXT NOT NULL DEFAULT '',
- role TEXT NOT NULL DEFAULT 'viewer',
+ full_access BOOLEAN NOT NULL DEFAULT 0,
knowledge_base_ids TEXT NOT NULL DEFAULT '[]',
last_used_at DATETIME,
expires_at DATETIME,
diff --git a/migrations/versioned/000065_tenant_api_keys.up.sql b/migrations/versioned/000065_tenant_api_keys.up.sql
index 33daf9f64..3d29c993b 100644
--- a/migrations/versioned/000065_tenant_api_keys.up.sql
+++ b/migrations/versioned/000065_tenant_api_keys.up.sql
@@ -6,7 +6,7 @@ CREATE TABLE IF NOT EXISTS tenant_api_keys (
name VARCHAR(128) NOT NULL,
key_hash VARCHAR(64) NOT NULL UNIQUE,
api_key TEXT NOT NULL DEFAULT '',
- role VARCHAR(32) NOT NULL DEFAULT 'viewer',
+ full_access BOOLEAN NOT NULL DEFAULT FALSE,
knowledge_base_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
last_used_at TIMESTAMP,
expires_at TIMESTAMP,
@@ -25,7 +25,7 @@ INSERT INTO tenant_api_keys (
name,
key_hash,
api_key,
- role,
+ full_access,
knowledge_base_ids,
created_at,
updated_at
@@ -35,7 +35,7 @@ SELECT
'Tenant API key',
'migrated-tenant-' || id::text,
api_key,
- 'owner',
+ TRUE,
'[]'::jsonb,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
diff --git a/migrations/versioned/000066_tenant_api_key_capabilities.down.sql b/migrations/versioned/000066_tenant_api_key_capabilities.down.sql
new file mode 100644
index 000000000..22eb22f29
--- /dev/null
+++ b/migrations/versioned/000066_tenant_api_key_capabilities.down.sql
@@ -0,0 +1 @@
+ALTER TABLE tenant_api_keys DROP COLUMN IF EXISTS capabilities;
diff --git a/migrations/versioned/000066_tenant_api_key_capabilities.up.sql b/migrations/versioned/000066_tenant_api_key_capabilities.up.sql
new file mode 100644
index 000000000..160929cf9
--- /dev/null
+++ b/migrations/versioned/000066_tenant_api_key_capabilities.up.sql
@@ -0,0 +1,9 @@
+DO $$ BEGIN RAISE NOTICE '[Migration 000066] Adding tenant_api_keys.capabilities...'; END $$;
+
+-- Additive per-key grants for non-full-access keys. Capabilities let a scoped
+-- key call a bounded route family, while knowledge_base_ids still constrains
+-- the KBs the key can touch where a route targets knowledge-base data.
+ALTER TABLE tenant_api_keys
+ ADD COLUMN IF NOT EXISTS capabilities JSONB NOT NULL DEFAULT '[]'::jsonb;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000066] tenant_api_keys.capabilities ready'; END $$;