From 97c36f634abe1d6060160522379966b1e565cb30 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 6 Jul 2026 18:27:18 +0800 Subject: [PATCH] refactor(api-keys): remove API key reset endpoint and update documentation Eliminate the POST /tenants/{id}/api-key endpoint for resetting tenant API keys, transitioning to a more granular API key management approach. Update related documentation and API specifications to reflect the new structure, including changes to the tenant API key management paths. Adjust frontend code and internationalization files to remove references to the deprecated API key reset functionality, enhancing clarity and consistency across the application. --- cmd/server/bootstrap.go | 7 +- docs/api/tenant.md | 34 +---- docs/docs.go | 130 ++++++++++-------- docs/swagger.json | 130 ++++++++++-------- docs/swagger.yaml | 89 +++++++----- frontend/src/api/tenant/index.ts | 17 --- frontend/src/i18n/locales/en-US.ts | 1 - frontend/src/i18n/locales/ko-KR.ts | 1 - frontend/src/i18n/locales/ru-RU.ts | 1 - frontend/src/i18n/locales/zh-CN.ts | 1 - .../application/repository/tenant_api_key.go | 25 ++-- internal/application/service/tenant.go | 52 ------- .../application/service/tenant_api_key.go | 76 ++-------- .../service/tenant_api_key_test.go | 85 +++--------- internal/handler/embed_flow_test.go | 1 - internal/handler/tenant.go | 63 +-------- .../handler/tenant_secret_disclosure_test.go | 1 - internal/middleware/access.go | 2 +- internal/middleware/auth.go | 20 +-- internal/middleware/embed_auth_test.go | 4 - internal/router/rbac.go | 2 +- internal/router/router.go | 3 +- .../router/router_api_key_management_test.go | 2 - internal/router/router_presigned_test.go | 1 - internal/types/interfaces/tenant.go | 11 +- 25 files changed, 265 insertions(+), 494 deletions(-) diff --git a/cmd/server/bootstrap.go b/cmd/server/bootstrap.go index b33d9950..47418193 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.md index 36ab2155..86665cd0 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.go index 254275af..02f00b09 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -11957,56 +11957,6 @@ const docTemplate = `{ } } }, - "/tenants/{id}/api-key": { - "post": { - "security": [ - { - "Bearer": [] - } - ], - "description": "为指定租户生成一个新的 API Key,旧 Key 立即失效", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "租户管理" - ], - "summary": "重置租户 API Key", - "parameters": [ - { - "type": "integer", - "description": "租户ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "新生成的 API Key", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "请求参数错误", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "403": { - "description": "权限不足", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/tenants/{id}/api-principal-config": { "get": { "security": [ @@ -12114,6 +12064,65 @@ const docTemplate = `{ } } }, + "/tenants/{id}/api-principal-test-token": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "租户管理" + ], + "summary": "生成 API Playground 测试 JWT", + "parameters": [ + { + "type": "integer", + "description": "租户ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "测试 Token 参数", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/internal_handler.apiPrincipalTestTokenRequest" + } + } + ], + "responses": { + "200": { + "description": "短期 JWT", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "403": { + "description": "权限不足", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/tenants/{id}/audit-log": { "get": { "security": [ @@ -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.json index 165b85f1..3642dcfe 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -11950,56 +11950,6 @@ } } }, - "/tenants/{id}/api-key": { - "post": { - "security": [ - { - "Bearer": [] - } - ], - "description": "为指定租户生成一个新的 API Key,旧 Key 立即失效", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "租户管理" - ], - "summary": "重置租户 API Key", - "parameters": [ - { - "type": "integer", - "description": "租户ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "新生成的 API Key", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "请求参数错误", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "403": { - "description": "权限不足", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/tenants/{id}/api-principal-config": { "get": { "security": [ @@ -12107,6 +12057,65 @@ } } }, + "/tenants/{id}/api-principal-test-token": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "租户管理" + ], + "summary": "生成 API Playground 测试 JWT", + "parameters": [ + { + "type": "integer", + "description": "租户ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "测试 Token 参数", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/internal_handler.apiPrincipalTestTokenRequest" + } + } + ], + "responses": { + "200": { + "description": "短期 JWT", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "403": { + "description": "权限不足", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/tenants/{id}/audit-log": { "get": { "security": [ @@ -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.yaml index d91b3a6b..56931e55 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: integer mcp_selection_mode: description: 'MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP' @@ -2787,8 +2792,8 @@ definitions: type: string user_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: string type: object github_com_Tencent_WeKnora_internal_types.SessionLastRequestState: @@ -3044,9 +3049,6 @@ definitions: type: object github_com_Tencent_WeKnora_internal_types.Tenant: properties: - api_key: - description: API key - type: string business: description: Business type: string @@ -4806,6 +4808,13 @@ definitions: signed_token_header_name: type: string type: object + internal_handler.apiPrincipalTestTokenRequest: + properties: + expires_in_seconds: + type: integer + external_user_id: + type: string + type: object internal_handler.auditLogListResponse: properties: data: @@ -12585,38 +12594,6 @@ paths: summary: 更新租户 tags: - 租户管理 - /tenants/{id}/api-key: - post: - consumes: - - application/json - description: 为指定租户生成一个新的 API Key,旧 Key 立即失效 - parameters: - - description: 租户ID - in: path - name: id - required: true - type: integer - produces: - - application/json - responses: - "200": - description: 新生成的 API Key - schema: - additionalProperties: true - type: object - "400": - description: 请求参数错误 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "403": - description: 权限不足 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - summary: 重置租户 API Key - tags: - - 租户管理 /tenants/{id}/api-principal-config: get: consumes: @@ -12686,6 +12663,44 @@ paths: summary: 更新租户 API Key 用户身份配置 tags: - 租户管理 + /tenants/{id}/api-principal-test-token: + post: + consumes: + - application/json + description: 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner) + parameters: + - description: 租户ID + in: path + name: id + required: true + type: integer + - description: 测试 Token 参数 + in: body + name: request + required: true + schema: + $ref: '#/definitions/internal_handler.apiPrincipalTestTokenRequest' + produces: + - application/json + responses: + "200": + description: 短期 JWT + schema: + additionalProperties: true + type: object + "400": + description: 请求参数错误 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + "403": + description: 权限不足 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + security: + - Bearer: [] + summary: 生成 API Playground 测试 JWT + tags: + - 租户管理 /tenants/{id}/audit-log: get: description: 返回该租户最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。 diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.ts index 1984ed5c..09431ec4 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.ts index 59b49b15..6d32ed0c 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.ts index 559fc2b3..b3bfd9b1 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.ts index e74c0d07..9f3eec6b 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.ts index 79ed126f..1306688b 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.go index 64db04f3..c6b7b5c0 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 uint return 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.go index 67749f8e..d72cb822 100644 --- a/internal/application/service/tenant.go +++ b/internal/application/service/tenant.go @@ -2,13 +2,7 @@ package service import ( "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 pagination type 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 users func (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.go index 244b103b..fe35b5c4 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 stri return 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.go index a9650830..132eeadb 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, ha return 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 uint64 return 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", + Name: "integration", Role: types.TenantRoleViewer, }) if err != nil { - t.Fatalf("CreateAPIKey first returned error: %v", err) + t.Fatalf("CreateAPIKey returned error: %v", err) } - second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{ - TenantID: 42, - Name: "second", - Role: types.TenantRoleViewer, - }) - if err != nil { - t.Fatalf("CreateAPIKey second returned error: %v", err) + if err := svc.RevokeAPIKey(ctx, 42, created.APIKey.ID); err != nil { + t.Fatalf("RevokeAPIKey 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") - } - keys, err := svc.ListAPIKeys(ctx, 42) - if err != nil { - t.Fatalf("ListAPIKeys 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.go index d520f277..c94e53c8 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 nil func (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.go index 88516195..bc721932 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.go index 3c93c2b3..d4e02294 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, er func (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.go index 07e5154b..a3e67a31 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.go index a6612f98..460ed640 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.go index f4c25f58..8b45b602 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, e return 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.go index 2379f8f3..0e9b02c5 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.go index 0b982eba..365c1704 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.go index d9dac814..fc71bd23 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 string path 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.go index b88e5170..b356ac85 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) (*types panic("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.go index 63d6222c..ee5c0d3c 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 tenant DeleteTenant(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) error UpdateAPIKeyHash(ctx context.Context, id uint64, hash string) error UpdateAPIKeyLastUsed(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) }