From fedb6c3f7eda4ceabc792576cb4eb562d16f6c51 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 6 Jul 2026 13:39:02 +0800 Subject: [PATCH] test(api-keys): add tests for tenant API key management path rejection Introduce tests to validate that tenant API keys are correctly restricted from accessing management paths. Implemented new test cases for both allowed and forbidden paths, ensuring proper enforcement of API key scopes. Additionally, refactored existing tests to utilize the new rejection logic. --- internal/middleware/api_key_access.go | 25 +++++ internal/middleware/api_key_access_test.go | 35 ++++++ .../api_key_route_scope_manifest_test.go | 15 ++- internal/middleware/api_key_scope.go | 55 ---------- internal/middleware/api_key_scope_test.go | 101 ------------------ internal/middleware/auth.go | 2 +- .../middleware/auth_api_key_scope_test.go | 14 +-- internal/middleware/kb_access.go | 4 +- 8 files changed, 77 insertions(+), 174 deletions(-) delete mode 100644 internal/middleware/api_key_scope.go delete mode 100644 internal/middleware/api_key_scope_test.go diff --git a/internal/middleware/api_key_access.go b/internal/middleware/api_key_access.go index 859a6f04..896924d9 100644 --- a/internal/middleware/api_key_access.go +++ b/internal/middleware/api_key_access.go @@ -2,6 +2,7 @@ package middleware import ( "context" + stderrors "errors" "net/http" "strings" @@ -9,6 +10,8 @@ import ( "github.com/gin-gonic/gin" ) +var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden") + // isTenantAPIKeyManagementPath reports tenant API-key lifecycle endpoints that // no scoped key may call, regardless of role. func isTenantAPIKeyManagementPath(path string) bool { @@ -21,6 +24,19 @@ func isTenantAPIKeyManagementPath(path string) bool { return strings.HasSuffix(path, "/api-key") } +// rejectTenantAPIKeyManagementPath is a defense-in-depth guard in auth: API keys +// must never reach key-management routes even if a route forgets APIKeyDeny(). +// Role and KB checks are enforced by per-route APIKey* guards and types helpers. +func rejectTenantAPIKeyManagementPath(ctx context.Context, path string) error { + if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok { + return nil + } + if isTenantAPIKeyManagementPath(path) { + return errTenantAPIKeyScopeForbidden + } + return nil +} + // RequireAPIKeyDeny rejects all X-API-Key callers. JWT sessions pass through. func RequireAPIKeyDeny() gin.HandlerFunc { return func(c *gin.Context) { @@ -81,3 +97,12 @@ func requireTenantAPIKeyMinRole(ctx context.Context, minRole types.TenantRole) e } return nil } + +func isSafeHTTPMethod(method string) bool { + switch method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + return true + default: + return false + } +} diff --git a/internal/middleware/api_key_access_test.go b/internal/middleware/api_key_access_test.go index 1bc138a3..bc10a9f1 100644 --- a/internal/middleware/api_key_access_test.go +++ b/internal/middleware/api_key_access_test.go @@ -11,6 +11,31 @@ import ( "github.com/gin-gonic/gin" ) +func TestRejectTenantAPIKeyManagementPath(t *testing.T) { + ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + Role: types.TenantRoleAdmin, + }) + + for _, path := range []string{ + "/api/v1/tenants/1/api-keys", + "/api/v1/tenants/1/api-key", + "/api/v1/tenants/1/api-principal-config", + "/api/v1/tenants/1/api-principal-test-token", + } { + err := rejectTenantAPIKeyManagementPath(ctx, path) + if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { + t.Fatalf("management path %s error = %v, want errTenantAPIKeyScopeForbidden", path, err) + } + } + + if err := rejectTenantAPIKeyManagementPath(ctx, "/api/v1/knowledge-bases"); err != nil { + t.Fatalf("non-management path should pass: %v", err) + } + if err := rejectTenantAPIKeyManagementPath(context.Background(), "/api/v1/tenants/1/api-keys"); err != nil { + t.Fatalf("non-api-key principal should pass: %v", err) + } +} + func TestRequireAPIKeyDenyBlocksAPIKey(t *testing.T) { gin.SetMode(gin.TestMode) ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ @@ -77,3 +102,13 @@ func TestRequireAPIKeyMinRoleEnforcesOnPost(t *testing.T) { t.Fatal("viewer key should pass viewer min role on POST") } } + +func TestRequireAPIKeyMinRoleForUnsafeAllowsContributorKnowledgeWrite(t *testing.T) { + ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + Role: types.TenantRoleContributor, + KnowledgeBaseIDs: types.StringArray{"kb-1"}, + }) + if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil { + t.Fatalf("scoped knowledge write should pass route guard: %v", err) + } +} diff --git a/internal/middleware/api_key_route_scope_manifest_test.go b/internal/middleware/api_key_route_scope_manifest_test.go index 7f502643..d4d264c6 100644 --- a/internal/middleware/api_key_route_scope_manifest_test.go +++ b/internal/middleware/api_key_route_scope_manifest_test.go @@ -24,22 +24,21 @@ func TestTenantAPIKeyRouteScopeManifest(t *testing.T) { baselineCases := []struct { name string ctx context.Context - method string path string allowed bool }{ - {name: "read get kb list", ctx: readCtx, method: http.MethodGet, path: "/api/v1/knowledge-bases", allowed: true}, - {name: "read get wiki page", ctx: readCtx, method: http.MethodGet, path: "/api/v1/knowledgebase/kb-1/wiki/pages", allowed: true}, - {name: "admin reset api key blocked", ctx: adminCtx, method: http.MethodPost, path: "/api/v1/tenants/1/api-key", allowed: false}, - {name: "admin api principal blocked", ctx: adminCtx, method: http.MethodGet, path: "/api/v1/tenants/1/api-principal-config", allowed: false}, + {name: "read get kb list", ctx: readCtx, path: "/api/v1/knowledge-bases", allowed: true}, + {name: "read get wiki page", ctx: readCtx, path: "/api/v1/knowledgebase/kb-1/wiki/pages", allowed: true}, + {name: "admin reset api key blocked", ctx: adminCtx, path: "/api/v1/tenants/1/api-key", allowed: false}, + {name: "admin api principal blocked", ctx: adminCtx, path: "/api/v1/tenants/1/api-principal-config", allowed: false}, } for _, tc := range baselineCases { t.Run("baseline/"+tc.name, func(t *testing.T) { - err := authorizeTenantAPIKeyAccess(tc.ctx, tc.method, tc.path) + err := rejectTenantAPIKeyManagementPath(tc.ctx, tc.path) got := err == nil if got != tc.allowed { - t.Fatalf("authorizeTenantAPIKeyAccess(%s %s) allowed=%v, want %v (err=%v)", - tc.method, tc.path, got, tc.allowed, err) + t.Fatalf("rejectTenantAPIKeyManagementPath(%s) allowed=%v, want %v (err=%v)", + tc.path, got, tc.allowed, err) } }) } diff --git a/internal/middleware/api_key_scope.go b/internal/middleware/api_key_scope.go deleted file mode 100644 index fcb815d7..00000000 --- a/internal/middleware/api_key_scope.go +++ /dev/null @@ -1,55 +0,0 @@ -package middleware - -import ( - "context" - stderrors "errors" - "net/http" - - "github.com/Tencent/WeKnora/internal/types" -) - -var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden") - -// authorizeTenantAPIKeyAccess enforces baseline rules for X-API-Key callers -// before route-level guards run: block key-management paths and require -// Viewer+ for safe reads. Unsafe methods defer to per-route APIKey* guards. -func authorizeTenantAPIKeyAccess(ctx context.Context, method, path string) error { - scope, ok := types.TenantAPIKeyScopeFromContext(ctx) - if !ok { - return nil - } - role := scope.Role - if role == "" { - role = types.TenantRoleViewer - } - if isTenantAPIKeyManagementPath(path) { - return errTenantAPIKeyScopeForbidden - } - if isSafeHTTPMethod(method) { - if role.HasPermission(types.TenantRoleViewer) { - return nil - } - return errTenantAPIKeyScopeForbidden - } - return nil -} - -func authorizeTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error { - scope, ok := types.TenantAPIKeyScopeFromContext(ctx) - if !ok { - return nil - } - if scope.AllowsKnowledgeBase(kbID) { - return nil - } - return errTenantAPIKeyScopeForbidden -} - -func isSafeHTTPMethod(method string) bool { - switch method { - case http.MethodGet, http.MethodHead, http.MethodOptions: - return true - default: - return false - } -} diff --git a/internal/middleware/api_key_scope_test.go b/internal/middleware/api_key_scope_test.go deleted file mode 100644 index 8caf4635..00000000 --- a/internal/middleware/api_key_scope_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package middleware - -import ( - "context" - stderrors "errors" - "net/http" - "testing" - - "github.com/Tencent/WeKnora/internal/types" -) - -func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: types.TenantRoleViewer, - }) - - if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil { - t.Fatalf("viewer key should allow GET: %v", err) - } - if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil { - t.Fatalf("viewer key should allow HEAD: %v", err) - } -} - -func TestTenantAPIKeyScopeBaselineAllowsUnsafeThrough(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: types.TenantRoleViewer, - }) - - if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); err != nil { - t.Fatalf("baseline should defer unsafe checks to route guards: %v", err) - } - if err := authorizeTenantAPIKeyAccess(ctx, http.MethodDelete, "/api/v1/knowledge-bases/kb-1"); err != nil { - t.Fatalf("baseline should defer unsafe checks to route guards: %v", err) - } -} - -func TestTenantAPIKeyScopeAllowsScopedKnowledgeBase(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - KnowledgeBaseIDs: types.StringArray{"kb-1"}, - }) - - if err := authorizeTenantAPIKeyKnowledgeBase(ctx, "kb-1"); err != nil { - t.Fatalf("key scoped to kb-1 should allow kb-1: %v", err) - } - if err := authorizeTenantAPIKeyKnowledgeBase(ctx, "kb-2"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { - t.Fatalf("key scoped to kb-1 should reject kb-2, got %v", err) - } -} - -func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: types.TenantRoleAdmin, - }) - - for _, path := range []string{ - "/api/v1/tenants/1/api-keys", - "/api/v1/tenants/1/api-key", - "/api/v1/tenants/1/api-principal-config", - "/api/v1/tenants/1/api-principal-test-token", - } { - err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, path) - if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) { - t.Fatalf("api key management path %s error = %v, want errTenantAPIKeyScopeForbidden", path, err) - } - } -} - -func TestTenantAPIKeyScopeEmptyRoleDefaultsToViewer(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: "", - }) - - if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil { - t.Fatalf("empty role should allow GET: %v", err) - } -} - -func TestRequireAPIKeyMinRoleForUnsafeAllowsContributorKnowledgeWrite(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: types.TenantRoleContributor, - KnowledgeBaseIDs: types.StringArray{"kb-1"}, - }) - if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil { - t.Fatalf("scoped knowledge write should pass route guard: %v", err) - } -} - -func TestRequireAPIKeyDenyBlocksBatchWrite(t *testing.T) { - ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ - Role: types.TenantRoleContributor, - KnowledgeBaseIDs: types.StringArray{"kb-1"}, - }) - if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil { - t.Fatalf("unexpected contributor role check failure: %v", err) - } - // Deny is enforced by RequireAPIKeyDeny middleware on the route; verify scope exists. - if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok { - t.Fatal("expected api key scope in context") - } -} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index f54a1ac5..68deeae8 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -260,7 +260,7 @@ func authenticateAPIKeyRequest( if c.IsAborted() { return false } - if err := authorizeTenantAPIKeyAccess(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil { + if err := rejectTenantAPIKeyManagementPath(c.Request.Context(), 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 diff --git a/internal/middleware/auth_api_key_scope_test.go b/internal/middleware/auth_api_key_scope_test.go index a7a491c1..c644a936 100644 --- a/internal/middleware/auth_api_key_scope_test.go +++ b/internal/middleware/auth_api_key_scope_test.go @@ -10,8 +10,8 @@ import ( ) // TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach verifies the -// authorizeTenantAPIKeyAccess call in authenticateAPIKeyRequest reads scope -// from c.Request.Context() after attachAPIKeyAuthContext, not the pre-attach ctx. +// rejectTenantAPIKeyManagementPath call in authenticateAPIKeyRequest reads +// scope from c.Request.Context() after attachAPIKeyAuthContext. func TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach(t *testing.T) { gin.SetMode(gin.TestMode) @@ -20,15 +20,15 @@ func TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach(t *testing.T) { preAttach := c.Request.Context() c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(preAttach, types.TenantAPIKeyScope{ - KeyID: 1, - Role: types.TenantRoleViewer, + KeyID: 1, + Role: types.TenantRoleViewer, })) - if err := authorizeTenantAPIKeyAccess(preAttach, c.Request.Method, c.Request.URL.Path); err != nil { + if err := rejectTenantAPIKeyManagementPath(preAttach, c.Request.URL.Path); err != nil { t.Fatalf("pre-attach ctx should not carry scope and must not block: %v", err) } - if err := authorizeTenantAPIKeyAccess(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil { - t.Fatalf("baseline defers unsafe DELETE to route guards: %v", err) + if err := rejectTenantAPIKeyManagementPath(c.Request.Context(), c.Request.URL.Path); err != nil { + t.Fatalf("non-management path should pass auth baseline: %v", err) } if err := requireTenantAPIKeyMinRole(c.Request.Context(), types.TenantRoleContributor); err == nil { t.Fatal("viewer key must not satisfy contributor route guard on DELETE") diff --git a/internal/middleware/kb_access.go b/internal/middleware/kb_access.go index 733b78ff..7093856b 100644 --- a/internal/middleware/kb_access.go +++ b/internal/middleware/kb_access.go @@ -241,8 +241,8 @@ func RequireKBAccess( } ctx := c.Request.Context() - if err := authorizeTenantAPIKeyKnowledgeBase(ctx, kbID); err != nil { - _ = c.Error(apperrors.NewForbiddenError("API key scope does not allow this knowledge base")) + if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil { + _ = c.Error(err) c.Abort() return }