fix(api-keys): allow scoped file serve and ingest batch routes
Let tenant-wide retrieve keys serve tenant-bounded /files paths while denying KB-restricted keys, declare knowledge batch write routes for ingest-capable keys, and short-circuit ownership checks for API-key principals already authorized by the gate and KB allow-list.
This commit is contained in:
@@ -161,6 +161,37 @@ func DenyAPIKeyPrincipal() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// AllowFileServeAPIKey guards the tenant-scoped file-proxy routes (/files and
|
||||
// the KB-scoped image proxy) for X-API-Key callers. Those routes serve an
|
||||
// arbitrary storage path that only carries a tenant segment — there is no KB
|
||||
// id in the path a KB-restricted key's allow-list could be checked against —
|
||||
// so a KB-restricted key is denied outright (it must download KB content via
|
||||
// the KB-scoped routes such as /knowledge/:id/download, which DO enforce the
|
||||
// allow-list). A key passes when it is full-access, or when it is NOT
|
||||
// KB-restricted and carries the retrieve capability: that is exactly the class
|
||||
// of key that can already read any of the tenant's KB content, so exposing the
|
||||
// tenant-bounded raw file path (the handler still enforces
|
||||
// ValidateStoragePathTenant / the KB owner tenant) grants it nothing new. JWT
|
||||
// sessions carry no API-key scope and pass straight through.
|
||||
func AllowFileServeAPIKey() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
scope, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context())
|
||||
if !ok {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if scope.FullAccess ||
|
||||
(!scope.IsKnowledgeBaseRestricted() &&
|
||||
scope.HasCapability(types.APIKeyCapabilityRetrieve)) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"error": "Forbidden: API key scope does not allow this operation",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -215,6 +215,74 @@ func TestDenyAPIKeyPrincipalAllowsJWT(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// runAllowFileServe mounts AllowFileServeAPIKey ahead of a handler and reports
|
||||
// whether the request reached the handler.
|
||||
func runAllowFileServe(t *testing.T, scope *types.TenantAPIKeyScope) (reached bool, status int) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(func(c *gin.Context) {
|
||||
if scope != nil {
|
||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *scope))
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
engine.GET("/files", AllowFileServeAPIKey(), func(c *gin.Context) {
|
||||
reached = true
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/files", nil))
|
||||
return reached, w.Code
|
||||
}
|
||||
|
||||
func TestAllowFileServeAPIKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
scope *types.TenantAPIKeyScope
|
||||
wantReached bool
|
||||
}{
|
||||
{name: "jwt passes", scope: nil, wantReached: true},
|
||||
{name: "full access passes", scope: &types.TenantAPIKeyScope{FullAccess: true}, wantReached: true},
|
||||
{
|
||||
name: "tenant-wide retrieve passes",
|
||||
scope: &types.TenantAPIKeyScope{
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityRetrieve)},
|
||||
},
|
||||
wantReached: true,
|
||||
},
|
||||
{
|
||||
name: "kb-restricted retrieve denied",
|
||||
scope: &types.TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityRetrieve)},
|
||||
},
|
||||
wantReached: false,
|
||||
},
|
||||
{
|
||||
name: "non-retrieve capability denied",
|
||||
scope: &types.TenantAPIKeyScope{
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityChat)},
|
||||
},
|
||||
wantReached: false,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reached, status := runAllowFileServe(t, tc.scope)
|
||||
if reached != tc.wantReached {
|
||||
t.Fatalf("reached=%v want %v (status=%d)", reached, tc.wantReached, status)
|
||||
}
|
||||
if tc.wantReached && status != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", status)
|
||||
}
|
||||
if !tc.wantReached && status != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRoutePath(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"/api/v1//models": "/api/v1/models",
|
||||
|
||||
@@ -314,6 +314,17 @@ func EvaluateOwnershipOrRole(
|
||||
creatorID string,
|
||||
lookupErr error,
|
||||
) error {
|
||||
// API-key principals are authorized solely by the APIKeyGate (route
|
||||
// policy) plus the KB allow-list handlers enforce separately
|
||||
// (requireTenantAPIKeyKnowledgeBase(s)). Ownership ("creator OR Admin+")
|
||||
// is a human concept that never applies to a machine principal, so
|
||||
// short-circuit here — exactly as RequireOwnershipOrRole does for the
|
||||
// middleware form. Without this, a scoped key (synthesized as Viewer for
|
||||
// legacy-guard compatibility) would be 403'd by the body-carried-KB
|
||||
// ownership checks even though the gate + allow-list already admitted it.
|
||||
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
|
||||
return nil
|
||||
}
|
||||
role := types.TenantRoleFromContext(ctx)
|
||||
if role.HasPermission(min) {
|
||||
return nil
|
||||
|
||||
@@ -82,6 +82,37 @@ func TestRequireOwnershipOrRole_ShortCircuitsAPIKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvaluateOwnershipOrRole_ShortCircuitsAPIKey mirrors
|
||||
// TestRequireOwnershipOrRole_ShortCircuitsAPIKey for the handler-side twin used
|
||||
// when the KB id is carried in the request body (MoveKnowledge /
|
||||
// BatchDeleteKnowledge via requireKBOwnershipOrAdmin). A scoped ingest key that
|
||||
// the APIKeyGate + KB allow-list already admitted must not be re-rejected here
|
||||
// just because it is synthesized as a Viewer for legacy-guard compatibility.
|
||||
func TestEvaluateOwnershipOrRole_ShortCircuitsAPIKey(t *testing.T) {
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
|
||||
})
|
||||
// Synthesized Viewer role + a foreign creator would 403 a human caller.
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
|
||||
if err := EvaluateOwnershipOrRole(ctx, cfgRBAC(true),
|
||||
types.TenantRoleAdmin, "some-other-human-user", nil); err != nil {
|
||||
t.Fatalf("API-key principal should short-circuit EvaluateOwnershipOrRole, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: a JWT Viewer with a foreign creator is still forbidden — the
|
||||
// short-circuit must be scoped to API-key principals only.
|
||||
func TestEvaluateOwnershipOrRole_JWTViewerStillDenied(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
err := EvaluateOwnershipOrRole(ctx, cfgRBAC(true),
|
||||
types.TenantRoleAdmin, "some-other-human-user", nil)
|
||||
if err == nil {
|
||||
t.Fatal("JWT Viewer with foreign creator must be denied by EvaluateOwnershipOrRole")
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: a real JWT Viewer is still rejected by the Admin gate — the
|
||||
// short-circuit must be scoped to API-key principals only.
|
||||
func TestRequireRole_JWTViewerStillDenied(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user