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
+149
View File
@@ -0,0 +1,149 @@
package middleware
import (
"net/http"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// CreatorLookup resolves the creator user ID for the resource targeted
// by the current request, based on whatever is on the gin.Context (URL
// params, query, body). Implementations live next to the handlers they
// guard, e.g. handler.kbCreatorLookup(c) reads ":id" and returns
// KnowledgeBase.CreatorID.
//
// Returning ("", nil) means "no creator recorded" — the resource pre-dates
// the migration backfill. RequireOwnershipOrRole treats this as
// "tenant-owned" and requires the role check to pass.
//
// Any non-nil error short-circuits the request with 403; callers should
// distinguish "not found" (404 in the handler if needed) from genuine
// failures inside their lookup helper.
type CreatorLookup func(c *gin.Context) (creatorID string, err error)
// RequireRole returns a gin middleware that aborts the request with
// HTTP 403 unless the caller's TenantRole (set by the auth middleware
// in TenantRoleContextKey) is at least min.
//
// When cfg.Tenant.EnableRBAC is false, the middleware logs the would-be
// rejection but lets the request through — preserving today's behaviour
// during the rollout window. Once operators flip the flag to true,
// the same code paths start rejecting unauthorised callers.
//
// The auth middleware always sets a TenantRole; if for some reason it
// is missing, TenantRoleFromContext defaults to TenantRoleViewer, which
// is the safest fail-closed value: anything that requires more than
// Viewer will reject.
func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
role := types.TenantRoleFromContext(c.Request.Context())
if role.HasPermission(min) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(c.Request.Context())
if !rbacEnforcementEnabled(cfg) {
logger.Warnf(c.Request.Context(),
"[rbac] role insufficient (logged but not enforced): user=%s have=%s need=%s path=%s",
uid, role, min, c.Request.URL.Path)
c.Next()
return
}
logger.Warnf(c.Request.Context(),
"[rbac] role insufficient: user=%s have=%s need=%s path=%s",
uid, role, min, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: insufficient tenant role",
})
c.Abort()
}
}
// RequireOwnershipOrRole guards endpoints whose access is allowed for
// either (a) callers whose role is at least min, or (b) the original
// creator of the resource being touched.
//
// Use it for KB / agent mutations where Contributors should only manage
// their own resources but Admins+ have free reign. The lookup closure
// is responsible for translating the URL into the resource's creator
// user ID.
//
// Decision order:
// 1. role >= min -> allow.
// 2. lookup returns the caller's user ID -> allow.
// 3. lookup returns a non-empty different user ID -> deny (or log when
// enforcement is disabled).
// 4. lookup returns an empty creator ID (legacy / unmigrated row) ->
// treat as tenant-owned; only role >= min may proceed. Effectively
// equivalent to step 1 for that row.
// 5. lookup returns an error -> deny (don't fail open on lookup errors:
// a broken creator query is more often a bug than a transient blip,
// and treating a load failure as "approve" would be a footgun).
//
// Like RequireRole, when cfg.Tenant.EnableRBAC is false the middleware
// logs but does not block.
func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
role := types.TenantRoleFromContext(ctx)
// Fast path: role meets the bar, skip the lookup entirely.
if role.HasPermission(min) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(ctx)
creator, err := lookup(c)
if err != nil {
logger.Warnf(ctx,
"[rbac] creator lookup failed: user=%s path=%s err=%v",
uid, c.Request.URL.Path, err)
if !rbacEnforcementEnabled(cfg) {
c.Next()
return
}
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: cannot verify resource ownership",
})
c.Abort()
return
}
// Ownership match wins even when role is below min — that's the
// whole point: Contributors can edit their own resources.
if creator != "" && creator == uid {
c.Next()
return
}
if !rbacEnforcementEnabled(cfg) {
logger.Warnf(ctx,
"[rbac] ownership/role insufficient (logged, not enforced): "+
"user=%s have=%s need=%s creator=%q path=%s",
uid, role, min, creator, c.Request.URL.Path)
c.Next()
return
}
logger.Warnf(ctx,
"[rbac] ownership/role insufficient: user=%s have=%s need=%s creator=%q path=%s",
uid, role, min, creator, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: must own the resource or have the required role",
})
c.Abort()
}
}
// rbacEnforcementEnabled reports whether middleware should actually
// reject failed checks. When the flag is off the middleware still runs
// (so role lookups exercise the membership table and any logging fires)
// but rejection is downgraded to a warning. Mirrors the pattern in
// resolveTenantRole's fail-open branch in middleware/auth.go.
func rbacEnforcementEnabled(cfg *config.Config) bool {
return cfg != nil && cfg.Tenant != nil && cfg.Tenant.EnableRBAC
}
+178
View File
@@ -0,0 +1,178 @@
package middleware
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// rbacTestHarness builds a tiny gin engine with the RBAC middleware in
// front of a no-op handler. It seeds context just like the real auth
// middleware would, so RequireRole / RequireOwnershipOrRole see the
// expected TenantRole and UserID.
//
// Returning the recorder rather than asserting inline keeps each test
// case focused on the (input -> status) pair it cares about.
func rbacTestHarness(role types.TenantRole, userID string, mw gin.HandlerFunc) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
// Mirror what middleware/auth.go's JWT path sets.
ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, role)
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.GET("/protected", mw, func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
r.ServeHTTP(w, req)
return w
}
func cfgRBAC(enabled bool) *config.Config {
return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: enabled}}
}
// ---------- RequireRole ----------
func TestRequireRole_AllowsAtMin(t *testing.T) {
w := rbacTestHarness(types.TenantRoleAdmin, "u1",
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)))
if w.Code != http.StatusOK {
t.Fatalf("Admin should clear Admin gate, got %d", w.Code)
}
}
func TestRequireRole_AllowsAboveMin(t *testing.T) {
w := rbacTestHarness(types.TenantRoleOwner, "u1",
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)))
if w.Code != http.StatusOK {
t.Fatalf("Owner should clear Admin gate, got %d", w.Code)
}
}
func TestRequireRole_RejectsBelowMin(t *testing.T) {
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("Contributor must NOT clear Admin gate, got %d", w.Code)
}
}
func TestRequireRole_FailOpenWhenRBACDisabled(t *testing.T) {
// EnableRBAC=false: the middleware should log but not block, so the
// downstream handler still runs. This is the rollout-safety guarantee.
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireRole(types.TenantRoleOwner, cfgRBAC(false)))
if w.Code != http.StatusOK {
t.Fatalf("EnableRBAC=false must let Viewer through Owner gate, got %d", w.Code)
}
}
func TestRequireRole_NilConfigFailsOpen(t *testing.T) {
// Defensive: nil config must not panic and must fail open (no enforcement
// configured = behave like the legacy path).
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireRole(types.TenantRoleAdmin, nil))
if w.Code != http.StatusOK {
t.Fatalf("nil config must fail open, got %d", w.Code)
}
}
// ---------- RequireOwnershipOrRole ----------
func TestRequireOwnershipOrRole_AdminBypassesLookup(t *testing.T) {
// Admin / Owner clear the role gate without touching the lookup,
// so an erroring lookup still passes when the caller has the role.
called := false
lookup := func(c *gin.Context) (string, error) {
called = true
return "", errors.New("must not be called")
}
w := rbacTestHarness(types.TenantRoleAdmin, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusOK {
t.Fatalf("Admin should pass without lookup, got %d", w.Code)
}
if called {
t.Fatalf("lookup must not run when role already meets min")
}
}
func TestRequireOwnershipOrRole_CreatorAllowed(t *testing.T) {
lookup := func(c *gin.Context) (string, error) { return "u1", nil }
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusOK {
t.Fatalf("creator must clear ownership gate, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_NonCreatorContributorRejected(t *testing.T) {
// Contributor editing someone else's resource is the exact case the
// matrix targets: only the original creator OR Admin+ may proceed.
lookup := func(c *gin.Context) (string, error) { return "someone-else", nil }
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("non-creator Contributor must hit 403, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_LegacyEmptyCreatorTreatedAsTenantOwned(t *testing.T) {
// Pre-migration rows (or rows the backfill couldn't resolve) carry
// creator_id = "". Per the contract those are tenant-owned: only the
// role check decides.
lookup := func(c *gin.Context) (string, error) { return "", nil }
// Contributor on a tenant-owned row -> rejected, only Admin+ can mutate.
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("Contributor on legacy tenant-owned row should hit 403, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_LookupErrorRejects(t *testing.T) {
// A failing lookup is treated as deny — failing open here would mean
// any DB hiccup on the creator query becomes a free pass.
lookup := func(c *gin.Context) (string, error) { return "", errors.New("boom") }
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("lookup error must reject, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_FailOpenWhenRBACDisabled(t *testing.T) {
// Enforcement off: even a failing lookup + non-creator + low role lets
// the request through. This preserves today's "anyone in the tenant
// can edit anything" behaviour while we ship the schema.
lookup := func(c *gin.Context) (string, error) { return "someone-else", nil }
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(false)))
if w.Code != http.StatusOK {
t.Fatalf("EnableRBAC=false must let Viewer non-creator through, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_FailOpenOnLookupErrorWhenRBACDisabled(t *testing.T) {
// Lookup errors in fail-open mode also let the request through —
// otherwise turning RBAC off wouldn't actually unblock anything that
// needs the lookup.
lookup := func(c *gin.Context) (string, error) { return "", errors.New("boom") }
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(false)))
if w.Code != http.StatusOK {
t.Fatalf("EnableRBAC=false + lookup error must fail open, got %d", w.Code)
}
}