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:
wizardchen
2026-07-20 19:47:42 +08:00
committed by lyingbug
parent 23e606f570
commit d1cab68e3d
7 changed files with 271 additions and 36 deletions
@@ -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) {