fix(api-keys): close KB scope gaps in handlers and CloneContext

Enforce per-key knowledge base restrictions on batch/search read paths,
centralize scope checks in shared KB access validators, and propagate
TenantAPIKeyScope through logger.CloneContext so async QA cannot bypass it.
This commit is contained in:
wizardchen
2026-07-05 10:55:00 +08:00
committed by lyingbug
parent 3f516d7f31
commit 94d18ea15a
5 changed files with 262 additions and 12 deletions
+2
View File
@@ -500,6 +500,7 @@ func CloneContext(ctx context.Context) context.Context {
types.UserIDContextKey,
types.UserContextKey,
types.PrincipalContextKey,
types.TenantAPIKeyScopeContextKey,
// TenantRoleContextKey: the caller's resolved role in the
// active tenant (PR 2 #1303). Must be propagated for the same
// reason as TenantIDContextKey — any handler that does
@@ -508,6 +509,7 @@ func CloneContext(ctx context.Context) context.Context {
// type-zero TenantRole and fall back
// to Viewer, blocking even Owners.
types.TenantRoleContextKey,
types.SystemAdminContextKey,
types.LanguageContextKey,
types.SessionTenantIDContextKey,
types.EmbedQueryContextKey,
+20
View File
@@ -177,3 +177,23 @@ func TestCloneContextPreservesPrincipal(t *testing.T) {
t.Fatalf("SessionOwnerIDFromContext(cloned) = %q", got)
}
}
func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
t.Parallel()
want := types.TenantAPIKeyScope{
KeyID: 7,
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
KnowledgeBaseIDs: types.StringArray{"kb-1"},
}
ctx := types.WithTenantAPIKeyScope(context.Background(), want)
cloned := CloneContext(ctx)
got, ok := types.TenantAPIKeyScopeFromContext(cloned)
if !ok {
t.Fatal("TenantAPIKeyScopeFromContext(cloned) = false, want true")
}
if got.KeyID != want.KeyID || !got.AllowsKnowledgeBase("kb-1") || got.AllowsKnowledgeBase("kb-2") {
t.Fatalf("cloned scope = %#v, want key_id=7 scoped to kb-1", got)
}
}