diff --git a/docs/api/tenant.md b/docs/api/tenant.md index f9973d9c..48aec20f 100644 --- a/docs/api/tenant.md +++ b/docs/api/tenant.md @@ -15,7 +15,10 @@ | GET | `/tenants/:id` | 获取指定租户信息 | | PUT | `/tenants/:id` | 更新租户信息 | | DELETE | `/tenants/:id` | 删除租户 | -| POST | `/tenants/:id/api-key` | 重置租户 API Key | +| POST | `/tenants/:id/api-key` | 重置租户 API Key(吊销该租户全部旧 Key 后创建一把新的全权限 Key) | +| GET | `/tenants/:id/api-keys` | 列出租户 API Key(Owner) | +| POST | `/tenants/:id/api-keys` | 创建带 scope 的 API Key(Owner) | +| DELETE | `/tenants/:id/api-keys/:key_id` | 吊销指定 API Key(Owner) | | GET | `/tenants/:id/api-principal-config` | 获取 API Key 用户身份配置(Owner) | | PUT | `/tenants/:id/api-principal-config` | 更新 API Key 用户身份配置(Owner) | | GET | `/tenants` | 获取当前用户可见的租户列表 | @@ -108,7 +111,7 @@ curl --location 'http://localhost:8080/api/v1/tenants/search?keyword=weknora&pag ## POST `/tenants` - 创建新租户 -创建一个新的租户,服务端会自动生成租户 ID 与 API Key。 +创建一个新的租户。**不会**自动发放 API Key;请在创建后通过 `POST /tenants/:id/api-keys` 或 `POST /tenants/:id/api-key` 获取密钥。从旧版本升级时,原有 `tenants.api_key` 会迁移到 `tenant_api_keys` 表并继续可用,直至被吊销。 **参数说明(请求体)**: @@ -329,7 +332,7 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/tenants/10000' \ ## POST `/tenants/:id/api-key` - 重置租户 API Key -为指定租户生成新的 API Key,旧 Key 立即失效。访问规则同 `GET /tenants/:id`。 +为指定租户生成新的 API Key,并**吊销该租户下所有现有 Key**(含迁移进来的旧 Key)。新 Key 拥有 `read` + `write` + `admin` 全权限。访问规则同 `GET /tenants/:id`。 **路径参数**: @@ -356,6 +359,17 @@ curl --location --request POST 'http://localhost:8080/api/v1/tenants/10000/api-k } ``` +## 租户 API Key 管理(`tenant_api_keys`) + +自 scoped API Key 改造后,密钥以独立记录存储,支持: + +- **scopes**:`read`(只读 + 语义检索 POST)、`write`(知识库写入)、`admin`(租户级管理,不含 `/api-keys` 管理面) +- **knowledge_base_ids**:可选,将 Key 限制在指定知识库 +- **吊销**:`DELETE /tenants/:id/api-keys/:key_id` +- **过期**:创建时可选 `expires_at_unix` + +认证上下文中的租户角色由 scope 映射:`read` → Viewer,`write` → Contributor,`admin` → Admin。路由级 scope 校验与 KB 访问守卫在 `X-API-Key` 认证后强制执行。 + ## API Key Principal:隔离边界与安全说明 `api-principal-config` 控制 `X-API-Key` 请求如何映射为终端 **Principal**。请先理解以下边界,再选择模式。 @@ -368,7 +382,7 @@ Principal **仅**用于按终端用户隔离以下能力: - **MCP OAuth** 访问令牌(同一租户下不同外部用户各自授权,token 互不共用) - 对话内 MCP OAuth 提示、MCP 工具审批等与终端用户绑定的流程 -Principal **不会**缩小 API Key 的 API 权限:`X-API-Key` 认证仍授予租户内 **Admin** 角色,知识库、Agent 配置等接口**不按**外部用户做 RBAC 隔离。 +Principal **不会**缩小 API Key 的 HTTP 路由权限:路由访问由 Key 的 `scopes` 控制;租户内 RBAC 角色由 scope 映射为 Viewer / Contributor / Admin。知识库、Agent 等资源的细粒度访问另受 scope 与 KB 守卫约束。 ### 模式与安全假设 diff --git a/internal/application/repository/tenant_api_key.go b/internal/application/repository/tenant_api_key.go index 8687f4e8..760b05a3 100644 --- a/internal/application/repository/tenant_api_key.go +++ b/internal/application/repository/tenant_api_key.go @@ -62,6 +62,14 @@ 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{}). diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.go index 8e149852..67749f8e 100644 --- a/internal/application/service/tenant.go +++ b/internal/application/service/tenant.go @@ -4,11 +4,9 @@ import ( "context" "crypto/aes" "crypto/cipher" - "crypto/rand" "encoding/base64" "encoding/binary" "errors" - "io" "os" "strings" "time" @@ -180,62 +178,6 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error { return nil } -// UpdateAPIKey updates the API key for a specific tenant -func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) { - logger.Info(ctx, "Start updating tenant API Key") - - if id == 0 { - logger.Error(ctx, "Tenant ID cannot be 0") - return "", errors.New("tenant ID cannot be 0") - } - - tenant, err := s.repo.GetTenantByID(ctx, id) - if err != nil { - logger.ErrorWithFields(ctx, err, map[string]interface{}{ - "tenant_id": id, - }) - return "", err - } - - logger.Infof(ctx, "Generating new API Key for tenant, ID: %d", id) - plaintextAPIKey := s.generateApiKey(tenant.ID) - - logger.Infof(ctx, "Tenant API Key generated successfully, ID: %d", id) - return plaintextAPIKey, nil -} - -// generateApiKey generates a secure API key for tenant authentication -func (r *tenantService) generateApiKey(tenantID uint64) string { - // 1. Convert tenant_id to bytes - idBytes := make([]byte, 8) - binary.LittleEndian.PutUint64(idBytes, uint64(tenantID)) - - // 2. Encrypt tenant_id using AES-GCM - block, err := aes.NewCipher(apiKeySecret()) - if err != nil { - panic("Failed to create AES cipher: " + err.Error()) - } - - nonce := make([]byte, 12) - if _, err := io.ReadFull(rand.Reader, nonce); err != nil { - panic(err.Error()) - } - - aesgcm, err := cipher.NewGCM(block) - if err != nil { - panic("Failed to create GCM cipher: " + err.Error()) - } - - ciphertext := aesgcm.Seal(nil, nonce, idBytes, nil) - - // 3. Combine nonce and ciphertext, then encode with base64 - combined := append(nonce, ciphertext...) - encoded := base64.RawURLEncoding.EncodeToString(combined) - - // Create final API Key in format: sk-{encrypted_part} - return "sk-" + encoded -} - // ExtractTenantIDFromAPIKey extracts the tenant ID from an API key func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) { // 1. Validate format and extract encrypted part diff --git a/internal/application/service/tenant_api_key.go b/internal/application/service/tenant_api_key.go index ed8b5f52..47e076d1 100644 --- a/internal/application/service/tenant_api_key.go +++ b/internal/application/service/tenant_api_key.go @@ -110,31 +110,6 @@ func (s *tenantAPIKeyService) AuthenticateTenantAPIKey( return nil, apprepo.ErrTenantAPIKeyNotFound } -func (s *tenantAPIKeyService) EnsureTenantAPIKey(ctx context.Context, tenantID uint64, apiKey string) error { - if tenantID == 0 || strings.TrimSpace(apiKey) == "" { - return nil - } - token := strings.TrimSpace(apiKey) - hash := hashTenantAPIKey(token) - if existing, err := s.repo.GetAPIKeyByHash(ctx, hash); err == nil && existing != nil { - return nil - } else if err != nil && !errors.Is(err, apprepo.ErrTenantAPIKeyNotFound) { - return err - } - key := &types.TenantAPIKey{ - TenantID: tenantID, - Name: "Tenant API key", - KeyHash: hash, - APIKey: token, - Scopes: types.StringArray{ - types.TenantAPIKeyScopeRead, - types.TenantAPIKeyScopeWrite, - types.TenantAPIKeyScopeAdmin, - }, - } - return s.repo.CreateAPIKey(ctx, key) -} - func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) { keys, err := s.repo.ListAPIKeys(ctx, tenantID) if err != nil { @@ -152,6 +127,13 @@ func (s *tenantAPIKeyService) RevokeAPIKey(ctx context.Context, tenantID uint64, 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 generateTenantAPIKeyToken() (string, error) { var b [32]byte if _, err := rand.Read(b[:]); err != nil { diff --git a/internal/application/service/tenant_api_key_test.go b/internal/application/service/tenant_api_key_test.go index e35ac3f0..f443347f 100644 --- a/internal/application/service/tenant_api_key_test.go +++ b/internal/application/service/tenant_api_key_test.go @@ -85,6 +85,16 @@ 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 { @@ -106,32 +116,6 @@ func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64 return nil } -func TestTenantAPIKeyServiceEnsureTenantAPIKeyBackfillsMetadata(t *testing.T) { - ctx := context.Background() - repo := newFakeTenantAPIKeyRepo() - svc := NewTenantAPIKeyService(repo) - token := "sk-42-migrated-secret-value" - - if err := svc.EnsureTenantAPIKey(ctx, 42, token); err != nil { - t.Fatalf("EnsureTenantAPIKey returned error: %v", err) - } - - keys, err := svc.ListAPIKeys(ctx, 42) - if err != nil { - t.Fatalf("ListAPIKeys returned error: %v", err) - } - if len(keys) != 1 { - t.Fatalf("tenant keys count = %d, want 1", len(keys)) - } - key := keys[0] - if key.APIKey != token { - t.Fatalf("tenant key api_key = %q, want %q", key.APIKey, token) - } - if !(types.TenantAPIKeyScope{Scopes: key.Scopes}).HasScope(types.TenantAPIKeyScopeAdmin) { - t.Fatalf("tenant key should include admin scope") - } -} - func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testing.T) { ctx := context.Background() repo := newFakeTenantAPIKeyRepo() @@ -158,3 +142,43 @@ func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testi t.Fatalf("AuthenticateAPIKey after repair returned error: %v", err) } } + +func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) { + ctx := context.Background() + repo := newFakeTenantAPIKeyRepo() + svc := NewTenantAPIKeyService(repo) + + first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{ + TenantID: 42, + Name: "first", + Scopes: []string{types.TenantAPIKeyScopeRead}, + }) + if err != nil { + t.Fatalf("CreateAPIKey first returned error: %v", err) + } + second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{ + TenantID: 42, + Name: "second", + Scopes: []string{types.TenantAPIKeyScopeRead}, + }) + 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") + } + 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)) + } +} diff --git a/internal/handler/embed_flow_test.go b/internal/handler/embed_flow_test.go index abf5b091..d520f277 100644 --- a/internal/handler/embed_flow_test.go +++ b/internal/handler/embed_flow_test.go @@ -104,9 +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) UpdateAPIKey(context.Context, uint64) (string, error) { - return "", 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 fb8ef3cf..41347170 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -537,7 +537,7 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) { // ResetAPIKey godoc // @Summary 重置租户 API Key -// @Description 为指定租户生成一个新的 API Key,旧 Key 立即失效 +// @Description 吊销该租户全部现有 API Key 后创建一把新的全权限 Key // @Tags 租户管理 // @Accept json // @Produce json @@ -562,6 +562,11 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) { 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", diff --git a/internal/handler/tenant_secret_disclosure_test.go b/internal/handler/tenant_secret_disclosure_test.go index de797aa5..3c93c2b3 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) UpdateAPIKey(context.Context, uint64) (string, error) { return "", 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/api_key_scope.go b/internal/middleware/api_key_scope.go index 81c80983..6967d2ed 100644 --- a/internal/middleware/api_key_scope.go +++ b/internal/middleware/api_key_scope.go @@ -11,14 +11,9 @@ import ( var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden") -func authorizeTenantAPIKeyOperation(ctx context.Context, method string) error { - if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok { - return nil - } - return nil -} - -func authorizeTenantAPIKeyRoute(ctx context.Context, method, path string) error { +// authorizeTenantAPIKeyAccess enforces per-key operation and route scopes for +// X-API-Key callers. Non-API-key principals are not restricted. +func authorizeTenantAPIKeyAccess(ctx context.Context, method, path string) error { scope, ok := types.TenantAPIKeyScopeFromContext(ctx) if !ok { return nil @@ -99,22 +94,20 @@ func isKnowledgeScopedUnsafePath(path string) bool { func allowsTenantAPIKeyRead(scope types.TenantAPIKeyScope) bool { scope = scope.Normalize() - return len(scope.Scopes) == 0 || - scope.HasScope(types.TenantAPIKeyScopeRead) || + return scope.HasScope(types.TenantAPIKeyScopeRead) || scope.HasScope(types.TenantAPIKeyScopeWrite) || scope.HasScope(types.TenantAPIKeyScopeAdmin) } func allowsTenantAPIKeyWrite(scope types.TenantAPIKeyScope) bool { scope = scope.Normalize() - return len(scope.Scopes) == 0 || - scope.HasScope(types.TenantAPIKeyScopeWrite) || + return scope.HasScope(types.TenantAPIKeyScopeWrite) || scope.HasScope(types.TenantAPIKeyScopeAdmin) } func allowsTenantAPIKeyAdmin(scope types.TenantAPIKeyScope) bool { scope = scope.Normalize() - return len(scope.Scopes) == 0 || scope.HasScope(types.TenantAPIKeyScopeAdmin) + return scope.HasScope(types.TenantAPIKeyScopeAdmin) } func isTenantAPIKeyReadUnsafePath(method, path string) bool { diff --git a/internal/middleware/api_key_scope_test.go b/internal/middleware/api_key_scope_test.go index 43fdcd90..ad57264e 100644 --- a/internal/middleware/api_key_scope_test.go +++ b/internal/middleware/api_key_scope_test.go @@ -14,10 +14,10 @@ func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeRead}, }) - if err := authorizeTenantAPIKeyOperation(ctx, http.MethodGet); err != nil { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil { t.Fatalf("read scoped key should allow GET: %v", err) } - if err := authorizeTenantAPIKeyOperation(ctx, http.MethodHead); err != nil { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil { t.Fatalf("read scoped key should allow HEAD: %v", err) } } @@ -27,9 +27,12 @@ func TestTenantAPIKeyScopeReadOnlyRejectsUnsafeMethods(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeRead}, }) - if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { t.Fatalf("read scoped key POST error = %v, want errTenantAPIKeyScopeForbidden", err) } + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodDelete, "/api/v1/knowledge-bases/kb-1"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { + t.Fatalf("read scoped key DELETE error = %v, want errTenantAPIKeyScopeForbidden", err) + } } func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) { @@ -37,7 +40,7 @@ func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeRead}, }) - if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil { t.Fatalf("read scoped key should allow semantic read POST: %v", err) } } @@ -60,7 +63,7 @@ func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin}, }) - err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/tenants/1/api-keys") + err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/tenants/1/api-keys") if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { t.Fatalf("api key management error = %v, want errTenantAPIKeyScopeForbidden", err) } @@ -72,7 +75,7 @@ func TestTenantAPIKeyRouteRejectsTenantWriteForKnowledgeRestrictedKey(t *testing KnowledgeBaseIDs: types.StringArray{"kb-1"}, }) - err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/kv/theme") + err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme") if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err) } @@ -83,7 +86,7 @@ func TestTenantAPIKeyRouteRejectsTenantWriteForWriteScope(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeWrite}, }) - err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/1") + err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/1") if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err) } @@ -94,7 +97,7 @@ func TestTenantAPIKeyRouteAllowsTenantWriteForAdminScope(t *testing.T) { Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin}, }) - if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); err != nil { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); err != nil { t.Fatalf("admin scoped key should allow tenant management route: %v", err) } } @@ -105,7 +108,7 @@ func TestTenantAPIKeyRouteAllowsKnowledgeWriteForKnowledgeRestrictedKey(t *testi KnowledgeBaseIDs: types.StringArray{"kb-1"}, }) - if err := authorizeTenantAPIKeyRoute(ctx, http.MethodPut, "/api/v1/knowledge-bases/kb-1"); err != nil { + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/knowledge-bases/kb-1"); err != nil { t.Fatalf("scoped knowledge write should pass route layer: %v", err) } } @@ -116,8 +119,21 @@ func TestTenantAPIKeyRouteRejectsCrossKnowledgeBatchWriteForKnowledgeRestrictedK KnowledgeBaseIDs: types.StringArray{"kb-1"}, }) - err := authorizeTenantAPIKeyRoute(ctx, http.MethodPost, "/api/v1/knowledge/batch-delete") + err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge/batch-delete") if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { t.Fatalf("batch write error = %v, want errTenantAPIKeyScopeForbidden", err) } } + +func TestTenantAPIKeyScopeEmptyScopesDefaultToReadOnly(t *testing.T) { + ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + Scopes: types.StringArray{}, + }) + + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { + t.Fatalf("empty scopes should default to read-only, got %v", err) + } + if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil { + t.Fatalf("empty scopes should allow GET: %v", err) + } +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index 27513a2b..3e4ee926 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -212,54 +212,9 @@ func Auth( apiKey := c.GetHeader("X-API-Key") if apiKey != "" { if apiKeyService != nil { - if key, err := apiKeyService.AuthenticateAPIKey(c.Request.Context(), apiKey); err == nil && key != nil { - attachAPIKeyAuthContext(c, tenantService, userService, key.TenantID, key) - if c.IsAborted() { - return - } - if err := authorizeTenantAPIKeyOperation(c.Request.Context(), c.Request.Method); err != nil { - c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"}) - c.Abort() - return - } - if err := authorizeTenantAPIKeyRoute(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil { - c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this route"}) - c.Abort() - return - } + if authenticateAPIKeyRequest(c, tenantService, userService, apiKeyService, apiKey) { c.Next() - return } - tenantID, err := tenantService.ExtractTenantIDFromAPIKey(apiKey) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{ - "error": "Unauthorized: invalid API key format", - }) - c.Abort() - return - } - if key, err := apiKeyService.AuthenticateTenantAPIKey( - c.Request.Context(), tenantID, apiKey, - ); err == nil && key != nil { - attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key) - if c.IsAborted() { - return - } - if err := authorizeTenantAPIKeyOperation(c.Request.Context(), c.Request.Method); err != nil { - c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"}) - c.Abort() - return - } - if err := authorizeTenantAPIKeyRoute(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil { - c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this route"}) - c.Abort() - return - } - c.Next() - return - } - c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"}) - c.Abort() return } @@ -274,6 +229,45 @@ func Auth( } } +func authenticateAPIKeyRequest( + c *gin.Context, + tenantService interfaces.TenantService, + userService interfaces.UserService, + apiKeyService interfaces.TenantAPIKeyService, + 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 { + c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid API key"}) + c.Abort() + return false + } + + attachAPIKeyAuthContext(c, tenantService, userService, tenantID, key) + if c.IsAborted() { + return false + } + if err := authorizeTenantAPIKeyAccess(ctx, c.Request.Method, c.Request.URL.Path); err != nil { + c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"}) + c.Abort() + return false + } + return true +} + func attachAPIKeyAuthContext( c *gin.Context, tenantService interfaces.TenantService, @@ -317,12 +311,19 @@ func attachAPIKeyAuthContext( return } c.Set(types.PrincipalContextKey.String(), principal) - c.Set(types.TenantRoleContextKey.String(), types.TenantRoleAdmin) + apiKeyRole := types.TenantRoleViewer + if key != nil { + apiKeyRole = types.TenantAPIKeyScope{ + Scopes: key.Scopes, + KnowledgeBaseIDs: key.KnowledgeBaseIDs, + }.TenantRole() + } + c.Set(types.TenantRoleContextKey.String(), apiKeyRole) c.Set(types.SystemAdminContextKey.String(), false) ctx = context.WithValue(ctx, types.UserContextKey, user) ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID) ctx = types.WithPrincipal(ctx, principal) - ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin) + ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyRole) ctx = context.WithValue(ctx, types.SystemAdminContextKey, false) if key != nil { ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{ diff --git a/internal/middleware/embed_auth_test.go b/internal/middleware/embed_auth_test.go index 84296f60..f4c25f58 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) UpdateAPIKey(ctx context.Context, id uint64) (string, error) { - return "", nil -} - func (f *fakeTenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) { return 0, nil } diff --git a/internal/router/router_presigned_test.go b/internal/router/router_presigned_test.go index 6c4cc857..b88e5170 100644 --- a/internal/router/router_presigned_test.go +++ b/internal/router/router_presigned_test.go @@ -51,9 +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) UpdateAPIKey(context.Context, uint64) (string, 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 50e05758..8fad2aa1 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 - // UpdateAPIKey updates the API key - UpdateAPIKey(ctx context.Context, id uint64) (string, 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) @@ -84,6 +82,7 @@ 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 } @@ -92,7 +91,7 @@ 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) - EnsureTenantAPIKey(ctx context.Context, tenantID uint64, apiKey string) 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 } diff --git a/internal/types/tenant_api_key.go b/internal/types/tenant_api_key.go index 7b55cf1d..21168b1a 100644 --- a/internal/types/tenant_api_key.go +++ b/internal/types/tenant_api_key.go @@ -99,12 +99,18 @@ func (s TenantAPIKeyScope) HasScope(scope string) bool { return false } -func (s TenantAPIKeyScope) AllowsUnsafeOperation() bool { +// TenantRole maps API-key scopes to the tenant RBAC role carried in request +// context. Admin scope -> Admin; write -> Contributor; read-only -> Viewer. +func (s TenantAPIKeyScope) TenantRole() TenantRole { s = s.Normalize() - if len(s.Scopes) == 0 { - return true + switch { + case s.HasScope(TenantAPIKeyScopeAdmin): + return TenantRoleAdmin + case s.HasScope(TenantAPIKeyScopeWrite): + return TenantRoleContributor + default: + return TenantRoleViewer } - return s.HasScope(TenantAPIKeyScopeWrite) || s.HasScope(TenantAPIKeyScopeAdmin) } func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool { @@ -158,6 +164,9 @@ func normalizeScopeArray(in StringArray) StringArray { seen[item] = struct{}{} out = append(out, item) } + if len(out) == 0 { + out = StringArray{TenantAPIKeyScopeRead} + } return out } diff --git a/internal/types/tenant_api_key_test.go b/internal/types/tenant_api_key_test.go new file mode 100644 index 00000000..a0b23d34 --- /dev/null +++ b/internal/types/tenant_api_key_test.go @@ -0,0 +1,31 @@ +package types + +import "testing" + +func TestTenantAPIKeyScopeNormalizeDefaultsEmptyScopesToRead(t *testing.T) { + scope := TenantAPIKeyScope{Scopes: StringArray{}}.Normalize() + if len(scope.Scopes) != 1 || scope.Scopes[0] != TenantAPIKeyScopeRead { + t.Fatalf("normalized scopes = %v, want [read]", scope.Scopes) + } +} + +func TestTenantAPIKeyScopeTenantRoleMapping(t *testing.T) { + tests := []struct { + name string + in StringArray + want TenantRole + }{ + {name: "read", in: StringArray{TenantAPIKeyScopeRead}, want: TenantRoleViewer}, + {name: "write", in: StringArray{TenantAPIKeyScopeWrite}, want: TenantRoleContributor}, + {name: "admin", in: StringArray{TenantAPIKeyScopeAdmin}, want: TenantRoleAdmin}, + {name: "empty defaults read", in: StringArray{}, want: TenantRoleViewer}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := TenantAPIKeyScope{Scopes: tt.in}.TenantRole() + if got != tt.want { + t.Fatalf("TenantRole() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/migrations/versioned/000065_tenant_api_keys.down.sql b/migrations/versioned/000065_tenant_api_keys.down.sql index 4fcc7c1f..c7e144da 100644 --- a/migrations/versioned/000065_tenant_api_keys.down.sql +++ b/migrations/versioned/000065_tenant_api_keys.down.sql @@ -1,5 +1,20 @@ +DO $$ BEGIN RAISE NOTICE '[Migration 000065 down] Restoring tenants.api_key from tenant_api_keys...'; END $$; + ALTER TABLE tenants ADD COLUMN IF NOT EXISTS api_key VARCHAR(256) NOT NULL DEFAULT ''; + +UPDATE tenants t +SET api_key = sub.api_key +FROM ( + SELECT DISTINCT ON (tenant_id) tenant_id, api_key + FROM tenant_api_keys + WHERE revoked_at IS NULL AND COALESCE(api_key, '') <> '' + ORDER BY tenant_id, created_at DESC +) sub +WHERE t.id = sub.tenant_id; + CREATE INDEX IF NOT EXISTS idx_tenants_api_key ON tenants(api_key); DROP INDEX IF EXISTS idx_tenant_api_keys_revoked_at; DROP INDEX IF EXISTS idx_tenant_api_keys_tenant; DROP TABLE IF EXISTS tenant_api_keys; + +DO $$ BEGIN RAISE NOTICE '[Migration 000065 down] tenants.api_key restored'; END $$;