refactor(api-keys): simplify authorization to a single-role gate

Redesign tenant API key authorization around one dimension (role) plus a
central default-deny gate, replacing the previous role + KB-scoped flag model.

- Add APIKeyGate as the single authority for API-key authorization: routes
  declare one policy (MinRole) via apiKeyGroup/apiKeyRoute helpers; undeclared
  routes are denied by default. JWT principals short-circuit the gate and the
  JWT-centric RBAC guards short-circuit for API-key principals.
- Roles: viewer/contributor/admin are knowledge-base data-plane only (KB scope
  is a pure downstream data filter); owner is a full-access tenant tier that
  unlocks tenant-level infrastructure routes and is required for every method.
- Drop the KBScoped policy flag and the KB-restricted-vs-tenant branching.
- Security hardening: never disclose HMAC secret (return presence only), abort
  writes on API-key encryption failure, deny KB-restricted keys on /files, and
  backfill legacy key hashes at startup instead of O(N) plaintext scans.
- Frontend: two-level create dialog (access type -> permission level), rename
  role labels to reflect actual scope, sync en/zh/ko/ru locales.
- Fix startup self-check false-positive on trailing-slash routes and normalize
  gin paths before comparison; add regression tests.
This commit is contained in:
wizardchen
2026-07-06 17:34:52 +08:00
committed by lyingbug
parent fedb6c3f7e
commit d2ffc1b973
26 changed files with 1045 additions and 500 deletions
+2 -2
View File
@@ -23,8 +23,8 @@ export interface APIPrincipalConfig {
direct_header_name: string
signed_token_header_name: string
require_direct_header: boolean
// The server never returns the plaintext secret; only its presence.
has_hmac_secret: boolean
hmac_secret?: string
}
export interface UpdateAPIPrincipalConfigPayload {
@@ -48,7 +48,7 @@ export interface APIPrincipalTestToken {
external_user_id: string
}
export type TenantAPIKeyRole = 'viewer' | 'contributor' | 'admin'
export type TenantAPIKeyRole = 'viewer' | 'contributor' | 'admin' | 'owner'
export interface TenantAPIKey {
id: number
+13 -5
View File
@@ -5768,15 +5768,23 @@ export default {
apiKeyNameRequired: 'Enter an API key name',
toggleApiKeyVisible: 'Show or hide API key',
apiKeyAccessRole: "Access role",
apiKeyAccessRoleHint: "Matches tenant member roles; requests are authorized by the selected role.",
accessRoleViewer: "Viewer",
accessRoleContributor: "Contributor",
accessRoleAdmin: "Admin",
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.",
accessTypeKnowledgeBase: "Knowledge base",
accessTypeTenantFull: "Tenant full",
apiKeyPermissionLevel: "Permission level",
apiKeyAccessRoleHint: "The first three roles are limited to knowledge-base operations; \"Tenant Full\" also unlocks tenant-level APIs such as models and data sources.",
accessRoleViewer: "KB Read",
accessRoleContributor: "KB Write",
accessRoleAdmin: "KB Admin",
accessRoleOwner: "Tenant Full",
accessRoleViewerDesc: "Query, search, and chat without modifying knowledge-base content.",
accessRoleContributorDesc: "Create, update, or delete knowledge-base content within the selected scope.",
accessRoleAdminDesc: "Manage tenant-level settings and integrations; cannot create, rotate, or delete API keys.",
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',
apiKeyKnowledgeScopePlaceholder: 'Leave empty to allow all knowledge bases',
apiKeyKnowledgeScopeOwnerHint: 'Owner is a full-access key; the knowledge-base scope does not apply to it.',
allKnowledgeBases: 'All knowledge bases',
createdAt: 'Created',
actions: 'Actions',
+13 -5
View File
@@ -5779,15 +5779,23 @@ export default {
apiKeyNameRequired: "API Key 이름을 입력하세요",
toggleApiKeyVisible: "API Key 표시 또는 숨기기",
apiKeyAccessRole: "접근 역할",
apiKeyAccessRoleHint: "워크스페이스 멤버 역할과 동일하며, 요청 시 선택한 역할로 인증됩니다.",
accessRoleViewer: "뷰어",
accessRoleContributor: "편집",
accessRoleAdmin: "관리자",
apiKeyAccessType: "접근 유형",
apiKeyAccessTypeHint: "\"지식베이스\"는 아래 권한 수준에 따라 지식베이스 범위 내에서 작동합니다. \"테넌트 전체 접근\"은 모델, 데이터 소스 등 모든 테넌트 수준 API를 추가로 사용할 수 있습니다.",
accessTypeKnowledgeBase: "지식베이스",
accessTypeTenantFull: "테넌트 전체 접근",
apiKeyPermissionLevel: "권한 수준",
apiKeyAccessRoleHint: "앞의 세 역할은 지식베이스 범위 내 작업으로 제한되며, \"테넌트 전체 접근\"은 모델, 데이터 소스 등 테넌트 수준 API도 추가로 사용할 수 있습니다.",
accessRoleViewer: "지식베이스 읽기",
accessRoleContributor: "지식베이스 읽기·쓰기",
accessRoleAdmin: "지식베이스 관리자",
accessRoleOwner: "테넌트 전체 접근",
accessRoleViewerDesc: "조회, 검색 및 대화만 가능하며 지식베이스 내용은 수정하지 않습니다.",
accessRoleContributorDesc: "선택한 범위 내에서 지식베이스 콘텐츠를 생성, 수정 또는 삭제합니다.",
accessRoleAdminDesc: "테넌트 수준 설정 및 통합을 관리합니다. API Key 생성, 교체 또는 삭제는 불가합니다.",
accessRoleAdminDesc: "선택한 범위 내에서 지식베이스를 관리하며, 지식베이스 비우기 등 파괴적 작업을 포함합니다. 테넌트 수준 설정은 다루지 않습니다.",
accessRoleOwnerDesc: "전체 접근, 테넌트 소유자와 동일: 모델, 벡터 스토어, 데이터 소스, 채널 등 모든 테넌트 수준 API를 호출할 수 있으며 지식베이스 범위의 제한을 받지 않습니다.",
apiKeyKnowledgeScope: "지식베이스 범위",
apiKeyKnowledgeScopePlaceholder: "비워 두면 모든 지식베이스 접근 허용",
apiKeyKnowledgeScopeOwnerHint: "소유자는 전체 접근 키이므로 지식베이스 범위가 적용되지 않습니다.",
allKnowledgeBases: "모든 지식베이스",
createdAt: "생성일",
actions: "작업",
+13 -5
View File
@@ -5600,15 +5600,23 @@ export default {
apiKeyNameRequired: 'Введите название API key',
toggleApiKeyVisible: 'Показать или скрыть API key',
apiKeyAccessRole: 'Роль доступа',
apiKeyAccessRoleHint: 'Соответствует роли участника workspace; запросы авторизуются по выбранной роли.',
accessRoleViewer: 'Наблюдатель',
accessRoleContributor: 'Редактор',
accessRoleAdmin: 'Администратор',
apiKeyAccessType: 'Тип доступа',
apiKeyAccessTypeHint: '«База знаний» работает в пределах области БЗ на выбранном ниже уровне прав; «Полный доступ арендатора» дополнительно открывает все API уровня арендатора, такие как модели и источники данных.',
accessTypeKnowledgeBase: 'База знаний',
accessTypeTenantFull: 'Полный доступ арендатора',
apiKeyPermissionLevel: 'Уровень прав',
apiKeyAccessRoleHint: 'Первые три роли ограничены операциями с базами знаний; «Полный доступ арендатора» дополнительно открывает API уровня арендатора, такие как модели и источники данных.',
accessRoleViewer: 'Чтение БЗ',
accessRoleContributor: 'Чтение и запись БЗ',
accessRoleAdmin: 'Администратор БЗ',
accessRoleOwner: 'Полный доступ арендатора',
accessRoleViewerDesc: 'Запросы, поиск и диалог без изменения содержимого баз знаний.',
accessRoleContributorDesc: 'Создание, обновление или удаление записей в выбранном диапазоне баз знаний.',
accessRoleAdminDesc: 'Управление настройками арендатора и интеграциями; нельзя создавать, ротировать или удалять API keys.',
accessRoleAdminDesc: 'Управление базами знаний в выбранном диапазоне, включая деструктивные операции, такие как очистка базы знаний; настройки уровня арендатора недоступны.',
accessRoleOwnerDesc: 'Полный доступ, эквивалент владельца арендатора: доступны все API уровня арендатора (модели, векторные хранилища, источники данных, каналы, ...). Не ограничивается диапазоном баз знаний.',
apiKeyKnowledgeScope: 'Базы знаний',
apiKeyKnowledgeScopePlaceholder: 'Оставьте пустым, чтобы разрешить доступ ко всем базам знаний',
apiKeyKnowledgeScopeOwnerHint: 'Владелец — это ключ с полным доступом; диапазон баз знаний к нему не применяется.',
allKnowledgeBases: 'Все базы знаний',
createdAt: 'Создано',
actions: 'Действия',
+13 -5
View File
@@ -5781,15 +5781,23 @@ export default {
apiKeyNameRequired: "请输入 API Key 名称",
toggleApiKeyVisible: "显示或隐藏 API Key",
apiKeyAccessRole: "访问角色",
apiKeyAccessRoleHint: "与空间成员角色一致,请求时按所选角色鉴权。",
accessRoleViewer: "访客",
accessRoleContributor: "编辑",
accessRoleAdmin: "管理员",
apiKeyAccessType: "访问类型",
apiKeyAccessTypeHint: "「知识库」按下方权限级别在知识库范围内操作;「租户完全访问」额外开放模型、数据源等全部租户级接口。",
accessTypeKnowledgeBase: "知识库",
accessTypeTenantFull: "租户完全访问",
apiKeyPermissionLevel: "权限级别",
apiKeyAccessRoleHint: "前三档仅限知识库范围内操作;「租户完全访问」额外开放模型、数据源等租户级接口。",
accessRoleViewer: "知识库只读",
accessRoleContributor: "知识库读写",
accessRoleAdmin: "知识库管理员",
accessRoleOwner: "租户完全访问",
accessRoleViewerDesc: "查询、检索和对话,不修改知识库内容。",
accessRoleContributorDesc: "创建、更新或删除知识库内容,受知识库范围限制。",
accessRoleAdminDesc: "管理租户级配置与集成设置;不能创建、轮换或删除 API 密钥。",
accessRoleAdminDesc: "知识库管理,包含清空知识库等破坏性操作,受知识库范围限制;不涉及租户级配置。",
accessRoleOwnerDesc: "完全访问,等同租户所有者:可调用模型、向量库、数据源、渠道等全部租户级接口,不受知识库范围限制。",
apiKeyKnowledgeScope: "知识库范围",
apiKeyKnowledgeScopePlaceholder: "留空表示允许访问全部知识库",
apiKeyKnowledgeScopeOwnerHint: "所有者为完全访问密钥,知识库范围对其不生效。",
allKnowledgeBases: "全部知识库",
createdAt: "创建时间",
actions: "操作",
@@ -460,21 +460,34 @@
<div class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
<label>{{ $t('integrations.api.apiKeyAccessRole') }}</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>
<p class="scope-role-hint">{{ $t('integrations.api.apiKeyAccessTypeHint') }}</p>
</div>
<div v-if="!apiKeyRoleIsOwner" class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
<label>{{ $t('integrations.api.apiKeyPermissionLevel') }}</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>
<p class="scope-role-hint">{{ $t('integrations.api.apiKeyAccessRoleHint') }}</p>
</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>
</div>
<div class="api-key-dialog-row">
<div v-if="!apiKeyRoleIsOwner" class="api-key-dialog-row">
<div class="api-key-dialog-row__label">
<label>{{ $t('integrations.api.apiKeyKnowledgeScope') }}</label>
</div>
@@ -545,7 +558,6 @@ const apiKeyCreating = ref(false)
const knowledgeBasesLoading = ref(false)
const knowledgeBases = ref<Array<{ id: string; name: string }>>([])
const secretInput = ref('')
const savedHMACSecret = ref('')
const exampleTab = ref<'jwt' | 'curl'>('curl')
const agents = ref<CustomAgent[]>([])
const agentsLoading = ref(false)
@@ -568,7 +580,7 @@ const form = reactive({
require_direct_header: false,
})
type ApiKeyAccessRole = 'viewer' | 'contributor' | 'admin'
type ApiKeyAccessRole = 'viewer' | 'contributor' | 'admin' | 'owner'
const apiKeyForm = reactive({
name: '',
@@ -576,18 +588,50 @@ const apiKeyForm = reactive({
knowledge_base_ids: [] as string[],
})
// 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'
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'),
}
return labels[normalized] ?? labels.viewer
}
const apiKeyFormRoleDesc = computed(() => {
switch (apiKeyForm.role) {
case 'owner':
return t('integrations.api.accessRoleOwnerDesc')
case 'admin':
return t('integrations.api.accessRoleAdminDesc')
case 'contributor':
@@ -665,7 +709,10 @@ const directHeaderName = computed(() => DEFAULT_DIRECT_HEADER_NAME)
const canAutoSave = computed(() => {
if (!tenantId.value) return false
if (form.mode === 'signed_token') {
return secretInput.value.trim() !== ''
// Either a secret is already stored server-side, or the user has just
// typed a new one. The plaintext secret is never returned by the API,
// so we rely on the has_hmac_secret presence flag.
return config.value?.has_hmac_secret === true || secretInput.value.trim() !== ''
}
return true
})
@@ -686,7 +733,9 @@ const hasUnsavedPrincipalChanges = computed(() => {
return (
form.mode !== cfg.mode
|| form.require_direct_header !== cfg.require_direct_header
|| secretInput.value.trim() !== savedHMACSecret.value.trim()
// A non-empty input always means the user intends to set a new secret;
// the existing secret is never echoed back so any typed value is a change.
|| secretInput.value.trim() !== ''
)
})
@@ -831,8 +880,9 @@ async function load() {
form.direct_header_name = DEFAULT_DIRECT_HEADER_NAME
form.signed_token_header_name = DEFAULT_TOKEN_HEADER_NAME
form.require_direct_header = cfgResp.data.require_direct_header === true
savedHMACSecret.value = cfgResp.data.hmac_secret || ''
secretInput.value = savedHMACSecret.value
// The plaintext secret is never returned; start with an empty input and
// rely on config.has_hmac_secret to reflect whether one is configured.
secretInput.value = ''
ensurePlaygroundAgent()
} catch (err: any) {
error.value = err?.message || t('integrations.api.loadFailed')
@@ -956,7 +1006,9 @@ async function saveIfNeeded(options: { showSuccess?: boolean } = {}) {
signed_token_header_name: DEFAULT_TOKEN_HEADER_NAME,
require_direct_header: form.require_direct_header,
}
if (secretInput.value.trim() !== savedHMACSecret.value.trim()) {
// Only send the secret when the user typed a new one; otherwise the
// backend keeps the stored value untouched.
if (secretInput.value.trim() !== '') {
payload.hmac_secret = secretInput.value.trim()
}
const resp = await updateAPIPrincipalConfig(tenantId.value, payload)
@@ -964,8 +1016,7 @@ async function saveIfNeeded(options: { showSuccess?: boolean } = {}) {
throw new Error(resp.message || t('integrations.api.saveFailed'))
}
config.value = resp.data
savedHMACSecret.value = resp.data.hmac_secret || payload.hmac_secret || ''
secretInput.value = savedHMACSecret.value
secretInput.value = ''
if (options.showSuccess) {
MessagePlugin.success(t('integrations.api.saveSuccess'))
}
@@ -1121,6 +1172,8 @@ function openCreateAPIKeyDialog() {
apiKeyForm.name = ''
apiKeyForm.role = 'viewer'
apiKeyForm.knowledge_base_ids = []
apiKeyAccessType.value = 'kb'
lastKbRole = 'viewer'
apiKeyDialogVisible.value = true
void loadKnowledgeBaseOptions()
}
@@ -1135,7 +1188,8 @@ async function createScopedAPIKey() {
const resp = await createTenantAPIKey(tenantId.value, {
name: apiKeyForm.name.trim(),
role: apiKeyForm.role,
knowledge_base_ids: apiKeyForm.knowledge_base_ids,
// Owner keys are full-access; KB scoping does not apply to them.
knowledge_base_ids: apiKeyRoleIsOwner.value ? [] : apiKeyForm.knowledge_base_ids,
})
if (!resp.success || !resp.data?.api_key) {
throw new Error(resp.message || t('integrations.api.createApiKeyFailed'))