Files
Enterprise-Knowledge-Base/internal/handler/rbac_lookups.go
T
wizardchen 9e3c92ca95 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.
2026-05-18 17:28:58 +08:00

71 lines
2.5 KiB
Go

package handler
import (
"errors"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/gin-gonic/gin"
)
// Per-resource creator-id resolvers used by middleware.RequireOwnershipOrRole.
// The route registration wires these as closures so they capture the handler's
// service dependencies; the middleware just calls them with the gin.Context
// and gets back ("", nil) for legacy tenant-owned rows or (creatorID, nil)
// for resources we know how to attribute.
//
// Lookup contract (mirrors middleware.CreatorLookup):
// - URL param missing -> error (the middleware will 403; better than
// letting an unauthenticated mutation through on a malformed route).
// - Resource not found -> error (downstream handler would 404 anyway,
// and middleware-level 403 is a fine signal to clients).
// - Resource found but creator_id == "" -> ("", nil); the middleware
// treats that as tenant-owned and falls back to pure role check.
// KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID. Used by all
// per-KB mutating routes.
func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
id := c.Param("id")
if id == "" {
return "", errors.New("missing :id param for KB creator lookup")
}
kb, err := h.service.GetKnowledgeBaseByID(c.Request.Context(), id)
if err != nil {
return "", err
}
if kb == nil {
return "", apprepo.ErrKnowledgeBaseNotFound
}
return kb.CreatorID, nil
}
// AgentCreatorLookup resolves :id -> CustomAgent.CreatedBy. Built-in
// agents (IsBuiltin == true) are tenant-owned across the board: they
// belong to the tenant rather than to any one user, so we return
// ("", nil) and let the role check decide. The same holds for legacy
// rows whose CreatedBy was never populated.
func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error) {
id := c.Param("id")
if id == "" {
return "", errors.New("missing :id param for agent creator lookup")
}
agent, err := h.service.GetAgentByID(c.Request.Context(), id)
if err != nil {
return "", err
}
if agent == nil {
return "", errors.New("agent not found")
}
if agent.IsBuiltin {
return "", nil
}
return agent.CreatedBy, nil
}
// Compile-time guards: the methods must satisfy middleware.CreatorLookup
// so route wiring stays type-safe even if a signature drifts.
var (
_ middleware.CreatorLookup = (*KnowledgeBaseHandler)(nil).KBCreatorLookup
_ middleware.CreatorLookup = (*CustomAgentHandler)(nil).AgentCreatorLookup
)