Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: support updating API key configuration
Easton Gud4a16cc8f361
diff --git a/client/tenant.go b/client/tenant.goindex 5afd8f9e8..7c0c31ac3 100644--- a/client/tenant.go+++ b/client/tenant.go@@ -80,24 +80,38 @@ const (type TenantAPIKey struct {ID uint64 `json:"id"`TenantID uint64 `json:"tenant_id"`+ ScopeType string `json:"scope_type"`Name string `json:"name"`APIKey string `json:"api_key"`Role TenantAPIKeyRole `json:"role"`+ FullAccess bool `json:"full_access"`KnowledgeBaseIDs []string `json:"knowledge_base_ids"`- LastUsedAt *time.Time `json:"last_used_at,omitempty"`- ExpiresAt *time.Time `json:"expires_at,omitempty"`- CreatedAt time.Time `json:"created_at"`- UpdatedAt time.Time `json:"updated_at"`+ Capabilities []string `json:"capabilities"`+ LastUsedAt *time.Time `json:"last_used_at,omitempty"`+ ExpiresAt *time.Time `json:"expires_at,omitempty"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`}// CreateTenantAPIKeyRequest creates a revocable tenant API key.type CreateTenantAPIKeyRequest struct {Name string `json:"name"`Role TenantAPIKeyRole `json:"role,omitempty"`+ FullAccess bool `json:"full_access,omitempty"`KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`+ Capabilities []string `json:"capabilities,omitempty"`ExpiresAtUnix *int64 `json:"expires_at_unix,omitempty"`}+// UpdateTenantAPIKeyRequest replaces an existing tenant API key's configurable attributes.+type UpdateTenantAPIKeyRequest struct {+ Name string `json:"name"`+ FullAccess bool `json:"full_access"`+ KnowledgeBaseIDs []string `json:"knowledge_base_ids"`+ Capabilities []string `json:"capabilities"`+ ExpiresAtUnix *int64 `json:"expires_at_unix"`+}+// CreatedTenantAPIKey includes the created API key. Token is kept for// backward-compatible clients; APIKey is also returned by list APIs.type CreatedTenantAPIKey struct {@@ -276,6 +290,25 @@ func (c *Client) CreateTenantAPIKey(return &response.Data, nil}+// UpdateTenantAPIKey replaces an existing tenant API key's configuration.+func (c *Client) UpdateTenantAPIKey(+ ctx context.Context, tenantID uint64, keyID uint64, req *UpdateTenantAPIKeyRequest,+) (*TenantAPIKey, error) {+ path := fmt.Sprintf("/api/v1/tenants/%d/api-keys/%d", tenantID, keyID)+ resp, err := c.doRequest(ctx, http.MethodPut, path, req, nil)+ if err != nil {+ return nil, err+ }+ var response struct {+ Success bool `json:"success"`+ Data TenantAPIKey `json:"data"`+ }+ if err := parseResponse(resp, &response); err != nil {+ return nil, err+ }+ return &response.Data, nil+}+// DeleteTenantAPIKey revokes a tenant API key.func (c *Client) DeleteTenantAPIKey(ctx context.Context, tenantID uint64, keyID uint64) error {path := fmt.Sprintf("/api/v1/tenants/%d/api-keys/%d", tenantID, keyID)diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.tsindex f638b6623..ae5baf1ee 100644--- a/frontend/src/api/tenant/index.ts+++ b/frontend/src/api/tenant/index.ts@@ -99,7 +99,7 @@ export interface TenantAPIKey {name: stringapi_key: stringfull_access: boolean- knowledge_base_ids: string[]+ knowledge_base_ids: string[] | nullcapabilities?: TenantAPIKeyCapability[]last_used_at?: stringexpires_at?: string@@ -118,6 +118,14 @@ export interface CreateTenantAPIKeyPayload {expires_at_unix?: number}+export interface UpdateTenantAPIKeyPayload {+ name: string+ full_access: boolean+ knowledge_base_ids: string[]+ capabilities: TenantAPIKeyCapability[]+ expires_at_unix?: number+}+// 搜索空间参数export interface SearchTenantsParams {keyword?: string@@ -227,6 +235,23 @@ export async function createTenantAPIKey(}}+/** 更新已创建租户 API Key 的授权范围和其他可配置属性。 */+export async function updateTenantAPIKey(+ tenantId: number,+ keyId: number,+ payload: UpdateTenantAPIKeyPayload,+): Promise<{ success: boolean; data?: TenantAPIKey; message?: string }> {+ try {+ const response = await put(`/api/v1/tenants/${tenantId}/api-keys/${keyId}`, payload)+ return response as unknown as { success: boolean; data?: TenantAPIKey; message?: string }+ } catch (error: any) {+ return {+ success: false,+ message: error.message || t('integrations.api.updateApiKeyScopeFailed'),+ }+ }+}+export async function deleteTenantAPIKey(tenantId: number,keyId: number,diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 36c035de5..8e981a89b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -5606,6 +5606,7 @@ export default {apiKeyValue: 'API Key',apiKeyNamePlaceholder: 'Example: MCP read-only access',apiKeyNameRequired: 'Enter an API key name',+ apiKeyCapabilitiesRequired: 'Select at least one capability for a scoped API key',apiKeyAccessMode: 'Access mode',apiKeyScopedAccess: 'Scoped access',apiKeyAccessType: 'Access type',@@ -5658,6 +5659,11 @@ export default {apiKeyKnowledgeScope: 'Knowledge bases',apiKeyKnowledgeScopePlaceholder: 'Leave empty to allow all knowledge bases',allKnowledgeBases: 'All knowledge bases',+ editApiKeyScope: 'Edit API key',+ editApiKeyScopeDesc: 'Change the name and authorization scope of API key "{name}".',+ editApiKeyScopeHint: 'Leave empty to allow all knowledge bases in this workspace. All changes take effect immediately.',+ updateApiKeyScopeSuccess: 'API key updated',+ updateApiKeyScopeFailed: 'Failed to update API key',createdAt: 'Created',actions: 'Actions',deleteApiKey: 'Delete',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex dfb334f8b..d60272edc 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -404,6 +404,7 @@ export default {apiKeyValue: 'API Key',apiKeyNamePlaceholder: '예: MCP 읽기 전용',apiKeyNameRequired: 'API Key 이름을 입력하세요',+ apiKeyCapabilitiesRequired: 'Scoped API Key에 하나 이상의 기능을 선택하세요',apiKeyAccessMode: '접근 방식',apiKeyScopedAccess: '범위 지정 접근',apiKeyAccessType: '접근 유형',@@ -456,6 +457,11 @@ export default {apiKeyKnowledgeScope: '지식베이스 범위',apiKeyKnowledgeScopePlaceholder: '비워 두면 모든 지식베이스 접근 허용',allKnowledgeBases: '모든 지식베이스',+ editApiKeyScope: 'API Key 편집',+ editApiKeyScopeDesc: 'API Key "{name}"의 이름과 권한 범위를 변경합니다.',+ editApiKeyScopeHint: '비워 두면 이 워크스페이스의 모든 지식베이스를 허용합니다. 모든 변경 사항은 즉시 적용됩니다.',+ updateApiKeyScopeSuccess: 'API Key가 업데이트되었습니다',+ updateApiKeyScopeFailed: 'API Key 업데이트 실패',createdAt: '생성일',actions: '작업',deleteApiKey: '삭제',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 08520e704..d8b6569da 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -404,6 +404,7 @@ export default {apiKeyValue: 'API Key',apiKeyNamePlaceholder: 'Например: MCP только чтение',apiKeyNameRequired: 'Введите название API key',+ apiKeyCapabilitiesRequired: 'Выберите хотя бы одну возможность для scoped API key',apiKeyAccessMode: 'Режим доступа',apiKeyScopedAccess: 'Ограниченный доступ',apiKeyAccessType: 'Тип доступа',@@ -456,6 +457,11 @@ export default {apiKeyKnowledgeScope: 'Базы знаний',apiKeyKnowledgeScopePlaceholder: 'Оставьте пустым, чтобы разрешить доступ ко всем базам знаний',allKnowledgeBases: 'Все базы знаний',+ editApiKeyScope: 'Изменить API key',+ editApiKeyScopeDesc: 'Изменить имя и область авторизации API key «{name}».',+ editApiKeyScopeHint: 'Оставьте пустым, чтобы разрешить все базы знаний рабочего пространства. Все изменения применяются сразу.',+ updateApiKeyScopeSuccess: 'API key обновлён',+ updateApiKeyScopeFailed: 'Не удалось обновить API key',createdAt: 'Создано',actions: 'Действия',deleteApiKey: 'Удалить',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 850c1cd61..5347e1c41 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -404,6 +404,7 @@ export default {apiKeyValue: 'API Key',apiKeyNamePlaceholder: '例如:MCP 只读访问',apiKeyNameRequired: '请输入 API Key 名称',+ apiKeyCapabilitiesRequired: 'Scoped API Key 至少需要选择一项能力',apiKeyAccessMode: '授权方式',apiKeyScopedAccess: '能力授权',apiKeyAccessType: '访问类型',@@ -456,6 +457,11 @@ export default {apiKeyKnowledgeScope: '知识库范围',apiKeyKnowledgeScopePlaceholder: '留空表示允许访问全部知识库',allKnowledgeBases: '全部知识库',+ editApiKeyScope: '编辑 API Key',+ editApiKeyScopeDesc: '修改 API Key「{name}」的名称和授权范围。',+ editApiKeyScopeHint: '留空表示允许访问本空间的全部知识库。所有修改保存后立即生效。',+ updateApiKeyScopeSuccess: 'API Key 已更新',+ updateApiKeyScopeFailed: '更新 API Key 失败',createdAt: '创建时间',actions: '操作',deleteApiKey: '删除',diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vueindex 7a1dc9292..73597d181 100644--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue@@ -157,6 +157,14 @@</td><td><div class="api-key-table__actions">+ <t-button+ shape="square"+ variant="text"+ :title="$t('integrations.api.editApiKeyScope')"+ @click="openEditAPIKeyScope(key)"+ >+ <t-icon name="edit-1" />+ </t-button><t-buttonshape="square"variant="text"@@ -555,6 +563,110 @@</div></SettingDrawer>+ <SettingDrawer+ :visible="apiKeyScopeDialogVisible"+ class="api-key-edit-drawer"+ :title="$t('integrations.api.editApiKeyScope')"+ :description="$t('integrations.api.editApiKeyScopeDesc', { name: editingAPIKey?.name || '' })"+ icon="edit-1"+ width="560px"+ :min-width="440"+ :max-width="760"+ storage-key="setting-drawer:width:api-key-scope"+ :confirm-text="$t('common.save')"+ :confirm-loading="apiKeyScopeSaving"+ @update:visible="(v: boolean) => apiKeyScopeDialogVisible = v"+ @confirm="saveAPIKeyConfiguration"+ >+ <div class="api-key-dialog">+ <div class="api-key-dialog-row">+ <div class="api-key-dialog-row__label">+ <label>{{ $t('integrations.api.apiKeyName') }}</label>+ </div>+ <t-input+ v-model="editingAPIKeyForm.name"+ :placeholder="$t('integrations.api.apiKeyNamePlaceholder')"+ />+ </div>++ <div class="api-key-dialog-row">+ <div class="api-key-dialog-row__label">+ <label>{{ $t('integrations.api.apiKeyAccessType') }}</label>+ </div>+ <t-radio-group v-model="editingAPIKeyAccessMode" 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-hint">+ {{+ editingAPIKeyFullAccessEnabled+ ? $t('integrations.api.capabilityTenantFullHint')+ : $t('integrations.api.apiKeyAccessTypeHint')+ }}+ </p>+ </div>++ <div v-if="!editingAPIKeyFullAccessEnabled" class="api-key-dialog-row">+ <div class="api-key-dialog-row__label">+ <label>{{ $t('integrations.api.apiKeyCapabilities') }}</label>+ </div>+ <div 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="toggleEditingCapabilityGroup(group, !editingCapabilityGroupAllSelected(group))"+ >+ {{+ editingCapabilityGroupAllSelected(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="editingCapabilitySelections[capability.value]"+ @change="editingCapabilitySelections[capability.value] = Boolean($event)"+ >+ {{ $t(capability.labelKey) }}+ </t-checkbox>+ <p class="scope-hint">{{ $t(capability.hintKey) }}</p>+ </div>+ </div>+ </div>+ </div>+ </div>++ <div v-if="editingKnowledgeScopeApplies" class="api-key-dialog-row">+ <div class="api-key-dialog-row__label">+ <label>{{ $t('integrations.api.apiKeyKnowledgeScope') }}</label>+ </div>+ <t-select+ v-model="editingAPIKeyForm.knowledge_base_ids"+ multiple+ filterable+ clearable+ :loading="knowledgeBasesLoading"+ :options="knowledgeBaseOptions"+ :placeholder="$t('integrations.api.apiKeyKnowledgeScopePlaceholder')"+ />+ <p class="scope-hint">{{ $t('integrations.api.editApiKeyScopeHint') }}</p>+ </div>+ </div>+ </SettingDrawer>+</div></template>@@ -571,6 +683,7 @@ import {createAPIPrincipalTestToken,getAPIPrincipalConfig,listTenantAPIKeys,+ updateTenantAPIKey,updateAPIPrincipalConfig,type APIPrincipalConfig,type APIPrincipalMode,@@ -586,6 +699,7 @@ import {TENANT_API_KEY_CAPABILITY_GROUPS,type ApiKeyCapabilityGroup,} from '@/config/apiKeyCapabilities'+import { normalizeAPIKeyKnowledgeBaseIDs } from './apiKeyScope'const { t } = useI18n()@@ -602,6 +716,9 @@ const apiKeys = ref<TenantAPIKey[]>([])const apiKeysLoading = ref(false)const apiKeyDialogVisible = ref(false)const apiKeyCreating = ref(false)+const apiKeyScopeDialogVisible = ref(false)+const apiKeyScopeSaving = ref(false)+const editingAPIKey = ref<TenantAPIKey | null>(null)const knowledgeBasesLoading = ref(false)const knowledgeBases = ref<Array<{ id: string; name: string }>>([])const secretInput = ref('')@@ -641,6 +758,49 @@ const capabilitySelections = reactive<Record<TenantAPIKeyCapability, boolean>>(}, {} as Record<TenantAPIKeyCapability, boolean>),)+const editingCapabilitySelections = reactive<Record<TenantAPIKeyCapability, boolean>>(+ API_KEY_CAPABILITIES.reduce((acc, capability) => {+ acc[capability] = false+ return acc+ }, {} as Record<TenantAPIKeyCapability, boolean>),+)++const editingAPIKeyForm = reactive({+ name: '',+ knowledge_base_ids: [] as string[],+ tenant_full_enabled: false,+ expires_at_unix: undefined as number | undefined,+})++const editingAPIKeyFullAccessEnabled = computed(() => editingAPIKeyForm.tenant_full_enabled)+const editingAPIKeyAccessMode = computed<'scoped' | 'full'>({+ get: () => (editingAPIKeyForm.tenant_full_enabled ? 'full' : 'scoped'),+ set: (value) => {+ editingAPIKeyForm.tenant_full_enabled = value === 'full'+ },+})+const editingSelectedCapabilities = computed(() => (+ API_KEY_CAPABILITIES.filter((capability) => editingCapabilitySelections[capability])+))+const editingKnowledgeScopeApplies = computed(() => (+ !editingAPIKeyFullAccessEnabled.value+ && editingSelectedCapabilities.value.some((capability) => KB_SCOPED_CAPABILITIES.has(capability))+))++watch(editingKnowledgeScopeApplies, (applies) => {+ if (!applies) editingAPIKeyForm.knowledge_base_ids = []+})++function editingCapabilityGroupAllSelected(group: ApiKeyCapabilityGroup): boolean {+ return group.capabilities.every((capability) => editingCapabilitySelections[capability.value])+}++function toggleEditingCapabilityGroup(group: ApiKeyCapabilityGroup, selected: boolean) {+ group.capabilities.forEach((capability) => {+ editingCapabilitySelections[capability.value] = selected+ })+}+const apiKeyForm = reactive({name: '',knowledge_base_ids: [] as string[],@@ -1301,6 +1461,10 @@ async function createScopedAPIKey() {MessagePlugin.error(t('integrations.api.apiKeyNameRequired'))return}+ if (!apiKeyFullAccessEnabled.value && selectedCapabilities().length === 0) {+ MessagePlugin.error(t('integrations.api.apiKeyCapabilitiesRequired'))+ return+ }apiKeyCreating.value = truetry {const resp = await createTenantAPIKey(tenantId.value, {@@ -1325,6 +1489,59 @@ async function createScopedAPIKey() {}}+// 打开编辑器时复制服务端配置,取消操作不会污染列表中的原始数据。+function openEditAPIKeyScope(key: TenantAPIKey) {+ editingAPIKey.value = key+ editingAPIKeyForm.name = key.name+ editingAPIKeyForm.tenant_full_enabled = key.full_access+ editingAPIKeyForm.knowledge_base_ids = normalizeAPIKeyKnowledgeBaseIDs(key.knowledge_base_ids)+ const expiresAt = key.expires_at ? Date.parse(key.expires_at) : Number.NaN+ editingAPIKeyForm.expires_at_unix = Number.isNaN(expiresAt)+ ? undefined+ : Math.floor(expiresAt / 1000)+ const currentCapabilities = new Set(key.capabilities || [])+ API_KEY_CAPABILITIES.forEach((capability) => {+ editingCapabilitySelections[capability] = currentCapabilities.has(capability)+ })+ apiKeyScopeDialogVisible.value = true+ void loadKnowledgeBaseOptions()+}++// 保存完整配置后刷新列表,确保鉴权范围与界面立即一致。+async function saveAPIKeyConfiguration() {+ const key = editingAPIKey.value+ if (!key) return+ if (!editingAPIKeyForm.name.trim()) {+ MessagePlugin.error(t('integrations.api.apiKeyNameRequired'))+ return+ }+ if (!editingAPIKeyFullAccessEnabled.value && editingSelectedCapabilities.value.length === 0) {+ MessagePlugin.error(t('integrations.api.apiKeyCapabilitiesRequired'))+ return+ }+ apiKeyScopeSaving.value = true+ try {+ const resp = await updateTenantAPIKey(tenantId.value, key.id, {+ name: editingAPIKeyForm.name.trim(),+ full_access: editingAPIKeyFullAccessEnabled.value,+ capabilities: editingAPIKeyFullAccessEnabled.value ? [] : editingSelectedCapabilities.value,+ knowledge_base_ids: editingKnowledgeScopeApplies.value ? editingAPIKeyForm.knowledge_base_ids : [],+ expires_at_unix: editingAPIKeyForm.expires_at_unix,+ })+ if (!resp.success || !resp.data) {+ throw new Error(resp.message || t('integrations.api.updateApiKeyScopeFailed'))+ }+ apiKeyScopeDialogVisible.value = false+ editingAPIKey.value = null+ MessagePlugin.success(t('integrations.api.updateApiKeyScopeSuccess'))+ await loadAPIKeys()+ } catch (err: any) {+ MessagePlugin.error(err?.message || t('integrations.api.updateApiKeyScopeFailed'))+ } finally {+ apiKeyScopeSaving.value = false+ }+}+function confirmDeleteAPIKey(id: number) {const dialog = DialogPlugin.confirm({header: t('integrations.api.deleteApiKey'),@@ -1349,9 +1566,10 @@ async function deleteScopedAPIKey(id: number) {await loadAPIKeys()}-function formatKeyKnowledgeScope(ids: string[] = []) {- if (!ids.length) return t('integrations.api.allKnowledgeBases')- const names = ids.map((id) => knowledgeBases.value.find((kb) => kb.id === id)?.name || id)+function formatKeyKnowledgeScope(ids: readonly string[] | null | undefined) {+ const normalizedIDs = normalizeAPIKeyKnowledgeBaseIDs(ids)+ if (!normalizedIDs.length) return t('integrations.api.allKnowledgeBases')+ const names = normalizedIDs.map((id) => knowledgeBases.value.find((kb) => kb.id === id)?.name || id)return names.join(', ')}diff --git a/frontend/src/views/integrations/apiKeyScope.test.ts b/frontend/src/views/integrations/apiKeyScope.test.tsnew file mode 100644index 000000000..47a54c217--- /dev/null+++ b/frontend/src/views/integrations/apiKeyScope.test.ts@@ -0,0 +1,26 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import { normalizeAPIKeyKnowledgeBaseIDs } from './apiKeyScope.ts'++/**+ * 验证完全授权 Key 的 null/undefined 范围会转换为空数组,避免列表渲染读取 length 时白屏。+ * 传入服务端可能返回的空值,期望返回表示“全部知识库”的空数组。+ */+test('normalizes missing API key knowledge base scope to an empty array', () => {+ assert.deepEqual(normalizeAPIKeyKnowledgeBaseIDs(null), [])+ assert.deepEqual(normalizeAPIKeyKnowledgeBaseIDs(undefined), [])+})++/**+ * 验证 scoped Key 的知识库 ID 会被完整复制,且返回值不是原数组,避免编辑表单污染列表数据。+ * 传入两个知识库 ID,期望按原顺序返回一份新数组。+ */+test('copies configured API key knowledge base scope', () => {+ const ids = ['kb-1', 'kb-2']+ const normalized = normalizeAPIKeyKnowledgeBaseIDs(ids)++ assert.deepEqual(normalized, ids)+ assert.notEqual(normalized, ids)+ assert.deepEqual(normalizeAPIKeyKnowledgeBaseIDs([]), [])+})diff --git a/frontend/src/views/integrations/apiKeyScope.ts b/frontend/src/views/integrations/apiKeyScope.tsnew file mode 100644index 000000000..b4183967c--- /dev/null+++ b/frontend/src/views/integrations/apiKeyScope.ts@@ -0,0 +1,11 @@+/**+ * 将 API 返回的知识库范围归一化为前端表单可安全使用的数组。+ *+ * @param ids API Key 的知识库 ID;完全授权的 Key 可能由服务端返回 null。+ * @returns 一份新的知识库 ID 数组;null 或 undefined 返回空数组,表示全部知识库。+ */+export function normalizeAPIKeyKnowledgeBaseIDs(+ ids: readonly string[] | null | undefined,+): string[] {+ return ids ? [...ids] : []+}diff --git a/internal/application/repository/tenant_api_key.go b/internal/application/repository/tenant_api_key.goindex 1daff605a..9cd4241d7 100644--- a/internal/application/repository/tenant_api_key.go+++ b/internal/application/repository/tenant_api_key.go@@ -56,6 +56,41 @@ func (r *tenantAPIKeyRepository) ListPlatformAPIKeys(ctx context.Context) ([]*tyreturn keys, err}+// UpdateAPIKey 更新租户 API Key 的可配置属性。+// tenant_id 和 scope_type 同时参与条件,避免跨租户或误改平台级 Key。+func (r *tenantAPIKeyRepository) UpdateAPIKey(+ ctx context.Context, tenantID uint64, id uint64, update *types.TenantAPIKey,+) (*types.TenantAPIKey, error) {+ res := r.db.WithContext(ctx).+ Model(&types.TenantAPIKey{}).+ Where("id = ? AND tenant_id = ? AND scope_type = ? AND revoked_at IS NULL",+ id, tenantID, types.APIKeyScopeTenant).+ Updates(map[string]any{+ "name": update.Name,+ "full_access": update.FullAccess,+ "knowledge_base_ids": update.KnowledgeBaseIDs,+ "capabilities": update.Capabilities,+ "expires_at": update.ExpiresAt,+ })+ if res.Error != nil {+ return nil, res.Error+ }+ if res.RowsAffected == 0 {+ return nil, ErrTenantAPIKeyNotFound+ }++ var updatedKey types.TenantAPIKey+ if err := r.db.WithContext(ctx).+ Where("id = ? AND tenant_id = ? AND revoked_at IS NULL", id, tenantID).+ First(&updatedKey).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrTenantAPIKeyNotFound+ }+ return nil, err+ }+ return &updatedKey, nil+}+func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {now := time.Now().UTC()res := r.db.WithContext(ctx).diff --git a/internal/application/repository/tenant_api_key_test.go b/internal/application/repository/tenant_api_key_test.goindex c7a3a0cfe..c4653003b 100644--- a/internal/application/repository/tenant_api_key_test.go+++ b/internal/application/repository/tenant_api_key_test.go@@ -40,3 +40,45 @@ func TestTenantAPIKeyRepositoryPersistsUTCExpiry(t *testing.T) {require.Equal(t, time.UTC, loaded.ExpiresAt.Location())require.True(t, loaded.ExpiresAt.Equal(expiresAt))}++// TestTenantAPIKeyRepositoryUpdateIsTenantScoped 验证通用更新不会越过租户边界。+// 输入同租户和其他租户的 Key;前者更新全部可配置字段,后者必须返回未找到。+func TestTenantAPIKeyRepositoryUpdateIsTenantScoped(t *testing.T) {+ db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(&types.TenantAPIKey{}))+ repo := NewTenantAPIKeyRepository(db)+ ctx := context.Background()+ tenant42, tenant43 := uint64(42), uint64(43)+ keys := []*types.TenantAPIKey{+ {TenantID: &tenant42, ScopeType: types.APIKeyScopeTenant, Name: "scoped", KeyHash: "hash-scoped", APIKey: "sk-scoped"},+ {TenantID: &tenant43, ScopeType: types.APIKeyScopeTenant, Name: "other", KeyHash: "hash-other", APIKey: "sk-other"},+ {TenantID: &tenant42, ScopeType: types.APIKeyScopeTenant, Name: "full", KeyHash: "hash-full", APIKey: "sk-full", FullAccess: true},+ }+ for _, key := range keys {+ require.NoError(t, repo.CreateAPIKey(ctx, key))+ }++ expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Second)+ updated, err := repo.UpdateAPIKey(ctx, tenant42, keys[0].ID, &types.TenantAPIKey{+ Name: "updated", FullAccess: false,+ KnowledgeBaseIDs: types.StringArray{"kb-1", "kb-2"},+ Capabilities: types.StringArray{"retrieve", "chat"},+ ExpiresAt: &expiresAt,+ })+ require.NoError(t, err)+ require.Equal(t, "updated", updated.Name)+ require.Equal(t, types.StringArray{"kb-1", "kb-2"}, updated.KnowledgeBaseIDs)+ require.Equal(t, types.StringArray{"retrieve", "chat"}, updated.Capabilities)+ require.NotNil(t, updated.ExpiresAt)+ require.True(t, updated.ExpiresAt.Equal(expiresAt))++ _, err = repo.UpdateAPIKey(ctx, tenant42, keys[1].ID, &types.TenantAPIKey{Name: "blocked"})+ require.ErrorIs(t, err, ErrTenantAPIKeyNotFound)++ full, err := repo.UpdateAPIKey(ctx, tenant42, keys[2].ID, &types.TenantAPIKey{+ Name: "full updated", FullAccess: false, Capabilities: types.StringArray{"retrieve"},+ })+ require.NoError(t, err)+ require.False(t, full.FullAccess)+}diff --git a/internal/application/service/tenant_api_key.go b/internal/application/service/tenant_api_key.goindex f6a187e6e..09a5243da 100644--- a/internal/application/service/tenant_api_key.go+++ b/internal/application/service/tenant_api_key.go@@ -130,6 +130,44 @@ func (s *tenantAPIKeyService) ListPlatformAPIKeys(ctx context.Context) ([]*typesreturn s.repo.ListPlatformAPIKeys(ctx)}+// UpdateAPIKey 按创建接口的相同语义更新租户 API Key 配置。+// scoped Key 需要至少一个能力;full-access Key 会清空细粒度能力和知识库范围。+func (s *tenantAPIKeyService) UpdateAPIKey(+ ctx context.Context, req interfaces.TenantAPIKeyUpdateRequest,+) (*types.TenantAPIKey, error) {+ if req.TenantID == 0 {+ return nil, errors.New("tenant_id is required")+ }+ if req.APIKeyID == 0 {+ return nil, errors.New("api_key_id is required")+ }+ name := strings.TrimSpace(req.Name)+ if name == "" {+ return nil, errors.New("name is required")+ }+ capabilities := types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities))+ if !req.FullAccess && len(capabilities) == 0 {+ return nil, errors.New("capabilities are required for scoped API keys")+ }+ expiresAt := req.ExpiresAt+ if expiresAt != nil {+ utc := expiresAt.UTC()+ expiresAt = &utc+ }+ key := &types.TenantAPIKey{+ Name: name,+ FullAccess: req.FullAccess,+ KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),+ Capabilities: capabilities,+ ExpiresAt: expiresAt,+ }+ if key.FullAccess {+ key.KnowledgeBaseIDs = nil+ key.Capabilities = nil+ }+ return s.repo.UpdateAPIKey(ctx, req.TenantID, req.APIKeyID, key)+}+func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {return s.repo.RevokeAPIKey(ctx, tenantID, id)}diff --git a/internal/application/service/tenant_api_key_test.go b/internal/application/service/tenant_api_key_test.goindex 7c192f77e..ba9f56f93 100644--- a/internal/application/service/tenant_api_key_test.go+++ b/internal/application/service/tenant_api_key_test.go@@ -96,6 +96,86 @@ func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64,return apprepo.ErrTenantAPIKeyNotFound}+// UpdateAPIKey 模拟仓储的租户边界并覆盖 API Key 的可配置属性。+// 传入租户 ID、Key ID 和新配置,返回更新后的 Key;跨租户或已撤销目标返回未找到。+func (r *fakeTenantAPIKeyRepo) UpdateAPIKey(+ _ context.Context, tenantID uint64, id uint64, update *types.TenantAPIKey,+) (*types.TenantAPIKey, error) {+ for _, key := range r.byHash {+ if key.ID == id && key.TenantIDValue() == tenantID && key.RevokedAt == nil {+ key.Name = update.Name+ key.FullAccess = update.FullAccess+ key.KnowledgeBaseIDs = append(types.StringArray(nil), update.KnowledgeBaseIDs...)+ key.Capabilities = append(types.StringArray(nil), update.Capabilities...)+ key.ExpiresAt = update.ExpiresAt+ cp := *key+ return &cp, nil+ }+ }+ return nil, apprepo.ErrTenantAPIKeyNotFound+}++// TestTenantAPIKeyServiceUpdateNormalizesConfiguration 验证通用更新的输入规范化。+// 输入包含重复 ID/能力和 UTC+8 到期时间,输出应去重、清理名称并统一为 UTC。+func TestTenantAPIKeyServiceUpdateNormalizesConfiguration(t *testing.T) {+ ctx := context.Background()+ repo := newFakeTenantAPIKeyRepo()+ svc := NewTenantAPIKeyService(repo)+ created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{+ TenantID: 42, Name: "scoped", Capabilities: []string{"retrieve"},+ })+ if err != nil {+ t.Fatalf("CreateAPIKey returned error: %v", err)+ }++ expiresAt := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("UTC+8", 8*60*60))+ updated, err := svc.UpdateAPIKey(ctx, interfaces.TenantAPIKeyUpdateRequest{+ TenantID: 42, APIKeyID: created.APIKey.ID,+ Name: " updated ", Capabilities: []string{"retrieve", "chat", "retrieve"},+ KnowledgeBaseIDs: []string{" kb-1 ", "", "kb-2", "kb-1"},+ ExpiresAt: &expiresAt,+ })+ if err != nil {+ t.Fatalf("UpdateAPIKey returned error: %v", err)+ }+ if updated.Name != "updated" {+ t.Fatalf("name = %q, want updated", updated.Name)+ }+ if got, want := []string(updated.KnowledgeBaseIDs), []string{"kb-1", "kb-2"}; !apiKeyEqualStrings(got, want) {+ t.Fatalf("knowledge_base_ids = %#v, want %#v", got, want)+ }+ if got, want := []string(updated.Capabilities), []string{"retrieve", "chat"}; !apiKeyEqualStrings(got, want) {+ t.Fatalf("capabilities = %#v, want %#v", got, want)+ }+ if updated.ExpiresAt == nil || updated.ExpiresAt.Location() != time.UTC {+ t.Fatalf("expires_at = %v, want UTC", updated.ExpiresAt)+ }++ full, err := svc.UpdateAPIKey(ctx, interfaces.TenantAPIKeyUpdateRequest{+ TenantID: 42, APIKeyID: created.APIKey.ID, Name: "full", FullAccess: true,+ KnowledgeBaseIDs: []string{"kb-ignored"}, Capabilities: []string{"retrieve"},+ })+ if err != nil {+ t.Fatalf("updating to full access returned error: %v", err)+ }+ if !full.FullAccess || len(full.KnowledgeBaseIDs) != 0 || len(full.Capabilities) != 0 {+ t.Fatalf("full access scope = full:%v kbs:%v caps:%v, want true/empty/empty",+ full.FullAccess, full.KnowledgeBaseIDs, full.Capabilities)+ }+}++func apiKeyEqualStrings(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}+func (r *fakeTenantAPIKeyRepo) RevokePlatformAPIKey(_ context.Context, id uint64) error {now := time.Now()for _, key := range r.byHash {diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex 9bc99927c..92195500f 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -143,6 +143,15 @@ type tenantAPIKeyCreateRequest struct {ExpiresAt *int64 `json:"expires_at_unix"`}+// tenantAPIKeyUpdateRequest 修改已创建 API Key 的配置,字段语义与创建接口一致。+type tenantAPIKeyUpdateRequest struct {+ Name string `json:"name"`+ FullAccess bool `json:"full_access"`+ KnowledgeBaseIDs []string `json:"knowledge_base_ids"`+ Capabilities []string `json:"capabilities"`+ ExpiresAt *int64 `json:"expires_at_unix"`+}+type tenantAPIKeyResponse struct {ID uint64 `json:"id"`ScopeType types.APIKeyScopeType `json:"scope_type"`@@ -713,6 +722,46 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {})}+// UpdateAPIKey 修改已创建租户 API Key 的授权范围和其他可配置属性。+// 路由层要求当前租户 Owner;字段校验与创建接口保持一致。+func (h *TenantHandler) UpdateAPIKey(c *gin.Context) {+ ctx := c.Request.Context()+ tenantID, err := strconv.ParseUint(c.Param("id"), 10, 64)+ if err != nil || tenantID == 0 {+ c.Error(errors.NewBadRequestError("Invalid workspace ID"))+ return+ }+ keyID, err := strconv.ParseUint(c.Param("key_id"), 10, 64)+ if err != nil || keyID == 0 {+ c.Error(errors.NewBadRequestError("Invalid API key ID"))+ return+ }+ var req tenantAPIKeyUpdateRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))+ return+ }+ if appErr := validateTenantAPIKeyRequest(ctx, h.kbService, tenantID, tenantAPIKeyCreateRequest(req)); appErr != nil {+ c.Error(appErr)+ return+ }+ var expiresAt *time.Time+ if req.ExpiresAt != nil {+ t := time.Unix(*req.ExpiresAt, 0).UTC()+ expiresAt = &t+ }++ updated, err := h.apiKeyService.UpdateAPIKey(ctx, interfaces.TenantAPIKeyUpdateRequest{+ TenantID: tenantID, APIKeyID: keyID, Name: req.Name, FullAccess: req.FullAccess,+ KnowledgeBaseIDs: req.KnowledgeBaseIDs, Capabilities: req.Capabilities, ExpiresAt: expiresAt,+ })+ if err != nil {+ c.Error(errors.NewNotFoundError("API key not found"))+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": tenantAPIKeyForResponse(updated)})+}+func (h *TenantHandler) DeleteAPIKey(c *gin.Context) {ctx := c.Request.Context()tenantID, err := strconv.ParseUint(c.Param("id"), 10, 64)@@ -774,12 +823,39 @@ func validateTenantAPIKeyRequest(return errors.NewValidationError("capabilities contains an unknown capability")}}- for _, kbID := range req.KnowledgeBaseIDs {+ return validateTenantAPIKeyKnowledgeBaseIDs(ctx, kbService, tenantID, req.KnowledgeBaseIDs)+}++// validateTenantAPIKeyKnowledgeBaseIDs 校验白名单中的知识库真实存在且属于目标租户。+// 入参是请求上下文、知识库服务、租户 ID 和待授权 ID;成功无返回值,失败返回可直接响应的应用错误。+func validateTenantAPIKeyKnowledgeBaseIDs(+ ctx context.Context,+ kbService interfaces.KnowledgeBaseService,+ tenantID uint64,+ knowledgeBaseIDs []string,+) *errors.AppError {+ if len(knowledgeBaseIDs) == 0 {+ return nil+ }+ return validateTenantAPIKeyKnowledgeBaseIDsWithLookup(+ ctx, tenantID, knowledgeBaseIDs, kbService.GetKnowledgeBaseByID,+ )+}++// validateTenantAPIKeyKnowledgeBaseIDsWithLookup 将归属校验与大型知识库服务接口解耦,便于覆盖边界测试。+// lookup 输入知识库 ID 并返回真实知识库;函数输出 nil 或可直接响应的校验错误。+func validateTenantAPIKeyKnowledgeBaseIDsWithLookup(+ ctx context.Context,+ tenantID uint64,+ knowledgeBaseIDs []string,+ lookup func(context.Context, string) (*types.KnowledgeBase, error),+) *errors.AppError {+ for _, kbID := range knowledgeBaseIDs {kbID = strings.TrimSpace(kbID)if kbID == "" {continue}- kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID)+ kb, err := lookup(ctx, kbID)if err != nil || kb == nil {return errors.NewValidationError("knowledge_base_ids contains an unknown knowledge base")}diff --git a/internal/handler/tenant_api_key_validation_test.go b/internal/handler/tenant_api_key_validation_test.goindex ecce5547a..020cfd777 100644--- a/internal/handler/tenant_api_key_validation_test.go+++ b/internal/handler/tenant_api_key_validation_test.go@@ -3,6 +3,8 @@ package handlerimport ("context""testing"++ "github.com/Tencent/WeKnora/internal/types")func TestValidateTenantAPIKeyRequestRequiresCapabilitiesForScopedKey(t *testing.T) {@@ -33,3 +35,28 @@ func TestValidateTenantAPIKeyRequestAcceptsScopedKeyWithCapability(t *testing.T)t.Fatalf("scoped key validation error = %v", err)}}++// TestValidateTenantAPIKeyKnowledgeBaseOwnership 验证知识库白名单的租户边界。+// 输入同租户、其他租户和不存在的知识库 ID;仅同租户 ID 应通过。+func TestValidateTenantAPIKeyKnowledgeBaseOwnership(t *testing.T) {+ lookup := func(_ context.Context, id string) (*types.KnowledgeBase, error) {+ switch id {+ case "kb-owned":+ return &types.KnowledgeBase{ID: id, TenantID: 42}, nil+ case "kb-other":+ return &types.KnowledgeBase{ID: id, TenantID: 43}, nil+ default:+ return nil, context.Canceled+ }+ }++ if err := validateTenantAPIKeyKnowledgeBaseIDsWithLookup(context.Background(), 42, []string{"kb-owned"}, lookup); err != nil {+ t.Fatalf("owned knowledge base validation error = %v", err)+ }+ if err := validateTenantAPIKeyKnowledgeBaseIDsWithLookup(context.Background(), 42, []string{"kb-other"}, lookup); err == nil {+ t.Fatal("expected cross-tenant knowledge base to be rejected")+ }+ if err := validateTenantAPIKeyKnowledgeBaseIDsWithLookup(context.Background(), 42, []string{"kb-missing"}, lookup); err == nil {+ t.Fatal("expected missing knowledge base to be rejected")+ }+}diff --git a/internal/router/router_api_key_management_test.go b/internal/router/router_api_key_management_test.goindex 1d3718ae9..b5f2b9152 100644--- a/internal/router/router_api_key_management_test.go+++ b/internal/router/router_api_key_management_test.go@@ -31,6 +31,7 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {{tenantByID.GET("/api-keys", reachedOK)tenantByID.POST("/api-keys", reachedOK)+ tenantByID.PUT("/api-keys/:key_id", reachedOK)tenantByID.DELETE("/api-keys/:key_id", reachedOK)tenantByID.GET("/api-principal-config", reachedOK)tenantByID.PUT("/api-principal-config", reachedOK)@@ -47,6 +48,7 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {}{{http.MethodGet, "/api/v1/tenants/42/api-keys"},{http.MethodPost, "/api/v1/tenants/42/api-keys"},+ {http.MethodPut, "/api/v1/tenants/42/api-keys/7"},{http.MethodDelete, "/api/v1/tenants/42/api-keys/7"},{http.MethodGet, "/api/v1/tenants/42/api-principal-config"},{http.MethodPut, "/api/v1/tenants/42/api-principal-config"},diff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.goindex cd5f55f10..319577112 100644--- a/internal/router/routes_auth_tenant.go+++ b/internal/router/routes_auth_tenant.go@@ -16,7 +16,7 @@ import (// - GET /:id Viewer+ (read tenant settings)// - PUT /:id Owner+ (mutate tenant config)// - DELETE /:id Owner+ (also normally a CanAccessAllTenants op)-// - GET/POST/DELETE /:id/api-keys Owner+ (scoped API key management)+// - GET/POST/PUT/DELETE /:id/api-keys Owner+ (scoped API key management)// - GET /:id/members Viewer+ (any member can see who else is in)// - POST /:id/members Owner+ (only Owner can add new members)// - PUT /:id/members/:user_id Owner+ (only Owner can change roles)@@ -96,6 +96,7 @@ func RegisterTenantRoutes(apiKeyPlatform(types.APIKeyCapabilitySystemTenantsManage), g.Owner(), handler.DeleteTenant)tenantByID.GET("/api-keys", g.Owner(), handler.ListAPIKeys)tenantByID.POST("/api-keys", g.Owner(), handler.CreateAPIKey)+ tenantByID.PUT("/api-keys/:key_id", g.Owner(), handler.UpdateAPIKey)tenantByID.DELETE("/api-keys/:key_id", g.Owner(), handler.DeleteAPIKey)tenantByID.GET("/api-principal-config", g.Owner(), handler.GetAPIPrincipalConfig)tenantByID.PUT("/api-principal-config", g.Owner(), handler.UpdateAPIPrincipalConfig)diff --git a/internal/types/interfaces/tenant.go b/internal/types/interfaces/tenant.goindex 15e6d2b7e..5beea60d8 100644--- a/internal/types/interfaces/tenant.go+++ b/internal/types/interfaces/tenant.go@@ -77,11 +77,24 @@ type TenantAPIKeyCreateResult struct {Token string}+// TenantAPIKeyUpdateRequest 修改已创建租户 API Key 的可配置属性。+// 配置语义与创建接口一致:FullAccess 为 true 时忽略细粒度能力和知识库范围。+type TenantAPIKeyUpdateRequest struct {+ TenantID uint64+ APIKeyID uint64+ Name string+ FullAccess bool+ KnowledgeBaseIDs []string+ Capabilities []string+ ExpiresAt *time.Time+}+type TenantAPIKeyRepository interface {CreateAPIKey(ctx context.Context, key *types.TenantAPIKey) errorGetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error)ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error)+ UpdateAPIKey(ctx context.Context, tenantID uint64, id uint64, key *types.TenantAPIKey) (*types.TenantAPIKey, error)RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) errorRevokePlatformAPIKey(ctx context.Context, id uint64) errorUpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error@@ -100,6 +113,7 @@ type TenantAPIKeyService interface {AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error)ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)ListPlatformAPIKeys(ctx context.Context) ([]*types.TenantAPIKey, error)+ UpdateAPIKey(ctx context.Context, req TenantAPIKeyUpdateRequest) (*types.TenantAPIKey, error)RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) errorRevokePlatformAPIKey(ctx context.Context, id uint64) error// BackfillMissingKeyHashes computes and persists the SHA-256 key_hash