feat(rbac): enforce tenant role matrix on routes (PR 2 of 3, #1303)

Build on PR 1's tenant_members schema by enforcing the role matrix on
every authenticated route and at agent run time. Enforcement is gated
behind cfg.Tenant.EnableRBAC so the change ships dormant — the same
code paths log the would-be rejection during the rollout window and
start blocking once operators flip the flag.

Middleware (internal/middleware/rbac.go):
- RequireRole(min, cfg): role-only gate using TenantRole.HasPermission.
- RequireOwnershipOrRole(min, lookup, cfg): allows the original creator
  through even when their role is below min, otherwise falls back to
  the role check. Lookup errors fail closed; an empty creator_id is
  treated as tenant-owned and requires the role.
- Both honour cfg.Tenant.EnableRBAC for the rollout window.

Creator lookups (internal/handler/rbac_lookups.go):
- KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID.
- AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy; built-in
  agents (IsBuiltin=true) return ("", nil) so they remain Admin+ only.
- Compile-time guards keep the methods aligned with CreatorLookup.

Route guards (internal/router/rbac.go + router.go):
- rbacGuards bundles the matrix into Viewer/Contributor/Admin/Owner
  helpers plus OwnedKBOrAdmin / OwnedAgentOrAdmin. Each Register*
  function takes *rbacGuards so route lines remain readable.
- KB / Agent / Knowledge / Chunk / Tenant / Model / MCPService /
  VectorStore / DataSource / IMChannel routes annotated per the PR 1
  design doc matrix. Tenant-wide infra (models, vector stores, MCP,
  data sources, IM channels) reads as Viewer+ and writes as Admin+;
  per-resource mutations on KB / Agent route through the
  ownership-or-Admin guard.

Resource ownership (services):
- CreateKnowledgeBase / CopyKnowledgeBase populate CreatorID from the
  authenticated user, so the OwnedKBOrAdmin guard has a creator to
  match.
- CreateAgent / CopyAgent populate CreatedBy similarly. Built-in
  agents stay tenant-owned.

Agent run-time gate (internal/handler/session/qa.go):
- AgentQA refuses to launch the agent engine for Viewers when the
  target agent has RunnableByViewer=false. Same EnableRBAC gating as
  the middleware so it's a no-op until enforcement is turned on.

Tests:
- 12 unit tests cover RequireRole / RequireOwnershipOrRole, including
  the fail-open and fail-closed branches and the lookup-error path.
This commit is contained in:
wizardchen
2026-05-13 21:16:54 +08:00
committed by lyingbug
parent af23483433
commit 9e3c92ca95
8 changed files with 789 additions and 212 deletions
@@ -65,6 +65,14 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
}
agent.TenantID = tenantID
// Record the creator. Mirrors KnowledgeBase.CreatorID — needed by
// RBAC's RequireOwnershipOrRole so Contributors can edit their own
// agents. Synthetic system-{tenantID} users (X-API-Key path) leave
// the field empty, which makes the agent tenant-owned (Admin+ only).
if uid, ok := types.UserIDFromContext(ctx); ok {
agent.CreatedBy = uid
}
// Set timestamps
agent.CreatedAt = time.Now()
agent.UpdatedAt = time.Now()
@@ -406,6 +414,11 @@ func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.C
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// The clone is owned by whoever ran the copy, not the original
// creator — same reasoning as CopyKnowledgeBase.
if uid, ok := types.UserIDFromContext(ctx); ok {
newAgent.CreatedBy = uid
}
// Ensure defaults
newAgent.EnsureDefaults()
@@ -92,6 +92,15 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb.CreatedAt = time.Now()
kb.TenantID = types.MustTenantIDFromContext(ctx)
kb.UpdatedAt = time.Now()
// Record the creator so RBAC's RequireOwnershipOrRole can let
// Contributors edit their own KBs without granting them tenant-wide
// edit rights. UserIDFromContext returns ("", false) for the
// synthetic system-{tenantID} user used by the X-API-Key auth path
// — leaving CreatorID empty there marks the KB as tenant-owned, which
// matches today's API-key semantics (any human Admin can manage it).
if uid, ok := types.UserIDFromContext(ctx); ok {
kb.CreatorID = uid
}
kb.EnsureDefaults()
// Fold empty-string vector_store_id into nil so this path and the
@@ -793,6 +802,12 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
FAQConfig: faqConfig,
VectorStoreID: sourceKB.VectorStoreID,
}
// The clone is owned by the caller, not the original creator —
// otherwise a Contributor copying someone else's KB would still
// not be able to edit the result.
if uid, ok := types.UserIDFromContext(ctx); ok {
targetKB.CreatorID = uid
}
targetKB.EnsureDefaults()
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
return nil, nil, err