fix(rbac): address PR 2 review feedback

Middleware
- RequireOwnershipOrRole now skips the creator lookup entirely when
  EnableRBAC is off, eliminating a hidden per-request DB roundtrip in
  the rollout window.
- New ErrResourceNotFound sentinel lets lookups signal "not visible to
  this tenant"; the middleware passes the request through so handlers
  can return a real 404 instead of a misleading 403.
- Transient lookup failures now surface as 503 (was 403) so monitoring
  can tell denied-by-policy from cannot-verify-right-now.
- Cross-tenant superusers (CanAccessAllTenants) bypass tenant role gates,
  restoring DELETE /tenants/:id and ResetAPIKey for org operators that
  resolve to Admin in foreign tenants.
- Construction-time warning fires once when cfg is nil/incomplete, so a
  wiring bug that disables enforcement globally is visible at boot.

Route coverage
- Add role guards to FAQ, KnowledgeTag, WikiPage, Skill, WebSearch,
  WebSearchProvider, WeKnoraCloud, Session, Chat, and Message route
  groups so the matrix actually matches the PR description.

Service layer
- KB and agent creators are no longer recorded as the synthetic
  system-<tenantID> user used by the X-API-Key path; resources stay
  tenant-owned. New types.IsSyntheticUserID helper centralises the
  prefix check.
- KBCreatorLookup and AgentCreatorLookup re-check tenant scope so a
  same-ID resource in another tenant cannot piggyback through the
  ownership shortcut.

Docs
- CustomAgent.RunnableByViewer comment now matches enforcement: it only
  blocks Viewer-driven agent-mode runs, not plain RAG/Wiki QA.

Tests
- New cases for the 503/404 paths, lookup-skip behaviour, cross-tenant
  superuser bypass, the lookup helpers (not-found, cross-tenant,
  built-in agent, missing tenant context), and IsSyntheticUserID.
This commit is contained in:
wizardchen
2026-05-13 21:37:47 +08:00
committed by lyingbug
parent 9e3c92ca95
commit 8b71def60b
10 changed files with 621 additions and 162 deletions
+130 -48
View File
@@ -1,7 +1,10 @@
package middleware
import (
"context"
"errors"
"net/http"
"sync"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
@@ -9,25 +12,49 @@ import (
"github.com/gin-gonic/gin"
)
// ErrResourceNotFound is the sentinel a CreatorLookup returns when the
// :id on the request does not match any row the lookup can see (either
// the row is genuinely missing or its tenant doesn't match). When a
// lookup returns this error, RequireOwnershipOrRole intentionally lets
// the request proceed so the downstream handler can respond with its
// own 404 — middleware-level 403 would hide real "URL is wrong" failures
// behind a permissions error, which breaks client diagnostics and
// operator dashboards.
var ErrResourceNotFound = errors.New("rbac: resource not found")
// 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.
// Return value contract:
// - (creatorID, nil) where creatorID != "" -> the resource has a
// recorded owner; ownership match grants access.
// - ("", nil) -> "tenant-owned": no
// human creator was recorded (legacy row or built-in resource);
// only callers whose role meets the bar may proceed.
// - ("", ErrResourceNotFound) -> the :id does not
// resolve to any row visible to this caller's tenant. Middleware
// proceeds to the handler so the handler can return 404 instead
// of masking it as 403.
// - ("", other error) -> transient or
// unexpected failure (DB hiccup, etc.). Middleware returns 503
// when enforcement is on so monitoring catches the real fault;
// when enforcement is off, it logs and lets the request through.
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.
//
// Cross-tenant superusers (User.CanAccessAllTenants) automatically
// satisfy any role gate. Otherwise rolling out tenant-RBAC would silently
// break organisation-level operators who own no tenant_members row in
// the tenant they're administering. The escape hatch is bounded by the
// existing canAccessTenant gate in auth.go; this middleware does not
// grant extra reach, only honours what was already approved.
//
// 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,
@@ -38,21 +65,27 @@ type CreatorLookup func(c *gin.Context) (creatorID string, err error)
// is the safest fail-closed value: anything that requires more than
// Viewer will reject.
func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
role := types.TenantRoleFromContext(c.Request.Context())
ctx := c.Request.Context()
role := types.TenantRoleFromContext(ctx)
if role.HasPermission(min) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(c.Request.Context())
if isCrossTenantSuperuser(ctx) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(ctx)
if !rbacEnforcementEnabled(cfg) {
logger.Warnf(c.Request.Context(),
logger.Warnf(ctx,
"[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(),
logger.Warnf(ctx,
"[rbac] role insufficient: user=%s have=%s need=%s path=%s",
uid, role, min, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
@@ -69,66 +102,81 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
// 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.
// user ID (see CreatorLookup for the return-value contract).
//
// 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.
// 1. role >= min -> allow without running lookup.
// 2. cross-tenant superuser -> allow without running lookup.
// 3. enforcement off -> log, allow without running lookup. This is the
// critical rollout-safety guarantee: when EnableRBAC is false, the
// lookup is NEVER invoked, so dormant mode incurs zero extra DB
// roundtrips on hot per-resource mutation paths.
// 4. lookup returns ErrResourceNotFound -> pass through; let the
// handler issue the proper 404.
// 5. lookup returns other error -> 503 (transient/unexpected fault).
// Preserves observability instead of disguising server errors as 403.
// 6. lookup returns the caller's user ID -> allow (ownership match).
// 7. lookup returns "" -> tenant-owned, role check already failed: 403.
// 8. lookup returns a different non-empty user ID -> 403.
func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
role := types.TenantRoleFromContext(ctx)
// Fast path: role meets the bar, skip the lookup entirely.
// 1. Fast path: role meets the bar.
if role.HasPermission(min) {
c.Next()
return
}
// 2. Cross-tenant superuser bypass — same reasoning as RequireRole.
if isCrossTenantSuperuser(ctx) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(ctx)
creator, err := lookup(c)
if err != nil {
// 3. Fail-open shortcut: when enforcement is off, do NOT run the
// lookup. Running it would add a hidden DB roundtrip on every
// mutating request during the rollout window — see #1318 review.
if !rbacEnforcementEnabled(cfg) {
logger.Warnf(ctx,
"[rbac] ownership/role would be checked (enforcement off, lookup skipped): "+
"user=%s have=%s need=%s path=%s",
uid, role, min, c.Request.URL.Path)
c.Next()
return
}
creator, err := lookup(c)
switch {
case errors.Is(err, ErrResourceNotFound):
// 4. Hand off to the handler so the client sees a real 404
// rather than a fake "no permission" 403.
c.Next()
return
case err != nil:
// 5. Genuine failure — surface it as 5xx so monitoring catches it.
logger.Errorf(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.JSON(http.StatusServiceUnavailable, gin.H{
"error": "Service Unavailable: 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.
// 6. 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
}
// 7-8. Tenant-owned (creator=="") or non-creator with insufficient role.
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)
@@ -141,9 +189,43 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con
// 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.
// role-only checks (logging, fast paths), but rejection is downgraded
// to a warning and ownership lookups are skipped entirely so the dormant
// rollout window incurs no per-request DB cost.
func rbacEnforcementEnabled(cfg *config.Config) bool {
return cfg != nil && cfg.Tenant != nil && cfg.Tenant.EnableRBAC
}
// isCrossTenantSuperuser reports whether the caller is an org-level
// superuser whose CanAccessAllTenants flag was honoured by the auth
// middleware (cfg.Tenant.EnableCrossTenantAccess must also be on for
// the flag to mean anything operationally). Such callers bypass tenant
// role gates because their access is already governed by a separate
// org-level authorisation check.
func isCrossTenantSuperuser(ctx context.Context) bool {
u, ok := ctx.Value(types.UserContextKey).(*types.User)
if !ok || u == nil {
return false
}
return u.CanAccessAllTenants
}
// warnOnNilConfig emits a one-shot startup warning when a guard is
// constructed with a nil-or-incomplete config. nil cfg makes
// rbacEnforcementEnabled return false, which means an entire deployment
// silently runs with RBAC disabled — usually because of a configuration
// bug rather than an intentional choice. Operators should see a noisy
// log line at boot pointing at the misconfiguration.
var nilCfgWarnOnce sync.Once
func warnOnNilConfig(cfg *config.Config) {
if cfg != nil && cfg.Tenant != nil {
return
}
nilCfgWarnOnce.Do(func() {
logger.Errorf(context.Background(),
"[rbac] middleware constructed with nil/incomplete config "+
"(cfg=%v); enforcement is permanently disabled. This is "+
"almost certainly a wiring bug.", cfg)
})
}
+96 -4
View File
@@ -142,14 +142,106 @@ func TestRequireOwnershipOrRole_LegacyEmptyCreatorTreatedAsTenantOwned(t *testin
}
}
func TestRequireOwnershipOrRole_LookupErrorRejects(t *testing.T) {
// A failing lookup is treated as deny — failing open here would mean
func TestRequireOwnershipOrRole_LookupErrorReturns503(t *testing.T) {
// A transient lookup error surfaces as 503 (not 403) so monitoring
// and clients can tell "your permission was denied" from "the server
// briefly couldn't verify ownership". 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)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("lookup error must surface as 503, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_NotFoundPassesThroughTo404(t *testing.T) {
// When the lookup signals "no such resource visible to this tenant",
// the middleware MUST NOT mask it as 403. The handler downstream
// gets to decide the right status (usually 404), which keeps client
// error handling honest and avoids hiding "wrong URL" behind a
// permissions error.
called := false
lookup := func(c *gin.Context) (string, error) {
return "", ErrResourceNotFound
}
router := gin.New()
router.Use(func(c *gin.Context) {
ctx := c.Request.Context()
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
ctx = context.WithValue(ctx, types.UserIDContextKey, "u1")
c.Request = c.Request.WithContext(ctx)
c.Next()
})
router.GET("/protected",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
func(c *gin.Context) {
called = true
c.JSON(http.StatusNotFound, gin.H{"error": "kb not found"})
},
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if !called {
t.Fatalf("handler should have been invoked so it can produce 404")
}
if w.Code != http.StatusNotFound {
t.Fatalf("expected handler 404 to win, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_SkipsLookupWhenRBACDisabled(t *testing.T) {
// H1 regression: when enforcement is off, the lookup must not run at
// all. Hooking up RBAC pre-rollout used to add a hidden DB roundtrip
// to every mutating request even though the result was thrown away.
calls := 0
lookup := func(c *gin.Context) (string, error) {
calls++
return "someone-else", nil
}
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(false)))
if w.Code != http.StatusOK {
t.Fatalf("fail-open should let the request through, got %d", w.Code)
}
if calls != 0 {
t.Fatalf("lookup must not run when EnableRBAC=false (got %d calls)", calls)
}
}
func TestRequireOwnershipOrRole_CrossTenantSuperuserBypass(t *testing.T) {
// Cross-tenant superusers resolve to Admin in foreign tenants (see
// resolveTenantRole). For Owner-only gates we additionally let them
// through to preserve the pre-RBAC ability to administer any tenant.
calls := 0
lookup := func(c *gin.Context) (string, error) {
calls++
return "", nil
}
router := gin.New()
router.Use(func(c *gin.Context) {
ctx := c.Request.Context()
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = context.WithValue(ctx, types.UserIDContextKey, "su1")
ctx = context.WithValue(ctx, types.UserContextKey, &types.User{
ID: "su1", CanAccessAllTenants: true,
})
c.Request = c.Request.WithContext(ctx)
c.Next()
})
router.GET("/protected",
RequireOwnershipOrRole(types.TenantRoleOwner, lookup, cfgRBAC(true)),
func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) },
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("superuser must bypass Owner gate, got %d", w.Code)
}
if calls != 0 {
t.Fatalf("superuser bypass must skip lookup, got %d", calls)
}
}