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
+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 {