Files
Enterprise-Knowledge-Base/internal/middleware/access.go
T
wizardchen 2082b63951 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).
2026-05-18 17:28:58 +08:00

191 lines
6.8 KiB
Go

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()
}
}