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")
+17 -53
View File
@@ -10,7 +10,6 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -27,31 +26,28 @@ import (
// is independent and MUST be cross-checked: a user who is Owner of
// tenant A could otherwise POST /tenants/B/members and have the role
// gate happily accept their tenant-A role for an operation that targets
// tenant B. resolveTenantIDFromPath performs that check below; every
// endpoint goes through it.
//
// Cross-tenant superusers (CanAccessAllTenants + EnableCrossTenantAccess)
// bypass the cross-check the same way RequireRole does — same reasoning
// as middleware/rbac.go.
// tenant B. That cross-check now lives in
// middleware.RequirePathTenantMatch (mounted at the /tenants/:id route
// group); by the time a request reaches one of the methods below, :id
// is guaranteed to either match the active tenant or carry a
// cross-tenant superuser bypass.
type TenantMemberHandler struct {
memberService interfaces.TenantMemberService
userService interfaces.UserService
cfg *config.Config
}
// NewTenantMemberHandler wires the dependencies. PR 1 already provides
// both services through the dig container; we just consume them. cfg is
// required so we can honour the cross-tenant superuser escape hatch the
// same way middleware/rbac.go does.
// both services through the dig container; we just consume them. The
// previous *config.Config argument was removed once
// middleware.RequirePathTenantMatch took over the cross-tenant
// superuser carve-out.
func NewTenantMemberHandler(
memberService interfaces.TenantMemberService,
userService interfaces.UserService,
cfg *config.Config,
) *TenantMemberHandler {
return &TenantMemberHandler{
memberService: memberService,
userService: userService,
cfg: cfg,
}
}
@@ -88,50 +84,18 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
return v, true
}
// resolveTenantIDFromPath parses :id and verifies it matches the
// caller's active tenant context, so an Owner-in-tenant-A can't drive
// operations on tenant B just by changing the URL. Cross-tenant
// superusers are exempt — same carve-out RequireRole grants.
// resolveTenantIDFromPath parses :id from the URL. The cross-check
// "URL :id must match the active tenant context (with a cross-tenant
// superuser carve-out)" used to live here but moved to
// middleware.RequirePathTenantMatch, mounted on the /tenants/:id
// route group. By the time a handler method calls this, the URL has
// already been authorised against the caller's tenant context.
//
// Returns the validated tenant ID and true; returns (0, false) after
// Returns the parsed tenant ID and true; returns (0, false) after
// having written the appropriate error to the gin context, in which
// case the handler must `return` immediately.
func (h *TenantMemberHandler) resolveTenantIDFromPath(c *gin.Context) (uint64, bool) {
pathTenantID, ok := parseTenantIDFromPath(c)
if !ok {
return 0, false
}
ctx := c.Request.Context()
ctxTenantID, hasCtxTenant := types.TenantIDFromContext(ctx)
if !hasCtxTenant {
// 没有租户上下文意味着 auth 中间件没有把人放进来;这是错误的链路,
// 兜底直接拒绝避免后续以零值租户跑业务逻辑。
c.Error(apperrors.NewUnauthorizedError("tenant context missing"))
return 0, false
}
if pathTenantID == ctxTenantID {
return pathTenantID, true
}
// Cross-tenant superuser carve-out (mirrors middleware/rbac.go).
// We require BOTH the feature flag and the user attribute: just
// reading user.CanAccessAllTenants without checking the cluster-wide
// EnableCrossTenantAccess would let dormant flags grant escalation.
if h.cfg != nil && h.cfg.Tenant != nil && h.cfg.Tenant.EnableCrossTenantAccess {
if u, ok := ctx.Value(types.UserContextKey).(*types.User); ok &&
u != nil && u.CanAccessAllTenants {
return pathTenantID, true
}
}
logger.Warnf(ctx,
"[rbac] tenant member endpoint rejected: caller tenant=%d, url tenant=%d, path=%s",
ctxTenantID, pathTenantID, c.Request.URL.Path)
c.Error(apperrors.NewForbiddenError(
"Access denied: URL tenant does not match the active tenant"))
return 0, false
return parseTenantIDFromPath(c)
}
// ListMembers godoc
+32 -17
View File
@@ -13,6 +13,7 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
@@ -83,29 +84,40 @@ func (s *stubMemberUserService) GetUsersByIDs(ctx context.Context, ids []string)
return out, nil
}
// newTestMemberHandler builds a TenantMemberHandler with a minimal
// config that enables the cross-tenant superuser carve-out by default
// (so tests can flip user.CanAccessAllTenants without having to also
// wire the feature flag). Tests that want to assert the carve-out is
// gated off should build the handler with their own cfg.
// newTestMemberHandler builds a TenantMemberHandler with no extra
// dependencies. The cross-tenant URL check moved to
// middleware.RequirePathTenantMatch in PR 4; tests mount that
// middleware via memberTestRouter rather than threading a cfg through
// the handler.
func newTestMemberHandler(ms interfaces.TenantMemberService, us interfaces.UserService) *TenantMemberHandler {
return NewTenantMemberHandler(ms, us, &config.Config{
Tenant: &config.TenantConfig{EnableCrossTenantAccess: true},
})
return NewTenantMemberHandler(ms, us)
}
// memberTestRouter wires the handler with the same errorCapture middleware
// production uses, so c.Error() shows up as a real HTTP status in the
// recorder.
// recorder. It also mounts middleware.RequirePathTenantMatch on the
// /tenants/:id group, mirroring router.RegisterTenantRoutes — that's
// where the URL-vs-active-tenant cross-check now lives, and the
// per-handler tests below assert it through this layer.
func memberTestRouter(h *TenantMemberHandler) *gin.Engine {
return memberTestRouterWithCfg(h, &config.Config{
Tenant: &config.TenantConfig{EnableCrossTenantAccess: true},
})
}
// memberTestRouterWithCfg lets a test choose its own config (e.g.
// disabling the cross-tenant superuser carve-out) so it can assert how
// RequirePathTenantMatch behaves under different cluster flags.
func memberTestRouterWithCfg(h *TenantMemberHandler, cfg *config.Config) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture()) // defined in auth_register_invite_only_test.go
r.GET("/tenants/:id/members", h.ListMembers)
r.POST("/tenants/:id/members", h.AddMember)
r.PUT("/tenants/:id/members/:user_id", h.UpdateMemberRole)
r.DELETE("/tenants/:id/members/:user_id", h.RemoveMember)
r.POST("/tenants/:id/leave", h.LeaveTenant)
tenantByID := r.Group("/tenants/:id", middleware.RequirePathTenantMatch(cfg))
tenantByID.GET("/members", h.ListMembers)
tenantByID.POST("/members", h.AddMember)
tenantByID.PUT("/members/:user_id", h.UpdateMemberRole)
tenantByID.DELETE("/members/:user_id", h.RemoveMember)
tenantByID.POST("/leave", h.LeaveTenant)
return r
}
@@ -626,11 +638,14 @@ func TestTenantMember_SuperuserBypassRequiresFeatureFlag(t *testing.T) {
return nil, nil
},
}
// Explicitly build without the flag.
h := NewTenantMemberHandler(ms, &stubMemberUserService{}, &config.Config{
// Build the router with the flag explicitly off — the carve-out
// now lives in middleware.RequirePathTenantMatch, which the router
// helper mounts.
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
router := memberTestRouterWithCfg(h, &config.Config{
Tenant: &config.TenantConfig{EnableCrossTenantAccess: false},
})
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodGet, "/tenants/5/members", nil,
w := doJSONWithCtx(t, router, http.MethodGet, "/tenants/5/members", nil,
memberCtxOpts{
callerID: "u-superuser",
tenantID: 1,