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.
This commit is contained in:
wizardchen
2026-07-06 13:39:02 +08:00
committed by lyingbug
parent 9a76a24ce6
commit fedb6c3f7e
8 changed files with 77 additions and 174 deletions
+25
View File
@@ -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
}
}
@@ -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)
}
}
@@ -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)
}
})
}
-55
View File
@@ -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
}
}
-101
View File
@@ -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")
}
}
+1 -1
View File
@@ -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
@@ -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")
+2 -2
View File
@@ -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
}