From 8efe1b4187e150ff9361aa07d647017cac245f4a Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 15 May 2026 23:26:54 +0800 Subject: [PATCH] refactor(rbac): address kb-access guard review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the route-level KB-access guard introduced earlier in this PR. Five reviewer findings, all fixed in middleware + tests without changing handler call sites: - Honour `?agent_id` in the agent-share fallback. The in-handler resolution in knowledgebase.go branches on a specific agent's KBSelectionMode (all / selected / none); the guard was only ever calling TenantCanAccessKBViaSomeSharedAgent, which let some requests pass at the guard layer that the handler would then reject — and rewrote the request's tenant context to the source tenant before the rejection happened. The guard now mirrors the handler: a specific agent_id pins the resolution to that agent (no fallback to any-agent), an empty agent_id keeps the existing any-agent behaviour. The knowledge.go / knowledgebase.go handler helpers stay in place as defence in depth until they're folded into the guard in a follow-up. - Distinguish not-found vs. transient on the knowledge / chunk resolvers. A DB hiccup used to surface as a 404, both confusing clients and hiding the underlying failure from monitoring. The resolvers now return apperror 404 only for the known not-found sentinels (apprepo.ErrKnowledgeBaseNotFound, ErrResourceNotFound) and let other errors propagate; the guard maps those to a fresh NewServiceUnavailableError (503). - Stop 500-ing on legacy chunks with empty knowledge_base_id. The chunk is effectively unresolvable to a KB, so the client gets the same 404 they'd get for a missing chunk instead of a 500 that pollutes alerting. The warn log preserves the operator signal. - Honour cfg.Tenant.EnableRBAC. The guard now mirrors RequireRole / RequireOwnershipOrRole: with enforcement off, 401/403 paths log the would-be rejection and pass through. 404 still fires either way (a missing resource is not an authorisation event). Keeps the rollout window safe — operators can flip enforcement on globally without code changes elsewhere. - Document the c.Keys vs. c.Request.Context() split. The guard intentionally rewrites only the request context (handlers that still run their own share resolution, currently knowledge.go / knowledgebase.go, would otherwise see kb.TenantID == c.Keys tenant and misclassify shared-Viewer access as Admin). The package-level comment now spells this out so the migration of the remaining handlers in a follow-up doesn't accidentally regress `my_permission` rendering. Tests: - Existing four cases keep working; runGuard signature gained a guardOpts knob. - Eight new cases cover the agent-share resolution paths (any-agent viewer, Editor required → must reject, specific agent in modes all / selected-match / selected-miss / none, cross-tenant mismatch) plus the EnableRBAC=false fail-open + 404-still-fires pair. --- internal/errors/errors.go | 13 + internal/middleware/kb_access.go | 191 +++++++++++++-- internal/middleware/kb_access_test.go | 341 +++++++++++++++++++++++++- internal/router/rbac.go | 6 + 4 files changed, 525 insertions(+), 26 deletions(-) diff --git a/internal/errors/errors.go b/internal/errors/errors.go index f5a95998..1458a983 100644 --- a/internal/errors/errors.go +++ b/internal/errors/errors.go @@ -122,6 +122,19 @@ func NewInternalServerError(message string) *AppError { } } +// NewServiceUnavailableError creates a service unavailable (503) +// error. Used for transient failures where the caller can retry. +func NewServiceUnavailableError(message string) *AppError { + if message == "" { + message = "服务暂时不可用" + } + return &AppError{ + Code: ErrServiceUnavailable, + Message: message, + HTTPCode: http.StatusServiceUnavailable, + } +} + // NewValidationError creates a validation error func NewValidationError(message string) *AppError { return &AppError{ diff --git a/internal/middleware/kb_access.go b/internal/middleware/kb_access.go index ce72aafa..1d560ff6 100644 --- a/internal/middleware/kb_access.go +++ b/internal/middleware/kb_access.go @@ -5,6 +5,7 @@ import ( stderrors "errors" apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/config" apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" @@ -33,6 +34,22 @@ import ( // Plan 3's 3-D cap (tenant Viewer pinned to OrgRoleViewer) is enforced // inside CheckTenantKBPermission itself, so the guard here just // propagates the result. +// +// ⚠️ Tenant id has TWO surfaces on a gin.Context: +// +// - c.Request.Context() (read via types.TenantIDFromContext) +// - c.Keys[TenantIDContextKey] (read via c.Get / c.GetUint64) +// +// The guard rewrites ONLY the request context — c.Keys is intentionally +// left at the caller's own tenant so handlers that still run their own +// share resolution (currently knowledge.go / knowledgebase.go, which +// branch on the ?agent_id query) keep working unchanged. New handlers +// MUST read tenant from c.Request.Context() (the "effective" tenant +// for shared KBs); reading from c.Keys after this guard runs gives +// the caller's own tenant, which is almost always the wrong answer +// for KB-scoped routes. The FAQ / Tag / Chunk handlers in this PR +// were converted to the ctx-based read; the migration of knowledge.go +// / knowledgebase.go is a follow-up. // KBAccess captures the result of a successful KB access resolution. // Stashed on gin.Context under KBAccessContextKey so handlers that @@ -87,6 +104,10 @@ type ChunkLookup interface { // KBIDResolver tells the guard how to find the kb_id for a given // request. Built-in resolvers below cover the param shapes we use: // :id, :kb_id, :kbId, :knowledge_id (-> parent KB). +// +// On error, resolvers MUST return either a 4xx apperror (bad request / +// not found) or a generic Go error for transient/internal failures; +// the guard maps the latter to 503. type KBIDResolver func(c *gin.Context) (string, error) // KBIDFromParam returns a resolver that reads a fixed gin param. @@ -103,6 +124,11 @@ func KBIDFromParam(param string) KBIDResolver { // KBIDFromKnowledgeIDParam reads `:knowledge_id` from the URL, looks // up the knowledge document, and returns its KB id. Used by the chunk // routes that address a chunk via /chunks/:knowledge_id. +// +// A genuine "not found" maps to 404; transient errors (DB hiccup, +// service unavailable) are surfaced as a plain Go error so the guard +// can return 503 instead of pretending the resource doesn't exist +// (a 404 here would also short-circuit any retry / monitoring). func KBIDFromKnowledgeIDParam(param string, kgService KnowledgeLookup) KBIDResolver { return func(c *gin.Context) (string, error) { v := c.Param(param) @@ -110,7 +136,13 @@ func KBIDFromKnowledgeIDParam(param string, kgService KnowledgeLookup) KBIDResol return "", apperrors.NewBadRequestError("missing " + param + " in path") } k, err := kgService.GetKnowledgeByIDOnly(c.Request.Context(), v) - if err != nil || k == nil { + if err != nil { + if isResourceNotFound(err) { + return "", apperrors.NewNotFoundError("Knowledge not found") + } + return "", err + } + if k == nil { return "", apperrors.NewNotFoundError("Knowledge not found") } return k.KnowledgeBaseID, nil @@ -121,6 +153,8 @@ func KBIDFromKnowledgeIDParam(param string, kgService KnowledgeLookup) KBIDResol // Used by /chunks/by-id/:id routes that address a chunk directly. The // chunk's KnowledgeBaseID is denormalised on the row, so a single // lookup is enough — no need to chain through GetKnowledgeByIDOnly. +// +// Not-found / transient split mirrors KBIDFromKnowledgeIDParam. func KBIDFromChunkIDParam(param string, chunkService ChunkLookup) KBIDResolver { return func(c *gin.Context) (string, error) { v := c.Param(param) @@ -128,18 +162,37 @@ func KBIDFromChunkIDParam(param string, chunkService ChunkLookup) KBIDResolver { return "", apperrors.NewBadRequestError("missing " + param + " in path") } ch, err := chunkService.GetChunkByIDOnly(c.Request.Context(), v) - if err != nil || ch == nil { + if err != nil { + if isResourceNotFound(err) { + return "", apperrors.NewNotFoundError("Chunk not found") + } + return "", err + } + if ch == nil { return "", apperrors.NewNotFoundError("Chunk not found") } if ch.KnowledgeBaseID == "" { - // Some old chunks may not carry the denormalised KB id; - // this is a should-never-happen branch on a fresh schema. - return "", apperrors.NewInternalServerError("chunk missing knowledge_base_id") + // Should-never-happen on a fresh schema; on legacy rows the + // chunk effectively isn't resolvable to a KB so the client + // gets the same 404 they'd get for a missing chunk rather + // than a 500 that pollutes alerting. + logger.Warnf(c.Request.Context(), + "[kb_access] chunk %s has empty knowledge_base_id; treating as not-found", v) + return "", apperrors.NewNotFoundError("Chunk not found") } return ch.KnowledgeBaseID, nil } } +// isResourceNotFound recognises the various "not found" sentinels we +// might see from the underlying services. Keeps the resolvers above +// from forcing every service to standardise on a single error type +// before this refactor is useful. +func isResourceNotFound(err error) bool { + return stderrors.Is(err, apprepo.ErrKnowledgeBaseNotFound) || + stderrors.Is(err, ErrResourceNotFound) +} + // RequireKBAccess returns a gin.HandlerFunc that resolves KB access // (own / org-shared / via shared agent), enforces the minimum required // org-level permission, and on success stores the result under @@ -148,24 +201,32 @@ func KBIDFromChunkIDParam(param string, chunkService ChunkLookup) KBIDResolver { // context as before. // // On failure the guard aborts with the appropriate HTTP status (400 / -// 401 / 404 / 403 / 500). Behaviour matches what each handler's +// 401 / 404 / 403 / 503). Behaviour matches what each handler's // effectiveCtxForKB helper used to do; the guard is what consolidates // the repetition so a fix in the resolution order propagates to every // gated route at once. // // Required permission semantics: // - OrgRoleViewer -> read-only routes (the agent-share fallback path -// activates only at this level) +// activates only at this level) // - OrgRoleEditor -> mutating routes (org-shared editor or own KB) // - OrgRoleAdmin -> share-management routes (only the original -// sharer / KB owner / Org admin should pass) +// sharer / KB owner / Org admin should pass) +// +// When cfg.Tenant.EnableRBAC is false the guard mirrors the sibling +// role/ownership guards: it logs the would-be rejection and lets the +// request through. The point is to keep the rollout window safe — the +// guard runs full enforcement once the flag flips on, with no code +// changes elsewhere. func RequireKBAccess( resolveKBID KBIDResolver, requiredPermission types.OrgMemberRole, kbService KBLookup, kbShareService interfaces.KBShareService, agentShareService interfaces.AgentShareService, + cfg *config.Config, ) gin.HandlerFunc { + warnOnNilConfig(cfg) return func(c *gin.Context) { kbID, err := resolveKBID(c) if err != nil { @@ -175,23 +236,47 @@ func RequireKBAccess( } ctx := c.Request.Context() - access, err := resolveKBAccessOnce(ctx, kbID, requiredPermission, kbService, kbShareService, agentShareService) + + // Rollout window: enforcement off -> log the would-be check and + // pass through. We still resolve the KB (best-effort) so the + // effective-tenant context rewrite still happens for shared + // KBs; that way embedding queries hit the right tenant + // regardless of whether RBAC enforcement is active. + enforcing := rbacEnforcementEnabled(cfg) + + access, err := resolveKBAccessOnce(ctx, c, kbID, requiredPermission, kbService, kbShareService, agentShareService) switch { case stderrors.Is(err, errKBAccessUnauthorized): + if !enforcing { + logger.Warnf(ctx, "[rbac] kb-access would 401 (enforcement off): kb=%s", kbID) + c.Next() + return + } _ = c.Error(apperrors.NewUnauthorizedError("Unauthorized")) c.Abort() return case stderrors.Is(err, errKBAccessNotFound): + // 404 still fires when enforcement is off — a missing KB is + // not an authorisation event, the client genuinely asked + // for nothing. _ = c.Error(apperrors.NewNotFoundError("knowledge base not found")) c.Abort() return case stderrors.Is(err, errKBAccessForbidden): + if !enforcing { + logger.Warnf(ctx, "[rbac] kb-access would 403 (enforcement off): kb=%s required=%s", + kbID, requiredPermission) + c.Next() + return + } _ = c.Error(apperrors.NewForbiddenError("Permission denied to access this knowledge base")) c.Abort() return case err != nil: logger.ErrorWithFields(ctx, err, nil) - _ = c.Error(apperrors.NewInternalServerError(err.Error())) + // Transient/internal -> 503 so monitoring catches the + // underlying failure rather than a misleading 500. + _ = c.Error(apperrors.NewServiceUnavailableError("cannot verify KB access right now")) c.Abort() return } @@ -210,8 +295,17 @@ func RequireKBAccess( // resolveKBAccessOnce performs the actual three-step resolution. Kept // unexported and using package-private sentinel errors so the guard's // error mapping is the only public surface. +// +// The shared-agent step honours the ?agent_id query parameter when +// present, mirroring the in-handler resolution in +// knowledgebase.go's validateAndGetKnowledgeBase: a request with a +// specific agent_id is validated against THAT agent's KB scope (mode = +// all / selected / none), not against "any shared agent". Falling +// back to "any shared agent" when agent_id is empty preserves the +// "通过智能体可见" KB list entry point. func resolveKBAccessOnce( ctx context.Context, + c *gin.Context, kbID string, requiredPermission types.OrgMemberRole, kbService KBLookup, @@ -265,14 +359,8 @@ func resolveKBAccessOnce( // 3. Shared agent that carries this KB — only ever grants read. if requiredPermission == types.OrgRoleViewer && agentShareService != nil { - can, err := agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) - if err == nil && can { - logger.Infof(ctx, "[kb_access] tenant %d -> KB %s via shared agent", tenantID, kbID) - return &KBAccess{ - KnowledgeBase: kb, - EffectiveTenantID: kb.TenantID, - Permission: types.OrgRoleViewer, - }, nil + if access := resolveSharedAgentAccess(ctx, c, tenantID, callerTenantRole, kb, agentShareService); access != nil { + return access, nil } } @@ -280,6 +368,73 @@ func resolveKBAccessOnce( return nil, errKBAccessForbidden } +// resolveSharedAgentAccess implements the agent-share fallback, +// mirroring knowledgebase.go's in-handler logic so the guard and the +// (still-present) handler resolver agree on which requests pass. +// +// - If ?agent_id=X is provided, validate against THAT agent's +// KBSelectionMode (all / selected / none). A mismatch means deny; +// we do NOT fall back to "any shared agent" because the client +// explicitly named one (typically from a @-mention or a deep link +// scoped to that agent). +// - If ?agent_id is empty, allow when any shared agent reachable by +// the caller can access this KB ("通过智能体可见" KB list entry). +func resolveSharedAgentAccess( + ctx context.Context, + c *gin.Context, + tenantID uint64, + callerTenantRole types.TenantRole, + kb *types.KnowledgeBase, + agentShareService interfaces.AgentShareService, +) *KBAccess { + agentID := c.Query("agent_id") + if agentID != "" { + agent, err := agentShareService.GetSharedAgentForTenant(ctx, tenantID, callerTenantRole, agentID) + if err != nil || agent == nil { + return nil + } + if kb.TenantID != agent.TenantID { + logger.Warnf(ctx, "[kb_access] shared agent tenant mismatch: kb=%s kb.tenant=%d agent.tenant=%d", + kb.ID, kb.TenantID, agent.TenantID) + return nil + } + switch agent.Config.KBSelectionMode { + case "all": + logger.Infof(ctx, "[kb_access] tenant %d -> KB %s via shared agent %s (mode=all)", + tenantID, kb.ID, agentID) + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: kb.TenantID, + Permission: types.OrgRoleViewer, + } + case "selected": + for _, allowedID := range agent.Config.KnowledgeBases { + if allowedID == kb.ID { + logger.Infof(ctx, "[kb_access] tenant %d -> KB %s via shared agent %s (mode=selected)", + tenantID, kb.ID, agentID) + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: kb.TenantID, + Permission: types.OrgRoleViewer, + } + } + } + } + return nil + } + + can, err := agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) + if err == nil && can { + logger.Infof(ctx, "[kb_access] tenant %d -> KB %s via some shared agent", tenantID, kb.ID) + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: kb.TenantID, + Permission: types.OrgRoleViewer, + } + } + return nil +} + var ( errKBAccessUnauthorized = stderrors.New("kb_access: unauthorized") errKBAccessNotFound = stderrors.New("kb_access: not found") diff --git a/internal/middleware/kb_access_test.go b/internal/middleware/kb_access_test.go index 0dd6604e..baccf60c 100644 --- a/internal/middleware/kb_access_test.go +++ b/internal/middleware/kb_access_test.go @@ -8,6 +8,7 @@ import ( apprepo "github.com/Tencent/WeKnora/internal/application/repository" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) @@ -94,15 +95,96 @@ func (s *stubKBShareForGuard) CountByOrganizations(context.Context, []string) (m panic("not implemented") } +// stubAgentShareForGuard implements just the two methods the guard +// touches: GetSharedAgentForTenant (when ?agent_id=X is supplied) and +// TenantCanAccessKBViaSomeSharedAgent (the any-shared-agent fallback). +// Every other method panics so unintended new dependencies surface +// immediately. +type stubAgentShareForGuard struct { + // agents indexed by agent id; nil entry means GetSharedAgentForTenant + // returns nil + nil (i.e. caller has no access to that agent id). + agents map[string]*types.CustomAgent + // kbsViaSomeAgent[kb.ID] -> true means the any-agent fallback grants + // access to that KB. + kbsViaSomeAgent map[string]bool +} + +func (s *stubAgentShareForGuard) GetSharedAgentForTenant(_ context.Context, _ uint64, _ types.TenantRole, agentID string) (*types.CustomAgent, error) { + return s.agents[agentID], nil +} + +func (s *stubAgentShareForGuard) TenantCanAccessKBViaSomeSharedAgent(_ context.Context, _ uint64, _ types.TenantRole, kb *types.KnowledgeBase) (bool, error) { + return s.kbsViaSomeAgent[kb.ID], nil +} + +func (s *stubAgentShareForGuard) ShareAgent(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) RemoveShare(context.Context, string, string, uint64) error { + panic("not implemented") +} +func (s *stubAgentShareForGuard) ListSharesByAgent(context.Context, string) ([]*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) ListSharesByOrganization(context.Context, string) ([]*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) ListSharedAgents(context.Context, uint64, types.TenantRole) ([]*types.SharedAgentInfo, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) ListSharedAgentsInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) ListSharedAgentsInOrganizations(context.Context, []string, uint64, types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) SetSharedAgentDisabledByMe(context.Context, uint64, string, uint64, bool) error { + panic("not implemented") +} +func (s *stubAgentShareForGuard) GetShare(context.Context, string) (*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) GetShareByAgentAndOrg(context.Context, string, string) (*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) GetShareByAgentIDForTenant(context.Context, uint64, string, uint64) (*types.AgentShare, error) { + panic("not implemented") +} +func (s *stubAgentShareForGuard) CountByOrganizations(context.Context, []string) (map[string]int64, error) { + panic("not implemented") +} + +// guardOpts collects optional knobs for runGuard. Keeps the call site +// readable when most tests only care about a couple of dimensions. +type guardOpts struct { + agentID string // ?agent_id query param + agentShare *stubAgentShareForGuard // nil means "no agent-share service" +} + // runGuard fires a single request through the guard and returns the -// gin recorder + the kb access (if any) the guard stashed. -func runGuard(t *testing.T, tenantID uint64, kbID string, requiredPerm types.OrgMemberRole, kb *types.KnowledgeBase, share *stubKBShareForGuard) (*httptest.ResponseRecorder, *gin.Context) { +// gin recorder + the kb access (if any) the guard stashed. Defaults +// to EnableRBAC=true; the EnableRBAC=false fail-open path has its own +// dedicated tests further below. +func runGuard( + t *testing.T, + tenantID uint64, + kbID string, + requiredPerm types.OrgMemberRole, + kb *types.KnowledgeBase, + share *stubKBShareForGuard, + opts guardOpts, +) (*httptest.ResponseRecorder, *gin.Context) { t.Helper() gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Params = gin.Params{{Key: "id", Value: kbID}} - req := httptest.NewRequest("GET", "/", nil) + + url := "/" + if opts.agentID != "" { + url = "/?agent_id=" + opts.agentID + } + req := httptest.NewRequest("GET", url, nil) ctx := context.WithValue(req.Context(), types.TenantIDContextKey, tenantID) c.Request = req.WithContext(ctx) @@ -110,7 +192,28 @@ func runGuard(t *testing.T, tenantID uint64, kbID string, requiredPerm types.Org if kb != nil { kbsvc.kbs[kbID] = kb } - guard := RequireKBAccess(KBIDFromParam("id"), requiredPerm, kbsvc, share, nil) + + // Convert the package-local concrete stub types to typed interface + // nils when they aren't supplied — otherwise the interface wraps a + // nil pointer and `iface != nil` evaluates true on the guard side + // (classic Go typed-nil trap). + var shareSvc interfaces.KBShareService + if share != nil { + shareSvc = share + } + var agentSvc interfaces.AgentShareService + if opts.agentShare != nil { + agentSvc = opts.agentShare + } + + guard := RequireKBAccess( + KBIDFromParam("id"), + requiredPerm, + kbsvc, + shareSvc, + agentSvc, + cfgRBAC(true), + ) guard(c) return rec, c } @@ -120,6 +223,7 @@ func TestRequireKBAccess_OwnKB(t *testing.T) { types.OrgRoleViewer, &types.KnowledgeBase{ID: "kb-1", TenantID: 100}, nil, + guardOpts{}, ) require.False(t, c.IsAborted(), "should pass through") require.Equal(t, 200, rec.Code) // gin's default; nothing wrote a status @@ -134,12 +238,11 @@ func TestRequireKBAccess_OwnKB(t *testing.T) { } func TestRequireKBAccess_NotFound_Aborts(t *testing.T) { - rec, c := runGuard(t, 100, "kb-missing", types.OrgRoleViewer, nil, nil) + _, c := runGuard(t, 100, "kb-missing", types.OrgRoleViewer, nil, nil, guardOpts{}) require.True(t, c.IsAborted(), "missing KB must abort") require.NotEmpty(t, c.Errors) _, ok := KBAccessFromContext(c) require.False(t, ok, "no access should be stashed on failure") - _ = rec } func TestRequireKBAccess_SharedKB_RewritesTenantContext(t *testing.T) { @@ -152,12 +255,12 @@ func TestRequireKBAccess_SharedKB_RewritesTenantContext(t *testing.T) { types.OrgRoleEditor, &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, share, + guardOpts{}, ) require.False(t, c.IsAborted()) access, ok := KBAccessFromContext(c) require.True(t, ok) require.Equal(t, uint64(200), access.EffectiveTenantID) - // The downstream handler should see tenant=200 from context. got, _ := types.TenantIDFromContext(c.Request.Context()) require.Equal(t, uint64(200), got, "guard must rewrite context to source tenant") } @@ -172,6 +275,7 @@ func TestRequireKBAccess_SharedKB_PermissionBelowMin_Aborts(t *testing.T) { types.OrgRoleEditor, // require Editor &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, share, + guardOpts{}, ) require.True(t, c.IsAborted(), "Viewer share must reject when Editor required") } @@ -182,7 +286,228 @@ func TestRequireKBAccess_NoTenant_Aborts(t *testing.T) { c, _ := gin.CreateTestContext(rec) c.Params = gin.Params{{Key: "id", Value: "kb-x"}} c.Request = httptest.NewRequest("GET", "/", nil) // no tenant in context - guard := RequireKBAccess(KBIDFromParam("id"), types.OrgRoleViewer, &stubKBLookup{}, nil, nil) + guard := RequireKBAccess( + KBIDFromParam("id"), + types.OrgRoleViewer, + &stubKBLookup{}, + nil, + nil, + cfgRBAC(true), + ) guard(c) require.True(t, c.IsAborted()) } + +// ---------- Agent-share fallback ---------- + +func TestRequireKBAccess_AgentShare_AnyAgent_ViewerOnly(t *testing.T) { + // No org-share entry; caller has at least one shared agent that can + // access this KB. Required permission is Viewer, so the agent-share + // branch activates and grants read access at the source tenant. + agent := &stubAgentShareForGuard{ + kbsViaSomeAgent: map[string]bool{"kb-shared": true}, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent}, + ) + require.False(t, c.IsAborted()) + access, ok := KBAccessFromContext(c) + require.True(t, ok) + require.Equal(t, uint64(200), access.EffectiveTenantID) + require.Equal(t, types.OrgRoleViewer, access.Permission, "agent share grants viewer only") +} + +func TestRequireKBAccess_AgentShare_EditorRequired_Aborts(t *testing.T) { + // Required permission is Editor → agent-share fallback MUST NOT + // activate. Regression test for the implicit-security-fix in this + // PR: old TagHandler.effectiveCtxForKB granted any agent-share + // access to write routes, which leaked tag CRUD. + agent := &stubAgentShareForGuard{ + kbsViaSomeAgent: map[string]bool{"kb-shared": true}, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleEditor, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent}, + ) + require.True(t, c.IsAborted(), "agent share must NOT satisfy Editor requirement") +} + +func TestRequireKBAccess_AgentShare_SpecificAgent_ModeAll(t *testing.T) { + // ?agent_id=A and A has KBSelectionMode=all on the source tenant. + // Guard should accept regardless of which KB. + agent := &stubAgentShareForGuard{ + agents: map[string]*types.CustomAgent{ + "agent-A": { + ID: "agent-A", + TenantID: 200, + Config: types.CustomAgentConfig{ + KBSelectionMode: "all", + }, + }, + }, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent, agentID: "agent-A"}, + ) + require.False(t, c.IsAborted()) + access, _ := KBAccessFromContext(c) + require.Equal(t, types.OrgRoleViewer, access.Permission) +} + +func TestRequireKBAccess_AgentShare_SpecificAgent_ModeSelected_Match(t *testing.T) { + agent := &stubAgentShareForGuard{ + agents: map[string]*types.CustomAgent{ + "agent-A": { + ID: "agent-A", + TenantID: 200, + Config: types.CustomAgentConfig{ + KBSelectionMode: "selected", + KnowledgeBases: []string{"kb-other", "kb-shared"}, + }, + }, + }, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent, agentID: "agent-A"}, + ) + require.False(t, c.IsAborted()) +} + +func TestRequireKBAccess_AgentShare_SpecificAgent_ModeSelected_Miss(t *testing.T) { + // ?agent_id=A but A's selected list does NOT include this KB. Even + // though SOME OTHER shared agent (B) would have granted access via + // the any-agent fallback, the explicit agent_id pins the resolution + // to A. This is the divergence the review flagged. + agent := &stubAgentShareForGuard{ + agents: map[string]*types.CustomAgent{ + "agent-A": { + ID: "agent-A", + TenantID: 200, + Config: types.CustomAgentConfig{ + KBSelectionMode: "selected", + KnowledgeBases: []string{"kb-other"}, + }, + }, + }, + // any-agent fallback would have said yes — but agent_id=A pins us. + kbsViaSomeAgent: map[string]bool{"kb-shared": true}, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent, agentID: "agent-A"}, + ) + require.True(t, c.IsAborted(), "agent_id=A must NOT fall back to any-agent") +} + +func TestRequireKBAccess_AgentShare_SpecificAgent_ModeNone(t *testing.T) { + agent := &stubAgentShareForGuard{ + agents: map[string]*types.CustomAgent{ + "agent-A": { + ID: "agent-A", + TenantID: 200, + Config: types.CustomAgentConfig{ + KBSelectionMode: "none", + }, + }, + }, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent, agentID: "agent-A"}, + ) + require.True(t, c.IsAborted(), "agent in mode=none must not grant access") +} + +func TestRequireKBAccess_AgentShare_SpecificAgent_TenantMismatch(t *testing.T) { + // Agent belongs to tenant 999 but KB belongs to tenant 200 → reject + // (this is the kb.TenantID != agent.TenantID guard in the handler; + // preserves cross-tenant isolation when shares get reshuffled). + agent := &stubAgentShareForGuard{ + agents: map[string]*types.CustomAgent{ + "agent-A": { + ID: "agent-A", + TenantID: 999, + Config: types.CustomAgentConfig{ + KBSelectionMode: "all", + }, + }, + }, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + nil, + guardOpts{agentShare: agent, agentID: "agent-A"}, + ) + require.True(t, c.IsAborted()) +} + +// ---------- EnableRBAC=false rollout window ---------- + +func TestRequireKBAccess_Forbidden_FailOpenWhenRBACDisabled(t *testing.T) { + // Same scenario as PermissionBelowMin (which aborts when enforcing), + // but with EnableRBAC=false the guard logs and passes through. + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Params = gin.Params{{Key: "id", Value: "kb-shared"}} + req := httptest.NewRequest("GET", "/", nil) + c.Request = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(100))) + + share := &stubKBShareForGuard{ + permission: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleViewer}, + shared: map[string]bool{"kb-shared": true}, + source: map[string]uint64{"kb-shared": 200}, + } + kbsvc := &stubKBLookup{kbs: map[string]*types.KnowledgeBase{ + "kb-shared": {ID: "kb-shared", TenantID: 200}, + }} + + guard := RequireKBAccess( + KBIDFromParam("id"), + types.OrgRoleEditor, // would-deny + kbsvc, share, nil, + cfgRBAC(false), // enforcement off + ) + guard(c) + require.False(t, c.IsAborted(), "guard must pass through when EnableRBAC is off") + _ = rec +} + +func TestRequireKBAccess_NotFound_FiresEvenWhenRBACDisabled(t *testing.T) { + // Not-found is not an authorisation event; the client asked for a + // resource that genuinely isn't there. We surface 404 regardless of + // the rollout flag (matches the comment in RequireKBAccess). + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Params = gin.Params{{Key: "id", Value: "kb-missing"}} + req := httptest.NewRequest("GET", "/", nil) + c.Request = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(100))) + + guard := RequireKBAccess( + KBIDFromParam("id"), + types.OrgRoleViewer, + &stubKBLookup{kbs: map[string]*types.KnowledgeBase{}}, + nil, nil, + cfgRBAC(false), + ) + guard(c) + require.True(t, c.IsAborted(), "404 still fires with enforcement off") + _ = rec +} diff --git a/internal/router/rbac.go b/internal/router/rbac.go index 08b50efe..e977b643 100644 --- a/internal/router/rbac.go +++ b/internal/router/rbac.go @@ -320,6 +320,7 @@ func (g *rbacGuards) KBAccessRead(param string) gin.HandlerFunc { g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) } @@ -333,6 +334,7 @@ func (g *rbacGuards) KBAccessWrite(param string) gin.HandlerFunc { g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) } @@ -347,6 +349,7 @@ func (g *rbacGuards) KBAccessReadFromKnowledgeIDParam(param string) gin.HandlerF g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) } @@ -359,6 +362,7 @@ func (g *rbacGuards) KBAccessWriteFromKnowledgeIDParam(param string) gin.Handler g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) } @@ -372,6 +376,7 @@ func (g *rbacGuards) KBAccessReadFromChunkIDParam(param string) gin.HandlerFunc g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) } @@ -385,5 +390,6 @@ func (g *rbacGuards) KBAccessWriteFromChunkIDParam(param string) gin.HandlerFunc g.kbService, g.kbShareService, g.agentShareService, + g.cfg, ) }