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
refactor(api-keys): remove API key reset endpoint and update documentation
wizardchen97c36f634abe
diff --git a/cmd/server/bootstrap.go b/cmd/server/bootstrap.goindex b33d9950d..474181930 100644--- a/cmd/server/bootstrap.go+++ b/cmd/server/bootstrap.go@@ -39,10 +39,9 @@ const bootstrapEnvVar = "WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL"func runStartupBootstrap(c *dig.Container) {ctx := context.Background()- // One-shot: backfill SHA-256 key_hash for legacy tenant API keys that- // migration 000065 seeded with a placeholder. Without this, the first- // authentication of each migrated key falls back to an O(n) plaintext- // scan of the tenant's keys. Best-effort: warn, never abort startup.+ // Legacy hash repair for migration 000065 placeholder rows. Invoked each+ // startup but short-circuits with a cheap EXISTS once every row is+ // backfilled (no api_key decryption on the steady-state path).if err := c.Invoke(func(apiKeySvc interfaces.TenantAPIKeyService) {if n, err := apiKeySvc.BackfillMissingKeyHashes(ctx); err != nil {logger.Warnf(ctx, "[bootstrap] tenant api key hash backfill failed: %v", err)diff --git a/docs/api/tenant.md b/docs/api/tenant.mdindex 36ab21556..86665cd03 100644--- a/docs/api/tenant.md+++ b/docs/api/tenant.md@@ -3,7 +3,7 @@[返回目录](./README.md)包含两组接口:-- 租户 CRUD(`/tenants`、`/tenants/:id`、`/tenants/:id/api-key`):当前认证用户对自己所属租户进行管理;跨租户访问需要管理员权限。+- 租户 CRUD(`/tenants`、`/tenants/:id`):当前认证用户对自己所属租户进行管理;跨租户访问需要管理员权限。- 跨租户接口(`/tenants/all`、`/tenants/search`):**需要服务端启用 `EnableCrossTenantAccess` 且当前用户具备 `CanAccessAllTenants` 权限**,否则返回 403。- 租户 KV 配置(`/tenants/kv/:key`):当前租户级别的通用配置项,**`tenant_id` 从认证上下文中获取,不在 URL 中传入**。@@ -15,7 +15,6 @@| GET | `/tenants/:id` | 获取指定租户信息 || PUT | `/tenants/:id` | 更新租户信息 || DELETE | `/tenants/:id` | 删除租户 |-| POST | `/tenants/:id/api-key` | 重置租户 API Key(吊销该租户全部旧 Key 后创建一把新的全权限 Key) || GET | `/tenants/:id/api-keys` | 列出租户 API Key(Owner) || POST | `/tenants/:id/api-keys` | 创建带角色的 API Key(Owner) || DELETE | `/tenants/:id/api-keys/:key_id` | 吊销指定 API Key(Owner) |@@ -111,7 +110,7 @@ curl --location 'http://localhost:8080/api/v1/tenants/search?keyword=weknora&pag## POST `/tenants` - 创建新租户-创建一个新的租户。**不会**自动发放 API Key;请在创建后通过 `POST /tenants/:id/api-keys` 或 `POST /tenants/:id/api-key` 获取密钥。从旧版本升级时,原有 `tenants.api_key` 会迁移到 `tenant_api_keys` 表并继续可用,直至被吊销。+创建一个新的租户。**不会**自动发放 API Key;请在创建后通过 `POST /tenants/:id/api-keys` 创建密钥。从旧版本升级时,原有 `tenants.api_key` 会迁移到 `tenant_api_keys` 表并继续可用,直至被吊销。**参数说明(请求体)**:@@ -330,35 +329,6 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/tenants/10000' \}```-## POST `/tenants/:id/api-key` - 重置租户 API Key--为指定租户生成新的 API Key,并**吊销该租户下所有现有 Key**(含迁移进来的旧 Key)。新 Key 拥有 `read` + `write` + `admin` 全权限。访问规则同 `GET /tenants/:id`。--**路径参数**:--| 字段 | 类型 | 说明 |-| ---- | ---- | ------- |-| id | int | 租户 ID |--**请求**:--```curl-curl --location --request POST 'http://localhost:8080/api/v1/tenants/10000/api-key' \---header 'X-API-Key: sk-aaLRAgvCRJcmtiL2vLMeB1FB5UV0Q-qB7DlTE1pJ9KA93XZG' \---header 'Content-Type: application/json'-```--**响应**:--```json-{- "data": {- "api_key": "sk-IKtd9JGV4-aPGQ6RiL8YJu9Vzb3-ae4lgFkjFJZmhvUn2mLu"- },- "success": true-}-```-## 租户 API Key 管理(`tenant_api_keys`)自 scoped API Key 改造后,密钥以独立记录存储,支持:diff --git a/docs/docs.go b/docs/docs.goindex 254275af9..02f00b091 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -11957,14 +11957,14 @@ const docTemplate = `{}}},- "/tenants/{id}/api-key": {- "post": {+ "/tenants/{id}/api-principal-config": {+ "get": {"security": [{"Bearer": []}],- "description": "为指定租户生成一个新的 API Key,旧 Key 立即失效",+ "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)","consumes": ["application/json"],@@ -11974,7 +11974,7 @@ const docTemplate = `{"tags": ["租户管理"],- "summary": "重置租户 API Key",+ "summary": "获取租户 API Key 用户身份配置","parameters": [{"type": "integer",@@ -11986,7 +11986,7 @@ const docTemplate = `{],"responses": {"200": {- "description": "新生成的 API Key",+ "description": "API principal 配置","schema": {"type": "object","additionalProperties": true@@ -12005,16 +12005,14 @@ const docTemplate = `{}}}- }- },- "/tenants/{id}/api-principal-config": {- "get": {+ },+ "put": {"security": [{"Bearer": []}],- "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)",+ "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)","consumes": ["application/json"],@@ -12024,7 +12022,7 @@ const docTemplate = `{"tags": ["租户管理"],- "summary": "获取租户 API Key 用户身份配置",+ "summary": "更新租户 API Key 用户身份配置","parameters": [{"type": "integer",@@ -12032,11 +12030,20 @@ const docTemplate = `{"name": "id","in": "path","required": true+ },+ {+ "description": "API principal 配置",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"+ }}],"responses": {"200": {- "description": "API principal 配置",+ "description": "更新后的配置","schema": {"type": "object","additionalProperties": true@@ -12055,14 +12062,16 @@ const docTemplate = `{}}}- },- "put": {+ }+ },+ "/tenants/{id}/api-principal-test-token": {+ "post": {"security": [{"Bearer": []}],- "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)",+ "description": "使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)","consumes": ["application/json"],@@ -12072,7 +12081,7 @@ const docTemplate = `{"tags": ["租户管理"],- "summary": "更新租户 API Key 用户身份配置",+ "summary": "生成 API Playground 测试 JWT","parameters": [{"type": "integer",@@ -12082,18 +12091,18 @@ const docTemplate = `{"required": true},{- "description": "API principal 配置",+ "description": "测试 Token 参数","name": "request","in": "body","required": true,"schema": {- "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"+ "$ref": "#/definitions/internal_handler.apiPrincipalTestTokenRequest"}}],"responses": {"200": {- "description": "更新后的配置",+ "description": "短期 JWT","schema": {"type": "object","additionalProperties": true@@ -14327,6 +14336,10 @@ const docTemplate = `{"description": "===== Agent Mode Settings =====\nMaximum iterations for ReAct loop (only for agent type)","type": "integer"},+ "mcp_auth_wait_timeout": {+ "description": "MCPAuthWaitTimeout is how many seconds to wait for in-conversation OAuth\nauthorization before skipping. \u003c=0 uses the gate's configured timeout.",+ "type": "integer"+ },"mcp_selection_mode": {"description": "MCP service selection mode: \"all\" = all enabled MCP services, \"selected\" = specific services, \"none\" = no MCP","type": "string"@@ -17147,7 +17160,7 @@ const docTemplate = `{"type": "string"},"user_id": {- "description": "UserID is the owner of the session. Empty for legacy rows (visible at\ntenant level) and for IM-created sessions that do not map to a WeKnora user.",+ "description": "UserID is the owner scope for this session. WeKnora user UUIDs, API\nexternal-user principals, and embed visitor principals all use this column.","type": "string"}}@@ -17486,10 +17499,6 @@ const docTemplate = `{"github_com_Tencent_WeKnora_internal_types.Tenant": {"type": "object","properties": {- "api_key": {- "description": "API key",- "type": "string"- },"business": {"description": "Business","type": "string"@@ -19917,6 +19926,17 @@ const docTemplate = `{}}},+ "internal_handler.apiPrincipalTestTokenRequest": {+ "type": "object",+ "properties": {+ "expires_in_seconds": {+ "type": "integer"+ },+ "external_user_id": {+ "type": "string"+ }+ }+ },"internal_handler.auditLogListResponse": {"type": "object","properties": {diff --git a/docs/swagger.json b/docs/swagger.jsonindex 165b85f17..3642dcfe9 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -11950,14 +11950,14 @@}}},- "/tenants/{id}/api-key": {- "post": {+ "/tenants/{id}/api-principal-config": {+ "get": {"security": [{"Bearer": []}],- "description": "为指定租户生成一个新的 API Key,旧 Key 立即失效",+ "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)","consumes": ["application/json"],@@ -11967,7 +11967,7 @@"tags": ["租户管理"],- "summary": "重置租户 API Key",+ "summary": "获取租户 API Key 用户身份配置","parameters": [{"type": "integer",@@ -11979,7 +11979,7 @@],"responses": {"200": {- "description": "新生成的 API Key",+ "description": "API principal 配置","schema": {"type": "object","additionalProperties": true@@ -11998,16 +11998,14 @@}}}- }- },- "/tenants/{id}/api-principal-config": {- "get": {+ },+ "put": {"security": [{"Bearer": []}],- "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)",+ "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)","consumes": ["application/json"],@@ -12017,7 +12015,7 @@"tags": ["租户管理"],- "summary": "获取租户 API Key 用户身份配置",+ "summary": "更新租户 API Key 用户身份配置","parameters": [{"type": "integer",@@ -12025,11 +12023,20 @@"name": "id","in": "path","required": true+ },+ {+ "description": "API principal 配置",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"+ }}],"responses": {"200": {- "description": "API principal 配置",+ "description": "更新后的配置","schema": {"type": "object","additionalProperties": true@@ -12048,14 +12055,16 @@}}}- },- "put": {+ }+ },+ "/tenants/{id}/api-principal-test-token": {+ "post": {"security": [{"Bearer": []}],- "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)",+ "description": "使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)","consumes": ["application/json"],@@ -12065,7 +12074,7 @@"tags": ["租户管理"],- "summary": "更新租户 API Key 用户身份配置",+ "summary": "生成 API Playground 测试 JWT","parameters": [{"type": "integer",@@ -12075,18 +12084,18 @@"required": true},{- "description": "API principal 配置",+ "description": "测试 Token 参数","name": "request","in": "body","required": true,"schema": {- "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"+ "$ref": "#/definitions/internal_handler.apiPrincipalTestTokenRequest"}}],"responses": {"200": {- "description": "更新后的配置",+ "description": "短期 JWT","schema": {"type": "object","additionalProperties": true@@ -14320,6 +14329,10 @@"description": "===== Agent Mode Settings =====\nMaximum iterations for ReAct loop (only for agent type)","type": "integer"},+ "mcp_auth_wait_timeout": {+ "description": "MCPAuthWaitTimeout is how many seconds to wait for in-conversation OAuth\nauthorization before skipping. \u003c=0 uses the gate's configured timeout.",+ "type": "integer"+ },"mcp_selection_mode": {"description": "MCP service selection mode: \"all\" = all enabled MCP services, \"selected\" = specific services, \"none\" = no MCP","type": "string"@@ -17140,7 +17153,7 @@"type": "string"},"user_id": {- "description": "UserID is the owner of the session. Empty for legacy rows (visible at\ntenant level) and for IM-created sessions that do not map to a WeKnora user.",+ "description": "UserID is the owner scope for this session. WeKnora user UUIDs, API\nexternal-user principals, and embed visitor principals all use this column.","type": "string"}}@@ -17479,10 +17492,6 @@"github_com_Tencent_WeKnora_internal_types.Tenant": {"type": "object","properties": {- "api_key": {- "description": "API key",- "type": "string"- },"business": {"description": "Business","type": "string"@@ -19910,6 +19919,17 @@}}},+ "internal_handler.apiPrincipalTestTokenRequest": {+ "type": "object",+ "properties": {+ "expires_in_seconds": {+ "type": "integer"+ },+ "external_user_id": {+ "type": "string"+ }+ }+ },"internal_handler.auditLogListResponse": {"type": "object","properties": {diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex d91b3a6b8..56931e55e 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -660,6 +660,11 @@ definitions:===== Agent Mode Settings =====Maximum iterations for ReAct loop (only for agent type)type: integer+ mcp_auth_wait_timeout:+ description: |-+ MCPAuthWaitTimeout is how many seconds to wait for in-conversation OAuth+ authorization before skipping. <=0 uses the gate's configured timeout.+ type: integermcp_selection_mode:description: 'MCP service selection mode: "all" = all enabled MCP services,"selected" = specific services, "none" = no MCP'@@ -2787,8 +2792,8 @@ definitions:type: stringuser_id:description: |-- UserID is the owner of the session. Empty for legacy rows (visible at- tenant level) and for IM-created sessions that do not map to a WeKnora user.+ UserID is the owner scope for this session. WeKnora user UUIDs, API+ external-user principals, and embed visitor principals all use this column.type: stringtype: objectgithub_com_Tencent_WeKnora_internal_types.SessionLastRequestState:@@ -3044,9 +3049,6 @@ definitions:type: objectgithub_com_Tencent_WeKnora_internal_types.Tenant:properties:- api_key:- description: API key- type: stringbusiness:description: Businesstype: string@@ -4806,6 +4808,13 @@ definitions:signed_token_header_name:type: stringtype: object+ internal_handler.apiPrincipalTestTokenRequest:+ properties:+ expires_in_seconds:+ type: integer+ external_user_id:+ type: string+ type: objectinternal_handler.auditLogListResponse:properties:data:@@ -12585,11 +12594,11 @@ paths:summary: 更新租户tags:- 租户管理- /tenants/{id}/api-key:- post:+ /tenants/{id}/api-principal-config:+ get:consumes:- application/json- description: 为指定租户生成一个新的 API Key,旧 Key 立即失效+ description: 返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)parameters:- description: 租户IDin: path@@ -12600,7 +12609,7 @@ paths:- application/jsonresponses:"200":- description: 新生成的 API Key+ description: API principal 配置schema:additionalProperties: truetype: object@@ -12614,25 +12623,30 @@ paths:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'security:- Bearer: []- summary: 重置租户 API Key+ summary: 获取租户 API Key 用户身份配置tags:- 租户管理- /tenants/{id}/api-principal-config:- get:+ put:consumes:- application/json- description: 返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)+ description: 配置 X-API-Key 请求如何映射为终端 Principal(Owner)parameters:- description: 租户IDin: pathname: idrequired: truetype: integer+ - description: API principal 配置+ in: body+ name: request+ required: true+ schema:+ $ref: '#/definitions/internal_handler.apiPrincipalConfigRequest'produces:- application/jsonresponses:"200":- description: API principal 配置+ description: 更新后的配置schema:additionalProperties: truetype: object@@ -12646,30 +12660,31 @@ paths:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'security:- Bearer: []- summary: 获取租户 API Key 用户身份配置+ summary: 更新租户 API Key 用户身份配置tags:- 租户管理- put:+ /tenants/{id}/api-principal-test-token:+ post:consumes:- application/json- description: 配置 X-API-Key 请求如何映射为终端 Principal(Owner)+ description: 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)parameters:- description: 租户IDin: pathname: idrequired: truetype: integer- - description: API principal 配置+ - description: 测试 Token 参数in: bodyname: requestrequired: trueschema:- $ref: '#/definitions/internal_handler.apiPrincipalConfigRequest'+ $ref: '#/definitions/internal_handler.apiPrincipalTestTokenRequest'produces:- application/jsonresponses:"200":- description: 更新后的配置+ description: 短期 JWTschema:additionalProperties: truetype: object@@ -12683,7 +12698,7 @@ paths:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'security:- Bearer: []- summary: 更新租户 API Key 用户身份配置+ summary: 生成 API Playground 测试 JWTtags:- 租户管理/tenants/{id}/audit-log:diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.tsindex 1984ed5c7..09431ec42 100644--- a/frontend/src/api/tenant/index.ts+++ b/frontend/src/api/tenant/index.ts@@ -108,23 +108,6 @@ export async function listAllTenants(): Promise<{ success: boolean; data?: { ite}}-/**- * 重置租户的 API Key。成功后返回新的明文 Key,旧 Key 立即失效。- */-export async function resetTenantApiKey(- tenantId: string | number,-): Promise<{ success: boolean; data?: { api_key: string }; message?: string }> {- try {- const response = await post(`/api/v1/tenants/${tenantId}/api-key`)- return response as unknown as { success: boolean; data?: { api_key: string }; message?: string }- } catch (error: any) {- return {- success: false,- message: error.message || t('error.tenant.resetApiKeyFailed'),- }- }-}-export async function getAPIPrincipalConfig(tenantId: number,): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 59b49b15c..6d32ed0c1 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3634,7 +3634,6 @@ export default {tenant: {listFailed: 'Failed to list tenants',searchFailed: 'Failed to search tenants',- resetApiKeyFailed: 'Failed to reset API Key',getApiPrincipalConfigFailed: 'Failed to get API principal config',updateApiPrincipalConfigFailed: 'Failed to update API principal config',createApiPrincipalTestTokenFailed: 'Failed to create API test token',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 559fc2b34..b3bfd9b18 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -2642,7 +2642,6 @@ export default {tenant: {listFailed: '테넌트 목록 조회 실패',searchFailed: '테넌트 검색 실패',- resetApiKeyFailed: 'API 키 재설정 실패',getApiPrincipalConfigFailed: 'API principal config 조회 실패',updateApiPrincipalConfigFailed: 'API principal config 업데이트 실패',createApiPrincipalTestTokenFailed: 'API 테스트 토큰 생성 실패',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex e74c0d07e..9f3eec6b8 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2357,7 +2357,6 @@ export default {tenant: {listFailed: 'Не удалось получить список тенантов',searchFailed: 'Не удалось выполнить поиск тенантов',- resetApiKeyFailed: 'Не удалось сбросить API Key',getApiPrincipalConfigFailed: 'Не удалось получить конфигурацию API principal',updateApiPrincipalConfigFailed: 'Не удалось обновить конфигурацию API principal',createApiPrincipalTestTokenFailed: 'Не удалось создать тестовый API Token',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 79ed126fe..1306688be 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -2652,7 +2652,6 @@ export default {tenant: {listFailed: "获取空间列表失败",searchFailed: "搜索空间失败",- resetApiKeyFailed: "重置 API Key 失败",getApiPrincipalConfigFailed: "获取 API 用户身份配置失败",updateApiPrincipalConfigFailed: "更新 API 用户身份配置失败",createApiPrincipalTestTokenFailed: "生成 API 测试 Token 失败",diff --git a/internal/application/repository/tenant_api_key.go b/internal/application/repository/tenant_api_key.goindex 64db04f32..c6b7b5c05 100644--- a/internal/application/repository/tenant_api_key.go+++ b/internal/application/repository/tenant_api_key.go@@ -62,14 +62,6 @@ func (r *tenantAPIKeyRepository) RevokeAPIKey(ctx context.Context, tenantID uintreturn nil}-func (r *tenantAPIKeyRepository) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {- now := time.Now()- return r.db.WithContext(ctx).- Model(&types.TenantAPIKey{}).- Where("tenant_id = ? AND revoked_at IS NULL", tenantID).- Update("revoked_at", &now).Error-}-func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error {return r.db.WithContext(ctx).Model(&types.TenantAPIKey{}).@@ -83,6 +75,23 @@ func (r *tenantAPIKeyRepository) UpdateAPIKeyHash(ctx context.Context, id uint64// key_hash is not the real SHA-256 of the API key yet.const placeholderKeyHashPrefix = "migrated-tenant-"+func (r *tenantAPIKeyRepository) HasKeysWithPlaceholderHash(ctx context.Context) (bool, error) {+ var id uint64+ err := r.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).+ Model(&types.TenantAPIKey{}).+ Select("id").+ Where("key_hash LIKE ? AND revoked_at IS NULL", placeholderKeyHashPrefix+"%").+ Limit(1).+ Scan(&id).Error+ if err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return false, nil+ }+ return false, err+ }+ return id != 0, nil+}+func (r *tenantAPIKeyRepository) ListKeysWithPlaceholderHash(ctx context.Context,) ([]*types.TenantAPIKey, error) {diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.goindex 67749f8e4..d72cb8226 100644--- a/internal/application/service/tenant.go+++ b/internal/application/service/tenant.go@@ -2,13 +2,7 @@ package serviceimport ("context"- "crypto/aes"- "crypto/cipher"- "encoding/base64"- "encoding/binary""errors"- "os"- "strings""time"werrors "github.com/Tencent/WeKnora/internal/errors"@@ -17,10 +11,6 @@ import ("github.com/Tencent/WeKnora/internal/types/interfaces")-var apiKeySecret = func() []byte {- return []byte(os.Getenv("TENANT_AES_KEY"))-}-// ListTenantsParams defines parameters for listing tenants with filtering and paginationtype ListTenantsParams struct {Page int // Page number for pagination@@ -178,48 +168,6 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {return nil}-// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key-func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {- // 1. Validate format and extract encrypted part- parts := strings.SplitN(apiKey, "-", 2)- if len(parts) != 2 || parts[0] != "sk" {- return 0, errors.New("invalid API key format")- }-- // 2. Decode the base64 part- encryptedData, err := base64.RawURLEncoding.DecodeString(parts[1])- if err != nil {- return 0, errors.New("invalid API key encoding")- }-- // 3. Separate nonce and ciphertext- if len(encryptedData) < 12 {- return 0, errors.New("invalid API key length")- }- nonce, ciphertext := encryptedData[:12], encryptedData[12:]-- // 4. Decrypt- block, err := aes.NewCipher(apiKeySecret())- if err != nil {- return 0, errors.New("decryption error")- }-- aesgcm, err := cipher.NewGCM(block)- if err != nil {- return 0, errors.New("decryption error")- }-- plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)- if err != nil {- return 0, errors.New("API key is invalid or has been tampered with")- }-- // 5. Convert back to tenant_id- tenantID := binary.LittleEndian.Uint64(plaintext)-- return tenantID, nil-}-// ListAllTenants lists all tenants (for users with cross-tenant access permission)// This method returns all tenants without filtering, intended for admin usersfunc (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {diff --git a/internal/application/service/tenant_api_key.go b/internal/application/service/tenant_api_key.goindex 244b103ba..fe35b5c40 100644--- a/internal/application/service/tenant_api_key.go+++ b/internal/application/service/tenant_api_key.go@@ -4,7 +4,6 @@ import ("context""crypto/rand""crypto/sha256"- "crypto/subtle""encoding/base64""encoding/hex""errors"@@ -75,66 +74,22 @@ func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token strireturn key, nil}-func (s *tenantAPIKeyService) AuthenticateTenantAPIKey(- ctx context.Context, tenantID uint64, token string,-) (*types.TenantAPIKey, error) {- token = strings.TrimSpace(token)- if tenantID == 0 || token == "" {- return nil, apprepo.ErrTenantAPIKeyNotFound- }- if key, err := s.AuthenticateAPIKey(ctx, token); err == nil && key != nil {- if key.TenantID != tenantID {- return nil, apprepo.ErrTenantAPIKeyNotFound- }- return key, nil- } else if err != nil && !errors.Is(err, apprepo.ErrTenantAPIKeyNotFound) {- return nil, err- }- keys, err := s.repo.ListAPIKeys(ctx, tenantID)- if err != nil {- return nil, err- }- for _, key := range keys {- if key == nil || subtle.ConstantTimeCompare([]byte(key.APIKey), []byte(token)) != 1 {- continue- }- if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) {- return nil, apprepo.ErrTenantAPIKeyNotFound- }- if err := s.ensureAPIKeyHash(ctx, key); err != nil {- return nil, err- }- _ = s.repo.UpdateAPIKeyLastUsed(ctx, key.ID, time.Now())- return key, nil- }- return nil, apprepo.ErrTenantAPIKeyNotFound-}-func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {- keys, err := s.repo.ListAPIKeys(ctx, tenantID)- if err != nil {- return nil, err- }- for _, key := range keys {- if err := s.ensureAPIKeyHash(ctx, key); err != nil {- return nil, err- }- }- return keys, nil+ return s.repo.ListAPIKeys(ctx, tenantID)}func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error {return s.repo.RevokeAPIKey(ctx, tenantID, id)}-func (s *tenantAPIKeyService) RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error {- if tenantID == 0 {- return nil- }- return s.repo.RevokeAllAPIKeys(ctx, tenantID)-}-func (s *tenantAPIKeyService) BackfillMissingKeyHashes(ctx context.Context) (int, error) {+ has, err := s.repo.HasKeysWithPlaceholderHash(ctx)+ if err != nil {+ return 0, err+ }+ if !has {+ return 0, nil+ }keys, err := s.repo.ListKeysWithPlaceholderHash(ctx)if err != nil {return 0, err@@ -169,21 +124,6 @@ func hashTenantAPIKey(token string) string {return hex.EncodeToString(sum[:])}-func (s *tenantAPIKeyService) ensureAPIKeyHash(ctx context.Context, key *types.TenantAPIKey) error {- if key == nil || strings.TrimSpace(key.APIKey) == "" {- return nil- }- hash := hashTenantAPIKey(key.APIKey)- if key.KeyHash == hash {- return nil- }- if err := s.repo.UpdateAPIKeyHash(ctx, key.ID, hash); err != nil {- return err- }- key.KeyHash = hash- return nil-}-func normalizeAPIKeyIDs(in []string) types.StringArray {out := types.StringArray{}seen := map[string]struct{}{}diff --git a/internal/application/service/tenant_api_key_test.go b/internal/application/service/tenant_api_key_test.goindex a9650830c..132eeadb5 100644--- a/internal/application/service/tenant_api_key_test.go+++ b/internal/application/service/tenant_api_key_test.go@@ -85,16 +85,6 @@ func (r *fakeTenantAPIKeyRepo) RevokeAPIKey(_ context.Context, tenantID uint64,return apprepo.ErrTenantAPIKeyNotFound}-func (r *fakeTenantAPIKeyRepo) RevokeAllAPIKeys(_ context.Context, tenantID uint64) error {- now := time.Now()- for _, key := range r.byHash {- if key.TenantID == tenantID && key.RevokedAt == nil {- key.RevokedAt = &now- }- }- return nil-}-func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, hash string) error {for oldHash, key := range r.byHash {if key.ID == id && key.RevokedAt == nil {@@ -107,6 +97,15 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyHash(_ context.Context, id uint64, hareturn apprepo.ErrTenantAPIKeyNotFound}+func (r *fakeTenantAPIKeyRepo) HasKeysWithPlaceholderHash(_ context.Context) (bool, error) {+ for _, key := range r.byHash {+ if key.RevokedAt == nil && strings.HasPrefix(key.KeyHash, "migrated-tenant-") {+ return true, nil+ }+ }+ return false, nil+}+func (r *fakeTenantAPIKeyRepo) ListKeysWithPlaceholderHash(_ context.Context) ([]*types.TenantAPIKey, error) {out := []*types.TenantAPIKey{}for _, key := range r.byHash {@@ -127,33 +126,6 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64return nil}-func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testing.T) {- ctx := context.Background()- repo := newFakeTenantAPIKeyRepo()- svc := NewTenantAPIKeyService(repo)- token := "sk-42-migrated-secret-value"- key := &types.TenantAPIKey{- TenantID: 42,- Name: "Tenant API key",- KeyHash: "migrated-tenant-42",- APIKey: token,- Role: types.TenantRoleAdmin,- }- if err := repo.CreateAPIKey(ctx, key); err != nil {- t.Fatalf("CreateAPIKey returned error: %v", err)- }- got, err := svc.AuthenticateTenantAPIKey(ctx, 42, token)- if err != nil {- t.Fatalf("AuthenticateTenantAPIKey returned error: %v", err)- }- if got.KeyHash != hashTenantAPIKey(token) {- t.Fatalf("repaired hash = %q, want %q", got.KeyHash, hashTenantAPIKey(token))- }- if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {- t.Fatalf("AuthenticateAPIKey after repair returned error: %v", err)- }-}-func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {ctx := context.Background()repo := newFakeTenantAPIKeyRepo()@@ -165,7 +137,7 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {Name: "legacy",KeyHash: "migrated-tenant-7",APIKey: token,- Role: types.TenantRoleAdmin,+ Role: types.TenantRoleOwner,}if err := repo.CreateAPIKey(ctx, legacy); err != nil {t.Fatalf("CreateAPIKey returned error: %v", err)@@ -178,52 +150,31 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {if n != 1 {t.Fatalf("backfilled = %d, want 1", n)}- // After backfill the key authenticates via the fast hash path.if _, err := svc.AuthenticateAPIKey(ctx, token); err != nil {t.Fatalf("AuthenticateAPIKey after backfill returned error: %v", err)}- // Idempotent: a second run finds nothing to do.if n, err := svc.BackfillMissingKeyHashes(ctx); err != nil || n != 0 {t.Fatalf("second BackfillMissingKeyHashes = (%d, %v), want (0, nil)", n, err)}}-func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {+func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {ctx := context.Background()repo := newFakeTenantAPIKeyRepo()svc := NewTenantAPIKeyService(repo)- first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{+ created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{TenantID: 42,- Name: "first",- Role: types.TenantRoleViewer,- })- if err != nil {- t.Fatalf("CreateAPIKey first returned error: %v", err)- }- second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{- TenantID: 42,- Name: "second",+ Name: "integration",Role: types.TenantRoleViewer,})if err != nil {- t.Fatalf("CreateAPIKey second returned error: %v", err)- }-- if err := svc.RevokeAllAPIKeys(ctx, 42); err != nil {- t.Fatalf("RevokeAllAPIKeys returned error: %v", err)- }- if _, err := svc.AuthenticateAPIKey(ctx, first.Token); err == nil {- t.Fatal("first key should be revoked")- }- if _, err := svc.AuthenticateAPIKey(ctx, second.Token); err == nil {- t.Fatal("second key should be revoked")+ t.Fatalf("CreateAPIKey returned error: %v", err)}- keys, err := svc.ListAPIKeys(ctx, 42)- if err != nil {- t.Fatalf("ListAPIKeys returned error: %v", err)+ if err := svc.RevokeAPIKey(ctx, 42, created.APIKey.ID); err != nil {+ t.Fatalf("RevokeAPIKey returned error: %v", err)}- if len(keys) != 0 {- t.Fatalf("active keys count = %d, want 0", len(keys))+ if _, err := svc.AuthenticateAPIKey(ctx, created.Token); err == nil {+ t.Fatal("revoked key should not authenticate")}}diff --git a/internal/handler/embed_flow_test.go b/internal/handler/embed_flow_test.goindex d520f2773..c94e53c87 100644--- a/internal/handler/embed_flow_test.go+++ b/internal/handler/embed_flow_test.go@@ -104,7 +104,6 @@ func (f *flowTenantSvc) DeleteTenant(context.Context, uint64) error { return nilfunc (f *flowTenantSvc) ListTenants(context.Context) ([]*types.Tenant, error) {return nil, nil}-func (f *flowTenantSvc) ExtractTenantIDFromAPIKey(string) (uint64, error) { return 0, nil }func (f *flowTenantSvc) ListAllTenants(context.Context) ([]*types.Tenant, error) {return nil, nil}diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex 88516195f..bc721932f 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -93,8 +93,8 @@ type createTenantRequest struct {// fields an Owner is permitted to mutate via the public API are bound;// everything else (storage_quota, status, business, api_key, agent /// retrieval / storage configs, ...) is intentionally NOT writable here-// — those go through dedicated endpoints (POST /:id/api-key,-// PUT /tenants/kv/:key, ...) that have their own validation.+// — those go through dedicated endpoints (PUT /tenants/kv/:key, ...)+// that have their own validation.//// Pointers so we can distinguish "not sent" from "explicit empty// string"; when nil we leave the existing column untouched.@@ -477,7 +477,7 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {// Strict whitelist: only Name / Description are mutable through the// public PUT. Storage quota, status, business, configs, api_key and// every other privileged column live behind dedicated endpoints- // (POST /:id/api-key, PUT /tenants/kv/:key, ...). Without this, an+ // (PUT /tenants/kv/:key, ...). Without this, an// Owner — including any user who just self-served a tenant — could// flip status / bump storage_quota by simply crafting an extended// JSON body. Pointers distinguish "field omitted" from "explicit@@ -541,63 +541,6 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {})}-// ResetAPIKey godoc-// @Summary 重置租户 API Key-// @Description 吊销该租户全部现有 API Key 后创建一把新的全权限 Key-// @Tags 租户管理-// @Accept json-// @Produce json-// @Param id path int true "租户ID"-// @Success 200 {object} map[string]interface{} "新生成的 API Key"-// @Failure 400 {object} errors.AppError "请求参数错误"-// @Failure 403 {object} errors.AppError "权限不足"-// @Security Bearer-// @Router /tenants/{id}/api-key [post]-func (h *TenantHandler) ResetAPIKey(c *gin.Context) {- ctx := c.Request.Context()-- id, err := strconv.ParseUint(c.Param("id"), 10, 64)- if err != nil {- logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))- c.Error(errors.NewBadRequestError("Invalid tenant ID"))- return- }-- logger.Infof(ctx, "Resetting API key for tenant, ID: %d", id)- if h.apiKeyService == nil {- c.Error(errors.NewInternalServerError("API key service is not configured"))- return- }- if err := h.apiKeyService.RevokeAllAPIKeys(ctx, id); err != nil {- logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": id})- c.Error(errors.NewInternalServerError("Failed to reset API key").WithDetails(err.Error()))- return- }- result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{- TenantID: id,- Name: "Tenant API key",- Role: types.TenantRoleOwner,- })- if err != nil {- if appErr, ok := errors.IsAppError(err); ok {- logger.Error(ctx, "Failed to reset API key: application error", appErr)- c.Error(appErr)- } else {- logger.ErrorWithFields(ctx, err, nil)- c.Error(errors.NewInternalServerError("Failed to reset API key").WithDetails(err.Error()))- }- return- }-- logger.Infof(ctx, "API key reset successfully, tenant ID: %d", id)- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": gin.H{- "api_key": result.APIKey.APIKey,- },- })-}-func (h *TenantHandler) ListAPIKeys(c *gin.Context) {ctx := c.Request.Context()id, err := strconv.ParseUint(c.Param("id"), 10, 64)diff --git a/internal/handler/tenant_secret_disclosure_test.go b/internal/handler/tenant_secret_disclosure_test.goindex 3c93c2b3a..d4e022943 100644--- a/internal/handler/tenant_secret_disclosure_test.go+++ b/internal/handler/tenant_secret_disclosure_test.go@@ -43,7 +43,6 @@ func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, erfunc (s *stubTenantService) SearchTenants(context.Context, string, uint64, int, int) ([]*types.Tenant, int64, error) {return nil, 0, nil}-func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { return 0, nil }func (s *stubTenantService) BulkSetStorageQuota(context.Context, int64) (int64, error) {return 0, nil}diff --git a/internal/middleware/access.go b/internal/middleware/access.goindex 07e5154b8..a3e67a317 100644--- a/internal/middleware/access.go+++ b/internal/middleware/access.go@@ -144,7 +144,7 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {// auth middleware.//// The router places this on the /tenants/:id group so every per-tenant-// endpoint (GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey /+// endpoint (GetTenant / UpdateTenant / DeleteTenant /// member management / leave) shares the same check, replacing what was// previously a copy-pasted block in each handler.//diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex a6612f982..460ed640d 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -237,26 +237,16 @@ func authenticateAPIKeyRequest(apiKey string,) bool {ctx := c.Request.Context()- var key *types.TenantAPIKey- var tenantID uint64-- if authenticated, err := apiKeyService.AuthenticateAPIKey(ctx, apiKey); err == nil && authenticated != nil {- key = authenticated- tenantID = key.TenantID- } else if tenantIDFromKey, extractErr := tenantService.ExtractTenantIDFromAPIKey(apiKey); extractErr == nil {- if authenticated, err := apiKeyService.AuthenticateTenantAPIKey(ctx, tenantIDFromKey, apiKey); err == nil && authenticated != nil {- key = authenticated- tenantID = tenantIDFromKey- }- }-- if key == nil {+ // AuthenticateAPIKey resolves the key by SHA-256 hash (see startup+ // BackfillMissingKeyHashes for migration 000065 placeholder rows).+ key, err := apiKeyService.AuthenticateAPIKey(ctx, apiKey)+ if err != nil || key == nil {c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"})c.Abort()return false}- attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key)+ attachAPIKeyAuthContext(c, tenantService, userService, key.TenantID, key)if c.IsAborted() {return false}diff --git a/internal/middleware/embed_auth_test.go b/internal/middleware/embed_auth_test.goindex f4c25f588..8b45b6023 100644--- a/internal/middleware/embed_auth_test.go+++ b/internal/middleware/embed_auth_test.go@@ -161,10 +161,6 @@ func (f *fakeTenantService) ListTenants(ctx context.Context) ([]*types.Tenant, ereturn nil, nil}-func (f *fakeTenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {- return 0, nil-}-func (f *fakeTenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, error) {return nil, nil}diff --git a/internal/router/rbac.go b/internal/router/rbac.goindex 2379f8f32..0e9b02c5f 100644--- a/internal/router/rbac.go+++ b/internal/router/rbac.go@@ -426,7 +426,7 @@ func (g *rbacGuards) CrossTenant() gin.HandlerFunc {// PathTenantMatch enforces that the URL :id matches the caller's// active tenant context (cross-tenant superusers bypass). Routes apply// it at the /tenants/:id group level so every per-tenant endpoint —-// GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey / member+// GetTenant / UpdateTenant / DeleteTenant / member// management / leave — shares the same check. Replaces the// authorizeTenantAccess helper that used to live inside the tenant// handler.diff --git a/internal/router/router.go b/internal/router/router.goindex 0b982eba5..365c1704c 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -527,7 +527,7 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGua// - GET /:id Viewer+ (read tenant settings)// - PUT /:id Owner+ (mutate tenant config)// - DELETE /:id Owner+ (also normally a CanAccessAllTenants op)-// - POST /:id/api-key Owner+ (rotating the tenant API key is sensitive)+// - GET/POST/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)@@ -596,7 +596,6 @@ func RegisterTenantRoutes(tenantByID.GET("", g.Viewer(), handler.GetTenant)tenantByID.PUT("", g.Owner(), handler.UpdateTenant)tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)- tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)tenantByID.GET("/api-keys", g.Owner(), handler.ListAPIKeys)tenantByID.POST("/api-keys", g.Owner(), handler.CreateAPIKey)tenantByID.DELETE("/api-keys/:key_id", g.Owner(), handler.DeleteAPIKey)diff --git a/internal/router/router_api_key_management_test.go b/internal/router/router_api_key_management_test.goindex d9dac814a..fc71bd232 100644--- a/internal/router/router_api_key_management_test.go+++ b/internal/router/router_api_key_management_test.go@@ -29,7 +29,6 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {v1 := engine.Group("/api/v1")tenantByID := v1.Group("/tenants/:id"){- tenantByID.POST("/api-key", reachedOK)tenantByID.GET("/api-keys", reachedOK)tenantByID.POST("/api-keys", reachedOK)tenantByID.DELETE("/api-keys/:key_id", reachedOK)@@ -46,7 +45,6 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {method stringpath string}{- {http.MethodPost, "/api/v1/tenants/42/api-key"},{http.MethodGet, "/api/v1/tenants/42/api-keys"},{http.MethodPost, "/api/v1/tenants/42/api-keys"},{http.MethodDelete, "/api/v1/tenants/42/api-keys/7"},diff --git a/internal/router/router_presigned_test.go b/internal/router/router_presigned_test.goindex b88e51702..b356ac851 100644--- a/internal/router/router_presigned_test.go+++ b/internal/router/router_presigned_test.go@@ -51,7 +51,6 @@ func (s *stubTenantService) UpdateTenant(context.Context, *types.Tenant) (*typespanic("unexpected")}func (s *stubTenantService) DeleteTenant(context.Context, uint64) error { panic("unexpected") }-func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { panic("unexpected") }func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, error) {panic("unexpected")}diff --git a/internal/types/interfaces/tenant.go b/internal/types/interfaces/tenant.goindex 63d6222c0..ee5c0d3c6 100644--- a/internal/types/interfaces/tenant.go+++ b/internal/types/interfaces/tenant.go@@ -23,8 +23,6 @@ type TenantService interface {UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error)// DeleteTenant deletes a tenantDeleteTenant(ctx context.Context, id uint64) error- // ExtractTenantIDFromAPIKey extracts the tenant ID from the API key- ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)// ListAllTenants lists all tenants (for users with cross-tenant access permission)ListAllTenants(ctx context.Context) ([]*types.Tenant, error)// BulkSetStorageQuota overwrites every tenant's storage_quota with@@ -82,25 +80,24 @@ type TenantAPIKeyRepository interface {GetAPIKeyByHash(ctx context.Context, hash string) (*types.TenantAPIKey, error)ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error- RevokeAllAPIKeys(ctx context.Context, tenantID uint64) errorUpdateAPIKeyHash(ctx context.Context, id uint64, hash string) errorUpdateAPIKeyLastUsed(ctx context.Context, id uint64, at time.Time) error// ListKeysWithPlaceholderHash returns keys whose key_hash is still the// migration placeholder (never authenticated since the 000065 upgrade),// so the real SHA-256 hash can be computed and backfilled.ListKeysWithPlaceholderHash(ctx context.Context) ([]*types.TenantAPIKey, error)+ // HasKeysWithPlaceholderHash is a cheap existence probe used at startup+ // to skip loading/decrypting api_key rows once backfill is complete.+ HasKeysWithPlaceholderHash(ctx context.Context) (bool, error)}type TenantAPIKeyService interface {CreateAPIKey(ctx context.Context, req TenantAPIKeyCreateRequest) (*TenantAPIKeyCreateResult, error)AuthenticateAPIKey(ctx context.Context, token string) (*types.TenantAPIKey, error)- AuthenticateTenantAPIKey(ctx context.Context, tenantID uint64, token string) (*types.TenantAPIKey, error)ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error)RevokeAPIKey(ctx context.Context, tenantID uint64, id uint64) error- RevokeAllAPIKeys(ctx context.Context, tenantID uint64) error// BackfillMissingKeyHashes computes and persists the SHA-256 key_hash- // for legacy keys still carrying the migration placeholder, so their- // first authentication does not fall back to an O(n) plaintext scan.+ // for legacy keys still carrying the migration placeholder.// Returns the number of keys backfilled.BackfillMissingKeyHashes(ctx context.Context) (int, error)}