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
+14 -84
View File
@@ -27,31 +27,6 @@ type TenantHandler struct {
config *config.Config
}
// authorizeTenantAccess checks that the authenticated user owns the target tenant
// or has cross-tenant access privileges. Returns the current user on success.
func (h *TenantHandler) authorizeTenantAccess(c *gin.Context, targetTenantID uint64) (*types.User, bool) {
ctx := c.Request.Context()
user, ok := ctx.Value(types.UserContextKey).(*types.User)
if !ok || user == nil {
c.Error(errors.NewUnauthorizedError("Authentication required"))
return nil, false
}
if user.TenantID == targetTenantID {
return user, true
}
if h.config != nil && h.config.Tenant != nil && h.config.Tenant.EnableCrossTenantAccess && user.CanAccessAllTenants {
return user, true
}
logger.Warnf(ctx, "User %s (tenant %d) attempted to access tenant %d without permission",
user.ID, user.TenantID, targetTenantID)
c.Error(errors.NewForbiddenError("Access denied: you do not have permission to access this tenant"))
return nil, false
}
// NewTenantHandler creates a new tenant handler instance with the provided service
// Parameters:
// - service: An implementation of the TenantService interface for business logic
@@ -59,6 +34,14 @@ func (h *TenantHandler) authorizeTenantAccess(c *gin.Context, targetTenantID uin
// - config: Application configuration
//
// Returns a pointer to the newly created TenantHandler
//
// Note on RBAC: cross-tenant gating (CanAccessAllTenants /
// EnableCrossTenantAccess) and per-tenant path matching (URL :id ==
// active tenant) used to live in `authorizeTenantAccess` and the if
// blocks at the top of ListAllTenants / SearchTenants. Both moved to
// `middleware/access.go` (RequireCrossTenantAccess /
// RequirePathTenantMatch) and are wired in `router.go` so the handler
// stays focused on business logic.
func NewTenantHandler(service interfaces.TenantService, userService interfaces.UserService, kbService interfaces.KnowledgeBaseService, config *config.Config) *TenantHandler {
return &TenantHandler{
service: service,
@@ -142,10 +125,6 @@ func (h *TenantHandler) GetTenant(c *gin.Context) {
return
}
if _, ok := h.authorizeTenantAccess(c, id); !ok {
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
@@ -188,10 +167,6 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
return
}
if _, ok := h.authorizeTenantAccess(c, id); !ok {
return
}
var tenantData types.Tenant
if err := c.ShouldBindJSON(&tenantData); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
@@ -248,10 +223,6 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
return
}
if _, ok := h.authorizeTenantAccess(c, id); !ok {
return
}
logger.Infof(ctx, "Resetting API key for tenant, ID: %d", id)
apiKey, err := h.service.UpdateAPIKey(ctx, id)
if err != nil {
@@ -297,10 +268,6 @@ func (h *TenantHandler) DeleteTenant(c *gin.Context) {
return
}
if _, ok := h.authorizeTenantAccess(c, id); !ok {
return
}
logger.Infof(ctx, "Deleting tenant, ID: %d", id)
if err := h.service.DeleteTenant(ctx, id); err != nil {
@@ -361,28 +328,9 @@ func (h *TenantHandler) ListTenants(c *gin.Context) {
func (h *TenantHandler) ListAllTenants(c *gin.Context) {
ctx := c.Request.Context()
// Get current user from context
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to get current user: %v", err)
c.Error(errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error()))
return
}
// Check if cross-tenant access is enabled
if h.config == nil || h.config.Tenant == nil || !h.config.Tenant.EnableCrossTenantAccess {
logger.Warnf(ctx, "Cross-tenant access is disabled, user: %s", user.ID)
c.Error(errors.NewForbiddenError("Cross-tenant access is disabled"))
return
}
// Check if user has permission
if !user.CanAccessAllTenants {
logger.Warnf(ctx, "User %s attempted to list all tenants without permission", user.ID)
c.Error(errors.NewForbiddenError("Insufficient permissions to access all tenants"))
return
}
// Cross-tenant gating (CanAccessAllTenants + EnableCrossTenantAccess)
// is enforced at the route layer via middleware.RequireCrossTenantAccess
// (router.go). The handler stays focused on listing.
tenants, err := h.service.ListAllTenants(ctx)
if err != nil {
// Check if this is an application-specific error
@@ -422,27 +370,9 @@ func (h *TenantHandler) ListAllTenants(c *gin.Context) {
func (h *TenantHandler) SearchTenants(c *gin.Context) {
ctx := c.Request.Context()
// Get current user from context
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to get current user: %v", err)
c.Error(errors.NewUnauthorizedError("Failed to get user information").WithDetails(err.Error()))
return
}
// Check if cross-tenant access is enabled
if h.config == nil || h.config.Tenant == nil || !h.config.Tenant.EnableCrossTenantAccess {
logger.Warnf(ctx, "Cross-tenant access is disabled, user: %s", user.ID)
c.Error(errors.NewForbiddenError("Cross-tenant access is disabled"))
return
}
// Check if user has permission
if !user.CanAccessAllTenants {
logger.Warnf(ctx, "User %s attempted to search tenants without permission", user.ID)
c.Error(errors.NewForbiddenError("Insufficient permissions to access all tenants"))
return
}
// Cross-tenant gating is enforced at the route layer via
// middleware.RequireCrossTenantAccess (router.go); the handler only
// parses query params and delegates to the service.
// Parse query parameters
keyword := c.Query("keyword")