refactor(api-keys): use role field and route-level API key guards

Replace scopes JSON with a viewer/contributor/admin role column, move
unsafe-method authorization from path-prefix middleware to declarative
APIKey* guards on routes, and close remaining KB-scope gaps in handlers.
This commit is contained in:
wizardchen
2026-07-06 13:23:55 +08:00
committed by lyingbug
parent 3ace6e657f
commit 9a76a24ce6
28 changed files with 678 additions and 438 deletions
+83
View File
@@ -0,0 +1,83 @@
package middleware
import (
"context"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// isTenantAPIKeyManagementPath reports tenant API-key lifecycle endpoints that
// no scoped key may call, regardless of role.
func isTenantAPIKeyManagementPath(path string) bool {
for _, marker := range []string{"/api-keys", "/api-principal"} {
if strings.Contains(path, marker) {
return true
}
}
// Legacy reset endpoint: POST /tenants/:id/api-key (singular).
return strings.HasSuffix(path, "/api-key")
}
// RequireAPIKeyDeny rejects all X-API-Key callers. JWT sessions pass through.
func RequireAPIKeyDeny() gin.HandlerFunc {
return func(c *gin.Context) {
if _, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context()); ok {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
// RequireAPIKeyMinRole enforces minRole for X-API-Key callers on every HTTP
// method. JWT sessions pass through.
func RequireAPIKeyMinRole(minRole types.TenantRole) gin.HandlerFunc {
return func(c *gin.Context) {
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
// RequireAPIKeyMinRoleForUnsafe enforces minRole for X-API-Key callers on
// POST/PUT/PATCH/DELETE only. Safe reads (GET/HEAD/OPTIONS) pass through so
// group-level guards can cover mixed read/write route trees.
func RequireAPIKeyMinRoleForUnsafe(minRole types.TenantRole) gin.HandlerFunc {
return func(c *gin.Context) {
if isSafeHTTPMethod(c.Request.Method) {
c.Next()
return
}
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
func requireTenantAPIKeyMinRole(ctx context.Context, minRole types.TenantRole) error {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok {
return nil
}
role := scope.Role
if role == "" {
role = types.TenantRoleViewer
}
if !role.HasPermission(minRole) {
return errTenantAPIKeyScopeForbidden
}
return nil
}
@@ -0,0 +1,79 @@
package middleware
import (
"context"
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func TestRequireAPIKeyDenyBlocksAPIKey(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleAdmin,
})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyDeny()(c)
if !c.IsAborted() {
t.Fatal("expected API key request to be aborted")
}
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
}
}
func TestRequireAPIKeyDenyAllowsJWT(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
RequireAPIKeyDeny()(c)
if c.IsAborted() {
t.Fatal("expected JWT request to pass RequireAPIKeyDeny")
}
}
func TestRequireAPIKeyMinRoleForUnsafeSkipsSafeMethods(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleAdmin); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("viewer should not satisfy admin min role: %v", err)
}
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/models", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin)(c)
if c.IsAborted() {
t.Fatal("safe GET should skip unsafe min-role guard")
}
}
func TestRequireAPIKeyMinRoleEnforcesOnPost(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-search", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyMinRole(types.TenantRoleViewer)(c)
if c.IsAborted() {
t.Fatal("viewer key should pass viewer min role on POST")
}
}
@@ -0,0 +1,84 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func TestTenantAPIKeyRouteScopeManifest(t *testing.T) {
readCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
writeCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleContributor,
})
adminCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleAdmin,
})
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},
}
for _, tc := range baselineCases {
t.Run("baseline/"+tc.name, func(t *testing.T) {
err := authorizeTenantAPIKeyAccess(tc.ctx, tc.method, 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)
}
})
}
guardCases := []struct {
name string
ctx context.Context
method string
guard gin.HandlerFunc
allowed bool
}{
{name: "read delete kb", ctx: readCtx, method: http.MethodDelete, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: false},
{name: "write put kb", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
{name: "write create kb", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
{name: "write batch delete", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
{name: "write faq upsert", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
{name: "write semantic search post", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "read semantic search post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "read knowledge chat post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "admin tenant kv", ctx: adminCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: true},
{name: "contributor tenant kv", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: false},
}
for _, tc := range guardCases {
t.Run("guard/"+tc.name, func(t *testing.T) {
got := runAPIKeyGuard(t, tc.ctx, tc.method, tc.guard)
if got != tc.allowed {
t.Fatalf("guard allowed=%v, want %v", got, tc.allowed)
}
})
}
}
func runAPIKeyGuard(t *testing.T, ctx context.Context, method string, guard gin.HandlerFunc) bool {
t.Helper()
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(method, "/api/v1/test", nil)
c.Request = c.Request.WithContext(ctx)
guard(c)
return !c.IsAborted() && w.Code != http.StatusForbidden
}
+10 -97
View File
@@ -4,39 +4,34 @@ import (
"context"
stderrors "errors"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/types"
)
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
// authorizeTenantAPIKeyAccess enforces per-key operation and route scopes for
// X-API-Key callers. Non-API-key principals are not restricted.
// 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
}
if strings.Contains(path, "/api-keys") {
role := scope.Role
if role == "" {
role = types.TenantRoleViewer
}
if isTenantAPIKeyManagementPath(path) {
return errTenantAPIKeyScopeForbidden
}
if isSafeHTTPMethod(method) {
if allowsTenantAPIKeyRead(scope) {
if role.HasPermission(types.TenantRoleViewer) {
return nil
}
return errTenantAPIKeyScopeForbidden
}
if isTenantAPIKeyReadUnsafePath(method, path) && allowsTenantAPIKeyRead(scope) {
return nil
}
if isKnowledgeScopedUnsafePath(path) && allowsTenantAPIKeyWrite(scope) {
return nil
}
if allowsTenantAPIKeyAdmin(scope) {
return nil
}
return errTenantAPIKeyScopeForbidden
return nil
}
func authorizeTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error {
@@ -58,85 +53,3 @@ func isSafeHTTPMethod(method string) bool {
return false
}
}
func isKnowledgeScopedUnsafePath(path string) bool {
denyPrefixes := []string{
"/api/v1/knowledge-bases/copy",
"/api/v1/knowledge/tags",
"/api/v1/knowledge/batch-reparse",
"/api/v1/knowledge/batch-delete",
"/api/v1/knowledge/move",
}
for _, prefix := range denyPrefixes {
if path == prefix || strings.HasPrefix(path, prefix+"/") {
return false
}
}
if path == "/api/v1/sessions" {
return true
}
allowPrefixes := []string{
"/api/v1/knowledge-bases/",
"/api/v1/knowledge/",
"/api/v1/chunks/",
"/api/v1/knowledgebase/",
"/api/v1/knowledge-search",
"/api/v1/knowledge-chat/",
}
for _, prefix := range allowPrefixes {
if path == prefix || strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
func allowsTenantAPIKeyRead(scope types.TenantAPIKeyScope) bool {
scope = scope.Normalize()
return scope.HasScope(types.TenantAPIKeyScopeRead) ||
scope.HasScope(types.TenantAPIKeyScopeWrite) ||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
}
func allowsTenantAPIKeyWrite(scope types.TenantAPIKeyScope) bool {
scope = scope.Normalize()
return scope.HasScope(types.TenantAPIKeyScopeWrite) ||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
}
func allowsTenantAPIKeyAdmin(scope types.TenantAPIKeyScope) bool {
scope = scope.Normalize()
return scope.HasScope(types.TenantAPIKeyScopeAdmin)
}
func isTenantAPIKeyReadUnsafePath(method, path string) bool {
if method != http.MethodPost {
return false
}
if path == "/api/v1/sessions" ||
path == "/api/v1/knowledge-search" ||
path == "/api/v1/messages/search" ||
path == "/api/v1/chunker/preview" {
return true
}
readPrefixes := []string{
"/api/v1/knowledge-chat/",
"/api/v1/agent-chat/",
}
for _, prefix := range readPrefixes {
if strings.HasPrefix(path, prefix) {
return true
}
}
readSuffixes := []string{
"/hybrid-search",
"/faq/search",
}
for _, suffix := range readSuffixes {
if strings.HasSuffix(path, suffix) {
return true
}
}
return false
}
+47 -85
View File
@@ -11,37 +11,27 @@ import (
func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
Role: types.TenantRoleViewer,
})
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
t.Fatalf("read scoped key should allow GET: %v", err)
t.Fatalf("viewer key should allow GET: %v", err)
}
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil {
t.Fatalf("read scoped key should allow HEAD: %v", err)
t.Fatalf("viewer key should allow HEAD: %v", err)
}
}
func TestTenantAPIKeyScopeReadOnlyRejectsUnsafeMethods(t *testing.T) {
func TestTenantAPIKeyScopeBaselineAllowsUnsafeThrough(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
Role: types.TenantRoleViewer,
})
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.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"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("read scoped key DELETE error = %v, want errTenantAPIKeyScopeForbidden", err)
}
}
func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
})
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil {
t.Fatalf("read scoped key should allow semantic read POST: %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)
}
}
@@ -60,80 +50,52 @@ func TestTenantAPIKeyScopeAllowsScopedKnowledgeBase(t *testing.T) {
func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
Role: types.TenantRoleAdmin,
})
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)
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 TestTenantAPIKeyRouteRejectsTenantWriteForKnowledgeRestrictedKey(t *testing.T) {
func TestTenantAPIKeyScopeEmptyRoleDefaultsToViewer(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
KnowledgeBaseIDs: types.StringArray{"kb-1"},
Role: "",
})
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme")
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
}
}
func TestTenantAPIKeyRouteRejectsTenantWriteForWriteScope(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
})
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/1")
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
}
}
func TestTenantAPIKeyRouteAllowsTenantWriteForAdminScope(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
})
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)
}
}
func TestTenantAPIKeyRouteAllowsKnowledgeWriteForKnowledgeRestrictedKey(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
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)
}
}
func TestTenantAPIKeyRouteRejectsCrossKnowledgeBatchWriteForKnowledgeRestrictedKey(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
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)
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")
}
}
+5 -5
View File
@@ -313,10 +313,10 @@ func attachAPIKeyAuthContext(
c.Set(types.PrincipalContextKey.String(), principal)
apiKeyRole := types.TenantRoleViewer
if key != nil {
apiKeyRole = types.TenantAPIKeyScope{
Scopes: key.Scopes,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
}.TenantRole()
apiKeyRole = types.NormalizeTenantAPIKeyRole(key.Role)
if apiKeyRole == "" {
apiKeyRole = types.TenantRoleViewer
}
}
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
c.Set(types.SystemAdminContextKey.String(), false)
@@ -328,7 +328,7 @@ func attachAPIKeyAuthContext(
if key != nil {
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
KeyID: key.ID,
Scopes: key.Scopes,
Role: apiKeyRole,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
})
}
@@ -21,13 +21,16 @@ func TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach(t *testing.T) {
preAttach := c.Request.Context()
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(preAttach, types.TenantAPIKeyScope{
KeyID: 1,
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
Role: types.TenantRoleViewer,
}))
if err := authorizeTenantAPIKeyAccess(preAttach, c.Request.Method, 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.Fatal("post-attach request context must enforce read scope on DELETE")
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 := requireTenantAPIKeyMinRole(c.Request.Context(), types.TenantRoleContributor); err == nil {
t.Fatal("viewer key must not satisfy contributor route guard on DELETE")
}
}