refactor(rbac): centralise tenant-access guards in middleware

Tenant-access decisions previously lived in four places with subtly
different shapes: canAccessTenant in middleware/auth.go, an unexported
isCrossTenantSuperuser in middleware/rbac.go, authorizeTenantAccess +
two opening if-blocks in handler/tenant.go, and resolveTenantIDFromPath
in handler/tenant_member.go. Each variant had its own logging, its
own treatment of the cluster-wide EnableCrossTenantAccess flag, and
its own subtle difference in what "URL :id matches active tenant"
meant.

Collapse all four into middleware/access.go:

- IsCrossTenantSuperuser(ctx, cfg): exported, flag-aware. Both the
  per-user CanAccessAllTenants attribute AND
  cfg.Tenant.EnableCrossTenantAccess must be true; either alone
  rejects, so flipping the cluster flag off operationally revokes
  every superuser without a token re-issue.
- IsTenantAccessible(ctx, user, target, memberService, cfg): home
  tenant + superuser path + active tenant_members row. Replaces the
  old superuser-only canAccessTenant; the X-Tenant-ID gate now also
  honours ordinary multi-tenant memberships.
- RequireCrossTenantAccess(cfg): route guard for /tenants/all and
  /tenants/search, replacing the 12-line if-blocks at the top of
  ListAllTenants and SearchTenants.
- RequirePathTenantMatch(cfg): route guard for /tenants/:id/...,
  replacing authorizeTenantAccess (4 callers in tenant.go) and
  resolveTenantIDFromPath's superuser carve-out (5 endpoints in
  tenant_member.go). The router declares it once on the /tenants/:id
  group so the rule lives next to the route definitions.

router/rbac.go grows two factory methods (CrossTenant,
PathTenantMatch) so RegisterTenantRoutes stays declarative and reads
the same as the existing g.Viewer() / g.Owner() / g.OwnedKBOrAdmin()
guards. The /tenants/:id endpoints now group under one
PathTenantMatch() middleware instead of each handler re-deriving the
check.

Handler cleanups follow naturally: tenant.go drops
authorizeTenantAccess and the cross-tenant if-blocks; tenant_member.go
drops the cfg field and shrinks resolveTenantIDFromPath to a thin
parser. NewTenantMemberHandler loses its *config.Config argument;
container/container.go's dig wiring picks up the simpler signature
automatically.

middleware/access_test.go covers all four exports with truth-table
cases (flag/attribute/membership combinations, lookup errors, missing
context). tenant_member_test.go's existing handler-level cross-tenant
assertions still pass because memberTestRouter now mounts
RequirePathTenantMatch the same way the production router does.

Net -41 lines across 8 changed files + 2 new files; no behaviour
change other than the X-Tenant-ID gate accepting active memberships
(which was the original PR 4 goal that motivated this refactor).
This commit is contained in:
wizardchen
2026-05-14 10:56:54 +08:00
committed by lyingbug
parent 543e9709be
commit 2082b63951
10 changed files with 657 additions and 217 deletions
+190
View File
@@ -0,0 +1,190 @@
package middleware
import (
"context"
"net/http"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// access.go centralises the tenant-access checks that previously lived
// scattered across handlers and the various RBAC middlewares:
//
// - "is the caller an org-level superuser" — used by the role guards
// in rbac.go, the X-Tenant-ID branch in auth.go, the tenant
// handler's authorizeTenantAccess, and the tenant member handler's
// resolveTenantIDFromPath.
//
// - "can the caller access target tenant X" — used by the
// X-Tenant-ID branch in auth.go to decide whether to honour the
// header. Originally allowed only superusers; now also allows
// ordinary multi-tenant members who have an active row in the
// target tenant's tenant_members table.
//
// - "must the URL :id match the active tenant" — used by every
// tenant-scoped route. Was duplicated in tenant.go (4 callers) and
// tenant_member.go (1 caller) before; now lives here as a route
// middleware so the route declaration is the single source of
// truth.
//
// All of these honour cfg.Tenant.EnableCrossTenantAccess: the
// CanAccessAllTenants attribute on a User row is meaningful only when
// the cluster-wide flag is on. Reading the attribute alone (without the
// flag) would let a dormant config grant escalation, which is exactly
// what bit us during the PR 3 review.
// IsCrossTenantSuperuser reports whether ctx carries a user that is
// authorised for cross-tenant access at this moment. Both the user
// attribute and the cluster-wide flag must be true; either alone is
// not enough.
func IsCrossTenantSuperuser(ctx context.Context, cfg *config.Config) bool {
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
return false
}
u, ok := ctx.Value(types.UserContextKey).(*types.User)
if !ok || u == nil {
return false
}
return u.CanAccessAllTenants
}
// IsTenantAccessible reports whether `user` is allowed to operate inside
// `targetTenantID`. The decision order is:
//
// 1. Home tenant (user.TenantID == targetTenantID): always.
// 2. Cross-tenant superuser: governed by IsCrossTenantSuperuser.
// 3. Multi-tenant member: an active tenant_members row in the target
// tenant grants access (this is what makes cross-tenant browsing
// work for non-superusers added via PR 3's member management).
//
// Lookup errors are treated as "not a member" — the safest fallback
// that doesn't expose other tenants on a transient DB hiccup.
func IsTenantAccessible(
ctx context.Context,
user *types.User,
targetTenantID uint64,
memberService interfaces.TenantMemberService,
cfg *config.Config,
) bool {
if user == nil || targetTenantID == 0 {
return false
}
if user.TenantID == targetTenantID {
return true
}
if cfg != nil && cfg.Tenant != nil && cfg.Tenant.EnableCrossTenantAccess && user.CanAccessAllTenants {
return true
}
if memberService == nil {
return false
}
m, err := memberService.GetMembership(ctx, user.ID, targetTenantID)
if err != nil || m == nil {
return false
}
return m.Status == types.TenantMemberStatusActive
}
// RequireCrossTenantAccess gates a route on the caller being an
// org-level superuser. Used by /tenants/all, /tenants/search,
// POST /tenants, GET /tenants — endpoints that operate across tenants
// rather than inside one.
//
// Unlike RequireRole this is NOT modulated by cfg.Tenant.EnableRBAC:
// cross-tenant operations are always sensitive regardless of whether
// per-tenant RBAC is being enforced, so we never log-and-pass.
func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
// First the cluster-wide flag — if it's off, nobody gets through,
// not even users with CanAccessAllTenants=true. This mirrors the
// "must require BOTH" rule that previously lived in tenant.go.
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
uid, _ := types.UserIDFromContext(ctx)
logger.Warnf(ctx,
"[rbac] cross-tenant route blocked (EnableCrossTenantAccess=false): user=%s path=%s",
uid, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: cross-tenant access is disabled",
})
c.Abort()
return
}
u, ok := ctx.Value(types.UserContextKey).(*types.User)
if !ok || u == nil || !u.CanAccessAllTenants {
uid, _ := types.UserIDFromContext(ctx)
logger.Warnf(ctx,
"[rbac] cross-tenant route blocked (not a superuser): user=%s path=%s",
uid, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Forbidden: insufficient permissions for cross-tenant operation",
})
c.Abort()
return
}
c.Next()
}
}
// RequirePathTenantMatch gates a route on the URL :id matching the
// caller's active tenant context. Cross-tenant superusers bypass the
// match because their X-Tenant-ID switch was already vetted by the
// auth middleware.
//
// The router places this on the /tenants/:id group so every per-tenant
// endpoint (GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey /
// member management / leave) shares the same check, replacing what was
// previously a copy-pasted block in each handler.
//
// Reads :id off c.Param. If the param is missing or non-numeric the
// request is rejected as 400 — the route can't have meaningfully
// matched without it.
func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
ctx := c.Request.Context()
raw := strings.TrimSpace(c.Param("id"))
if raw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant id is required"})
c.Abort()
return
}
pathTenantID, err := strconv.ParseUint(raw, 10, 64)
if err != nil || pathTenantID == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant id must be a positive integer"})
c.Abort()
return
}
ctxTenantID, ok := types.TenantIDFromContext(ctx)
if !ok || ctxTenantID == 0 {
// Auth middleware should always have set this; if not we
// fail closed rather than silently treating "no context" as
// a match.
logger.Warnf(ctx, "[rbac] path-tenant-match: no tenant in ctx, path=%s", c.Request.URL.Path)
c.JSON(http.StatusUnauthorized, gin.H{"error": "tenant context missing"})
c.Abort()
return
}
if pathTenantID == ctxTenantID {
c.Next()
return
}
if IsCrossTenantSuperuser(ctx, cfg) {
c.Next()
return
}
uid, _ := types.UserIDFromContext(ctx)
logger.Warnf(ctx,
"[rbac] path-tenant-match rejected: user=%s ctx_tenant=%d path_tenant=%d path=%s",
uid, ctxTenantID, pathTenantID, c.Request.URL.Path)
c.JSON(http.StatusForbidden, gin.H{
"error": "Access denied: URL tenant does not match the active tenant",
})
c.Abort()
}
}
+291
View File
@@ -0,0 +1,291 @@
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"
)
// access_test.go covers the four exported helpers in access.go:
// IsCrossTenantSuperuser, IsTenantAccessible, RequireCrossTenantAccess,
// RequirePathTenantMatch. The shapes are similar — feature-flag +
// per-user attribute combinations — so the tests are organised around
// the truth-table for each helper rather than per-handler scenarios.
// cfgCrossTenant returns a config with the cluster-wide
// EnableCrossTenantAccess flag set as requested. EnableRBAC is left at
// its zero value because none of these helpers consult it directly —
// the role middleware does.
func cfgCrossTenant(enabled bool) *config.Config {
return &config.Config{Tenant: &config.TenantConfig{EnableCrossTenantAccess: enabled}}
}
// ---------- IsCrossTenantSuperuser ----------
func TestIsCrossTenantSuperuser_NilCfgRejects(t *testing.T) {
ctx := context.WithValue(context.Background(), types.UserContextKey,
&types.User{ID: "u1", CanAccessAllTenants: true})
if IsCrossTenantSuperuser(ctx, nil) {
t.Fatalf("nil cfg must reject (no flag implies no cross-tenant access)")
}
}
func TestIsCrossTenantSuperuser_FlagOffRejectsEvenWithAttribute(t *testing.T) {
// The user attribute alone is not enough — by design. This is the
// "stale claim revocation" guarantee: flipping the cluster flag off
// disables every CanAccessAllTenants user without a re-issue.
ctx := context.WithValue(context.Background(), types.UserContextKey,
&types.User{ID: "u1", CanAccessAllTenants: true})
if IsCrossTenantSuperuser(ctx, cfgCrossTenant(false)) {
t.Fatalf("flag off must reject even when User.CanAccessAllTenants=true")
}
}
func TestIsCrossTenantSuperuser_FlagOnNoAttributeRejects(t *testing.T) {
ctx := context.WithValue(context.Background(), types.UserContextKey,
&types.User{ID: "u1", CanAccessAllTenants: false})
if IsCrossTenantSuperuser(ctx, cfgCrossTenant(true)) {
t.Fatalf("ordinary user must not pass even when flag is on")
}
}
func TestIsCrossTenantSuperuser_BothAllow(t *testing.T) {
ctx := context.WithValue(context.Background(), types.UserContextKey,
&types.User{ID: "u1", CanAccessAllTenants: true})
if !IsCrossTenantSuperuser(ctx, cfgCrossTenant(true)) {
t.Fatalf("flag on + attribute true must allow")
}
}
func TestIsCrossTenantSuperuser_NoUserInCtxRejects(t *testing.T) {
// Defensive: a context lacking UserContextKey should never be
// promoted. Returning false rather than panicking keeps the caller
// (auth.go fast paths) safe to use even before user resolution.
if IsCrossTenantSuperuser(context.Background(), cfgCrossTenant(true)) {
t.Fatalf("missing user must reject")
}
}
// ---------- IsTenantAccessible ----------
func TestIsTenantAccessible_HomeTenantAlwaysAllows(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1}
// Even with no member service and the cross-tenant flag off, a user
// reaching their own tenant is fine. Home tenant is the cheapest
// fast path.
if !IsTenantAccessible(context.Background(), user, 1, nil, cfgCrossTenant(false)) {
t.Fatalf("home tenant must allow regardless of other inputs")
}
}
func TestIsTenantAccessible_NilUserRejects(t *testing.T) {
if IsTenantAccessible(context.Background(), nil, 1, nil, cfgCrossTenant(true)) {
t.Fatalf("nil user must reject (defensive)")
}
}
func TestIsTenantAccessible_ZeroTargetRejects(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1}
if IsTenantAccessible(context.Background(), user, 0, nil, cfgCrossTenant(true)) {
t.Fatalf("zero target tenant must reject")
}
}
func TestIsTenantAccessible_SuperuserPathRequiresFlag(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1, CanAccessAllTenants: true}
// With flag OFF, the superuser attribute alone must NOT grant
// cross-tenant access — same revocation rule as
// IsCrossTenantSuperuser.
if IsTenantAccessible(context.Background(), user, 99, nil, cfgCrossTenant(false)) {
t.Fatalf("superuser without cluster flag must reject cross-tenant target")
}
// With the flag ON, no membership lookup is needed — the user can
// reach any tenant.
if !IsTenantAccessible(context.Background(), user, 99, nil, cfgCrossTenant(true)) {
t.Fatalf("superuser with cluster flag must allow without membership lookup")
}
}
func TestIsTenantAccessible_ActiveMembershipAllows(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1}
ms := newFakeMemberService()
ms.seedActive("u1", 99, types.TenantRoleContributor)
if !IsTenantAccessible(context.Background(), user, 99, ms, cfgCrossTenant(false)) {
t.Fatalf("active membership must allow even with flag off and no superuser")
}
}
func TestIsTenantAccessible_NoMembershipRejects(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1}
ms := newFakeMemberService() // empty
if IsTenantAccessible(context.Background(), user, 99, ms, cfgCrossTenant(true)) {
t.Fatalf("no membership and not superuser must reject")
}
}
func TestIsTenantAccessible_LookupErrorRejects(t *testing.T) {
// A DB hiccup must NOT silently grant access; the safest behaviour
// is "treat as no membership". The X-Tenant-ID gate in auth.go
// relies on this — failing closed prevents tenant-bleed during
// transient outages.
user := &types.User{ID: "u1", TenantID: 1}
ms := newFakeMemberService()
ms.failGet = errors.New("db down")
if IsTenantAccessible(context.Background(), user, 99, ms, cfgCrossTenant(true)) {
t.Fatalf("lookup error must reject (fail closed)")
}
}
func TestIsTenantAccessible_NilMemberServiceRejectsNonHome(t *testing.T) {
user := &types.User{ID: "u1", TenantID: 1}
if IsTenantAccessible(context.Background(), user, 99, nil, cfgCrossTenant(false)) {
t.Fatalf("no member service + non-home tenant must reject")
}
}
// ---------- RequireCrossTenantAccess ----------
func runCrossTenantHandler(cfg *config.Config, user *types.User) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
if user != nil {
ctx := context.WithValue(c.Request.Context(), types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
c.Request = c.Request.WithContext(ctx)
}
c.Next()
})
r.GET("/cross", RequireCrossTenantAccess(cfg), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/cross", nil)
r.ServeHTTP(w, req)
return w
}
func TestRequireCrossTenantAccess_FlagOffBlocksEveryone(t *testing.T) {
w := runCrossTenantHandler(cfgCrossTenant(false),
&types.User{ID: "u1", CanAccessAllTenants: true})
if w.Code != http.StatusForbidden {
t.Fatalf("flag off must 403 even for superuser, got %d", w.Code)
}
}
func TestRequireCrossTenantAccess_FlagOnNoAttributeBlocks(t *testing.T) {
w := runCrossTenantHandler(cfgCrossTenant(true),
&types.User{ID: "u1", CanAccessAllTenants: false})
if w.Code != http.StatusForbidden {
t.Fatalf("ordinary user must 403 even with flag on, got %d", w.Code)
}
}
func TestRequireCrossTenantAccess_BothAllow(t *testing.T) {
w := runCrossTenantHandler(cfgCrossTenant(true),
&types.User{ID: "u1", CanAccessAllTenants: true})
if w.Code != http.StatusOK {
t.Fatalf("flag + superuser must allow, got %d", w.Code)
}
}
func TestRequireCrossTenantAccess_NoUserBlocks(t *testing.T) {
w := runCrossTenantHandler(cfgCrossTenant(true), nil)
if w.Code != http.StatusForbidden {
t.Fatalf("missing user must 403, got %d", w.Code)
}
}
// ---------- RequirePathTenantMatch ----------
func runPathTenantHandler(
cfg *config.Config, ctxTenantID uint64, user *types.User, urlPath string,
) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
ctx := c.Request.Context()
if ctxTenantID != 0 {
ctx = context.WithValue(ctx, types.TenantIDContextKey, ctxTenantID)
}
if user != nil {
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
}
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.GET("/tenants/:id", RequirePathTenantMatch(cfg), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, urlPath, nil)
r.ServeHTTP(w, req)
return w
}
func TestRequirePathTenantMatch_MatchAllows(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(false), 7, nil, "/tenants/7")
if w.Code != http.StatusOK {
t.Fatalf("matching :id must allow, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_MismatchRejects(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(false), 7, nil, "/tenants/9")
if w.Code != http.StatusForbidden {
t.Fatalf("mismatch must 403, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_SuperuserBypassesMismatch(t *testing.T) {
// Pinned regression: this is the same carve-out
// resolveTenantIDFromPath used to enforce in tenant_member.go.
// Both flag and attribute must be set; either alone must reject
// (covered by the next test).
w := runPathTenantHandler(cfgCrossTenant(true), 7,
&types.User{ID: "su1", CanAccessAllTenants: true},
"/tenants/9")
if w.Code != http.StatusOK {
t.Fatalf("superuser must bypass mismatch with flag on, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_SuperuserNeedsClusterFlag(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(false), 7,
&types.User{ID: "su1", CanAccessAllTenants: true},
"/tenants/9")
if w.Code != http.StatusForbidden {
t.Fatalf("superuser without flag must 403, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_MissingCtxTenantRejects(t *testing.T) {
// If the auth middleware never set TenantIDContextKey we fail
// closed — silently treating "no ctx" as a match would be a footgun
// the next time someone refactors the auth chain.
w := runPathTenantHandler(cfgCrossTenant(true), 0, nil, "/tenants/7")
if w.Code != http.StatusUnauthorized {
t.Fatalf("missing tenant ctx must 401, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_NonNumericIDRejects(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(true), 7, nil, "/tenants/abc")
if w.Code != http.StatusBadRequest {
t.Fatalf("non-numeric :id must 400, got %d", w.Code)
}
}
func TestRequirePathTenantMatch_ZeroIDRejects(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(true), 7, nil, "/tenants/0")
if w.Code != http.StatusBadRequest {
t.Fatalf(":id=0 must 400, got %d", w.Code)
}
}
+18 -18
View File
@@ -47,22 +47,20 @@ func isNoAuthAPI(path string, method string) bool {
return false
}
// canAccessTenant checks if a user can access a target tenant
func canAccessTenant(user *types.User, targetTenantID uint64, cfg *config.Config) bool {
// 1. 检查功能是否启用
if cfg == nil || cfg.Tenant == nil || !cfg.Tenant.EnableCrossTenantAccess {
return false
}
// 2. 检查用户权限
if !user.CanAccessAllTenants {
return false
}
// 3. 如果目标租户是用户自己的租户,允许访问
if user.TenantID == targetTenantID {
return true
}
// 4. 用户有跨租户权限,允许访问(具体验证在中间件中完成)
return true
// canAccessTenant kept as a thin shim so the call sites below stay
// readable. The real decision lives in IsTenantAccessible (access.go),
// which centralises the home-tenant / superuser / multi-tenant-member
// rules so the X-Tenant-ID gate, the tenant role guards, and the path
// match check all share one definition of "may this user touch this
// tenant".
func canAccessTenant(
ctx context.Context,
user *types.User,
targetTenantID uint64,
memberService interfaces.TenantMemberService,
cfg *config.Config,
) bool {
return IsTenantAccessible(ctx, user, targetTenantID, memberService, cfg)
}
// Auth 认证中间件
@@ -104,8 +102,10 @@ func Auth(
// 解析目标租户ID
parsedTenantID, err := strconv.ParseUint(tenantHeader, 10, 64)
if err == nil {
// 检查用户是否有跨租户访问权限
if canAccessTenant(user, parsedTenantID, cfg) {
// 检查用户是否有权限访问目标租户:自家租户、跨租户超管、或
// 有 active membership 行——三选一,由 IsTenantAccessible
// 统一判定。
if canAccessTenant(c.Request.Context(), user, parsedTenantID, memberService, cfg) {
// 验证目标租户是否存在
targetTenant, err := tenantService.GetTenantByID(c.Request.Context(), parsedTenantID)
if err == nil && targetTenant != nil {
+6 -15
View File
@@ -73,7 +73,7 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
c.Next()
return
}
if isCrossTenantSuperuser(ctx) {
if IsCrossTenantSuperuser(ctx, cfg) {
c.Next()
return
}
@@ -132,7 +132,7 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con
}
// 2. Cross-tenant superuser bypass — same reasoning as RequireRole.
if isCrossTenantSuperuser(ctx) {
if IsCrossTenantSuperuser(ctx, cfg) {
c.Next()
return
}
@@ -197,19 +197,10 @@ 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
}
// isCrossTenantSuperuser was moved to access.go (renamed to
// IsCrossTenantSuperuser, exported, and made flag-aware) so the same
// helper backs the X-Tenant-ID gate in auth.go and the RequireRole /
// RequireOwnershipOrRole guards above.
// warnOnNilConfig emits a one-shot startup warning when a guard is
// constructed with a nil-or-incomplete config. nil cfg makes
+13 -2
View File
@@ -43,6 +43,17 @@ func cfgRBAC(enabled bool) *config.Config {
return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: enabled}}
}
// cfgRBACWithCrossTenant returns a config with both per-tenant RBAC
// enforcement AND the cluster-wide cross-tenant access flag enabled.
// IsCrossTenantSuperuser requires BOTH to honour the User attribute,
// so cross-tenant superuser tests need this rather than plain cfgRBAC.
func cfgRBACWithCrossTenant(enabled bool) *config.Config {
return &config.Config{Tenant: &config.TenantConfig{
EnableRBAC: enabled,
EnableCrossTenantAccess: true,
}}
}
// ---------- RequireRole ----------
func TestRequireRole_AllowsAtMin(t *testing.T) {
@@ -111,7 +122,7 @@ func TestRequireRole_CrossTenantSuperuserBypass(t *testing.T) {
c.Next()
})
router.GET("/protected",
RequireRole(types.TenantRoleOwner, cfgRBAC(true)),
RequireRole(types.TenantRoleOwner, cfgRBACWithCrossTenant(true)),
func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) },
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
@@ -264,7 +275,7 @@ func TestRequireOwnershipOrRole_CrossTenantSuperuserBypass(t *testing.T) {
c.Next()
})
router.GET("/protected",
RequireOwnershipOrRole(types.TenantRoleOwner, lookup, cfgRBAC(true)),
RequireOwnershipOrRole(types.TenantRoleOwner, lookup, cfgRBACWithCrossTenant(true)),
func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) },
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)