Refine scoped API key capabilities

This commit is contained in:
wizardchen
2026-07-07 11:09:10 +08:00
committed by lyingbug
parent b5cc7d2a28
commit 2c6f082062
38 changed files with 1718 additions and 655 deletions
+35 -37
View File
@@ -21,20 +21,32 @@ var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidde
// default (fail-closed), which removes the old "remember to add APIKeyDeny"
// footgun.
type APIKeyRoutePolicy struct {
// MinRole is the minimum tenant role an API key needs for this route.
//
// Data-plane routes (knowledge bases and their content) use Viewer /
// Contributor / Admin; for those, safe reads (GET/HEAD/OPTIONS) only
// require Viewer while writes require the declared role. Tenant-level
// infrastructure routes (models, vector stores, MCP, data sources,
// channels, tenant KV, ...) use Owner, which is required for EVERY
// method — reading tenant configuration is itself a privileged action.
//
// KB scoping is NOT enforced here: a key's knowledge_base_ids allow-list
// is a pure data filter applied by the KBAccess guards and the handler
// scope checks on data-plane routes. Tenant-level routes are simply
// gated behind the Owner role instead of being reachable by a narrow key.
MinRole types.TenantRole
// RequireFullAccess admits only full-access tenant API keys unless one of
// the listed capabilities also matches. Routes with neither full-access
// requirement nor capabilities are open to any valid API key.
RequireFullAccess bool
// Capabilities is an any-of allow-list for scoped API keys. A capability
// never widens which knowledge bases a key may touch; KB scoping is
// enforced downstream by KBAccess guards and handler scope checks.
Capabilities []types.APIKeyCapability
}
// WithCapability returns a copy of the policy that additionally admits keys
// carrying capability c. Multiple calls accumulate (any-of semantics);
// duplicates are ignored.
func (p APIKeyRoutePolicy) WithCapability(c types.APIKeyCapability) APIKeyRoutePolicy {
for _, existing := range p.Capabilities {
if existing == c {
return p
}
}
// Copy the slice so mutating the returned policy never aliases the
// receiver's backing array.
next := make([]types.APIKeyCapability, len(p.Capabilities), len(p.Capabilities)+1)
copy(next, p.Capabilities)
p.Capabilities = append(next, c)
return p
}
// APIKeyRouteAuthorizer is the registry of per-route API-key policies. It is
@@ -116,23 +128,18 @@ func (a *APIKeyRouteAuthorizer) authorize(scope types.TenantAPIKeyScope, method,
if !ok {
return errTenantAPIKeyScopeForbidden
}
role := scope.Role
if role == "" {
role = types.TenantRoleViewer
if scope.FullAccess {
return nil
}
required := policy.MinRole
if required == "" {
required = types.TenantRoleViewer
for _, cap := range policy.Capabilities {
if cap != "" && scope.HasCapability(cap) {
return nil
}
}
// Data-plane safe reads only need a Viewer floor. Tenant-level (Owner)
// routes require the full role even for reads, so they are never lowered.
if isSafeHTTPMethod(method) && required != types.TenantRoleOwner {
required = types.TenantRoleViewer
if !policy.RequireFullAccess && len(policy.Capabilities) == 0 {
return nil
}
if !role.HasPermission(required) {
return errTenantAPIKeyScopeForbidden
}
return nil
return errTenantAPIKeyScopeForbidden
}
// DenyAPIKeyPrincipal returns a middleware that rejects any X-API-Key
@@ -154,15 +161,6 @@ func DenyAPIKeyPrincipal() gin.HandlerFunc {
}
}
func isSafeHTTPMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
default:
return false
}
}
// normalizeRoutePath collapses duplicate slashes and trims a trailing slash so
// helper-built paths (BasePath()+rel) match gin's c.FullPath() exactly.
func normalizeRoutePath(p string) string {
+75 -55
View File
@@ -11,20 +11,16 @@ import (
func newTestAuthorizer() *APIKeyRouteAuthorizer {
a := NewAPIKeyRouteAuthorizer()
// Data-plane routes (Viewer read, Contributor write, Admin destructive)
// plus one tenant-level Owner route.
a.Register(http.MethodGet, "/api/v1/knowledge-bases/:id", policyMinRole(types.TenantRoleViewer))
a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file", policyMinRole(types.TenantRoleContributor))
a.Register(http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge", policyMinRole(types.TenantRoleAdmin))
a.Register(http.MethodGet, "/api/v1/models", policyMinRole(types.TenantRoleOwner))
a.Register(http.MethodPut, "/api/v1/tenants/kv/:key", policyMinRole(types.TenantRoleOwner))
a.Register(http.MethodGet, "/api/v1/auth/me", APIKeyRoutePolicy{})
a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityIngest))
a.Register(http.MethodGet, "/api/v1/models",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageModels))
a.Register(http.MethodPut, "/api/v1/tenants/kv/:key",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageTenantSettings))
return a
}
func policyMinRole(r types.TenantRole) APIKeyRoutePolicy {
return APIKeyRoutePolicy{MinRole: r}
}
// runGate exercises the gate middleware with a given scope, method and route
// full-path, returning whether the request was allowed to proceed.
func runGate(t *testing.T, a *APIKeyRouteAuthorizer, scope *types.TenantAPIKeyScope, method, fullPath string) bool {
@@ -56,8 +52,6 @@ func concretePath(tmpl string) string {
return "/api/v1/knowledge-bases/kb-1"
case "/api/v1/knowledge-bases/:id/knowledge/file":
return "/api/v1/knowledge-bases/kb-1/knowledge/file"
case "/api/v1/knowledge-bases/:id/knowledge":
return "/api/v1/knowledge-bases/kb-1/knowledge"
case "/api/v1/tenants/kv/:key":
return "/api/v1/tenants/kv/some-key"
default:
@@ -67,7 +61,7 @@ func concretePath(tmpl string) string {
func TestGateJWTPassesThrough(t *testing.T) {
a := newTestAuthorizer()
// No scope => JWT principal => always allowed, even on an Owner route.
// No scope => JWT principal => always allowed, even on a full-access route.
if !runGate(t, a, nil, http.MethodGet, "/api/v1/models") {
t.Fatal("JWT principal must pass the gate")
}
@@ -75,11 +69,11 @@ func TestGateJWTPassesThrough(t *testing.T) {
func TestGateDefaultDeny(t *testing.T) {
a := newTestAuthorizer()
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
full := &types.TenantAPIKeyScope{FullAccess: true}
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *owner))
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *full))
c.Next()
})
engine.Use(a.Middleware())
@@ -87,54 +81,80 @@ func TestGateDefaultDeny(t *testing.T) {
w := httptest.NewRecorder()
engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/agents", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("undeclared route should default-deny even an Owner key: status=%d", w.Code)
t.Fatalf("undeclared route should default-deny even a full-access key: status=%d", w.Code)
}
}
func TestGateDataPlaneRoleLadder(t *testing.T) {
func TestGateAnyPolicyAllowsScopedKey(t *testing.T) {
a := newTestAuthorizer()
viewer := &types.TenantAPIKeyScope{Role: types.TenantRoleViewer}
contributor := &types.TenantAPIKeyScope{Role: types.TenantRoleContributor}
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
scoped := &types.TenantAPIKeyScope{}
// Safe read: any data-plane key (Viewer) passes.
if !runGate(t, a, viewer, http.MethodGet, "/api/v1/knowledge-bases/:id") {
t.Fatal("viewer key should read a declared KB route")
}
// Contributor write.
if runGate(t, a, viewer, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("viewer key must not perform a contributor write")
}
if !runGate(t, a, contributor, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("contributor key should perform a contributor write")
}
// Admin destructive.
if runGate(t, a, contributor, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
t.Fatal("contributor key must not perform an admin destructive op")
}
if !runGate(t, a, admin, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
t.Fatal("admin key should perform an admin destructive op")
if !runGate(t, a, scoped, http.MethodGet, "/api/v1/auth/me") {
t.Fatal("scoped key should call a declared route with an empty policy")
}
}
func TestGateTenantRoutesRequireOwner(t *testing.T) {
func TestGateFullAccessAndCapabilityPolicies(t *testing.T) {
a := newTestAuthorizer()
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
scoped := &types.TenantAPIKeyScope{}
full := &types.TenantAPIKeyScope{FullAccess: true}
ingest := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"ingest"}}
models := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_models"}}
// Even a safe GET on a tenant-level route requires Owner (no Viewer floor).
if runGate(t, a, admin, http.MethodGet, "/api/v1/models") {
t.Fatal("admin key must NOT read a tenant-level route")
if runGate(t, a, scoped, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("plain scoped key must not write content")
}
if !runGate(t, a, owner, http.MethodGet, "/api/v1/models") {
t.Fatal("owner key should read a tenant-level route")
if !runGate(t, a, full, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("full-access key should write content")
}
// Unsafe tenant write also requires Owner.
if runGate(t, a, admin, http.MethodPut, "/api/v1/tenants/kv/:key") {
t.Fatal("admin key must NOT write a tenant-level route")
if !runGate(t, a, ingest, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("ingest capability should write content")
}
if !runGate(t, a, owner, http.MethodPut, "/api/v1/tenants/kv/:key") {
t.Fatal("owner key should write a tenant-level route")
if runGate(t, a, ingest, http.MethodGet, "/api/v1/models") {
t.Fatal("ingest capability must not read model management routes")
}
if !runGate(t, a, models, http.MethodGet, "/api/v1/models") {
t.Fatal("manage_models capability should read model management routes")
}
}
func TestGateAnyOfCapabilities(t *testing.T) {
a := NewAPIKeyRouteAuthorizer()
a.Register(http.MethodPost, "/api/v1/sessions",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityChat))
a.Register(http.MethodGet, "/api/v1/agents",
APIKeyRoutePolicy{RequireFullAccess: true}.
WithCapability(types.APIKeyCapabilityChat).
WithCapability(types.APIKeyCapabilityManageAgents))
a.Register(http.MethodPost, "/api/v1/agents",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageAgents))
a.Register(http.MethodPut, "/api/v1/knowledge-bases/:id",
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageKnowledgeBases))
chat := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"chat"}}
manage := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_agents"}}
manageKBs := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_kbs"}}
// Either capability satisfies the any-of read route.
if !runGate(t, a, chat, http.MethodGet, "/api/v1/agents") {
t.Fatal("chat should read agents (any-of)")
}
if !runGate(t, a, manage, http.MethodGet, "/api/v1/agents") {
t.Fatal("manage_agents should read agents (any-of)")
}
// Only manage_agents may author agents.
if runGate(t, a, chat, http.MethodPost, "/api/v1/agents") {
t.Fatal("chat must not author agents")
}
if !runGate(t, a, manage, http.MethodPost, "/api/v1/agents") {
t.Fatal("manage_agents should author agents")
}
// Only manage_kbs may manage KB metadata/config.
if runGate(t, a, manage, http.MethodPut, "/api/v1/knowledge-bases/:id") {
t.Fatal("manage_agents must not manage knowledge bases")
}
if !runGate(t, a, manageKBs, http.MethodPut, "/api/v1/knowledge-bases/:id") {
t.Fatal("manage_kbs should manage knowledge bases")
}
}
@@ -143,11 +163,11 @@ func TestGateKBScopeDoesNotBlockDataPlane(t *testing.T) {
// A KB-restricted key is NOT blocked by the gate on data-plane routes;
// its KB allow-list is enforced downstream by KBAccess/handler checks.
restricted := &types.TenantAPIKeyScope{
Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-1"},
Capabilities: types.StringArray{"ingest"},
}
if !runGate(t, a, restricted, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("KB-restricted contributor key should pass the gate on a data-plane write")
t.Fatal("KB-restricted ingest key should pass the gate on a data-plane write")
}
}
@@ -176,8 +196,8 @@ func runDenyAPIKey(t *testing.T, scope *types.TenantAPIKeyScope) (reached bool,
// engine-root routes (outside /api/v1) that rely on RequireRole must not be
// reachable by API-key principals, since RequireRole short-circuits them.
func TestDenyAPIKeyPrincipalBlocksAPIKeys(t *testing.T) {
// Even an Owner-role API key must be rejected outright.
reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{Role: types.TenantRoleOwner})
// Even a full-access API key must be rejected outright.
reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{FullAccess: true})
if reached {
t.Fatal("API-key principal must not reach a DenyAPIKeyPrincipal-guarded handler")
}
+12 -11
View File
@@ -250,8 +250,8 @@ func authenticateAPIKeyRequest(
if c.IsAborted() {
return false
}
// Per-route API-key authorization (role + KB scope + default-deny) is
// enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
// Per-route API-key authorization (full access + capabilities + KB scope)
// is enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
// Key-management and any other undeclared route is denied there.
return true
}
@@ -299,25 +299,26 @@ func attachAPIKeyAuthContext(
return
}
c.Set(types.PrincipalContextKey.String(), principal)
apiKeyRole := types.TenantRoleViewer
if key != nil {
apiKeyRole = types.NormalizeTenantAPIKeyRole(key.Role)
if apiKeyRole == "" {
apiKeyRole = types.TenantRoleViewer
}
// This role context exists only for legacy guard compatibility after
// RequireRole short-circuits API-key principals. The API key's real
// authority is FullAccess + Capabilities + KnowledgeBaseIDs.
apiKeyTenantRoleContext := types.TenantRoleViewer
if key != nil && key.FullAccess {
apiKeyTenantRoleContext = types.TenantRoleOwner
}
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
c.Set(types.TenantRoleContextKey.String(), apiKeyTenantRoleContext)
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, apiKeyRole)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyTenantRoleContext)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
if key != nil {
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
KeyID: key.ID,
Role: apiKeyRole,
FullAccess: key.FullAccess,
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
Capabilities: key.Capabilities,
})
}
c.Request = c.Request.WithContext(ctx)
@@ -12,9 +12,9 @@ import (
)
// apiKeyRBACHarness seeds an API-key scope (as attachAPIKeyAuthContext would)
// plus a deliberately-insufficient TenantRole, then runs the guard. It
// asserts the JWT guard short-circuits for API-key principals so that
// per-route API-key authorization is left entirely to the APIKeyGate.
// plus a deliberately-insufficient TenantRole, then runs the guard. It asserts
// the JWT guard short-circuits for API-key principals so that per-route
// API-key authorization is left entirely to the APIKeyGate.
func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw gin.HandlerFunc) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
@@ -32,10 +32,10 @@ func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw
}
func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
// Viewer-role API key against an Admin gate would 403 under the JWT
// Scoped API key against an Admin gate would 403 under the JWT
// ladder; the short-circuit lets it through (the gate handles it).
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleViewer},
types.TenantAPIKeyScope{},
types.TenantRoleViewer,
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)),
)
@@ -46,7 +46,7 @@ func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleOwner},
types.TenantAPIKeyScope{FullAccess: true},
types.TenantRoleOwner,
RequireSystemAdmin(cfgRBAC(true)),
)
@@ -55,24 +55,27 @@ func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
}
}
// TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor is the core
// regression for review #1: a Contributor API key writing to a KB it does not
// TestRequireOwnershipOrRole_ShortCircuitsAPIKey is the core regression for
// review #1: an API key writing to a KB it does not
// "own" (synthetic system user never matches creator_id) must not be 403'd by
// the OwnedKBOrAdmin guard when EnableRBAC=true. The lookup deliberately
// returns a foreign creator to prove the guard never runs it.
func TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor(t *testing.T) {
func TestRequireOwnershipOrRole_ShortCircuitsAPIKey(t *testing.T) {
lookupCalled := false
lookup := func(_ *gin.Context) (string, error) {
lookupCalled = true
return "some-other-human-user", nil
}
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleContributor, KnowledgeBaseIDs: types.StringArray{"kb-1"}},
types.TenantAPIKeyScope{
KnowledgeBaseIDs: types.StringArray{"kb-1"},
Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
},
types.TenantRoleContributor,
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("Contributor API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
t.Fatalf("API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
}
if lookupCalled {
t.Fatal("ownership lookup must not run for API-key principals")