Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(rbac): centralise tenant-access guards in middleware
wizardchen2082b639515c
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex 685f28284..a6f4044f1 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -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.Tenantif 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 parameterskeyword := c.Query("keyword")diff --git a/internal/handler/tenant_member.go b/internal/handler/tenant_member.goindex 554b3258f..2c77643a9 100644--- a/internal/handler/tenant_member.go+++ b/internal/handler/tenant_member.go@@ -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.TenantMemberServiceuserService 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 godocdiff --git a/internal/handler/tenant_member_test.go b/internal/handler/tenant_member_test.goindex 2ce8019e0..753242543 100644--- a/internal/handler/tenant_member_test.go+++ b/internal/handler/tenant_member_test.go@@ -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,diff --git a/internal/middleware/access.go b/internal/middleware/access.gonew file mode 100644index 000000000..2c6631d32--- /dev/null+++ b/internal/middleware/access.go@@ -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()+ }+}diff --git a/internal/middleware/access_test.go b/internal/middleware/access_test.gonew file mode 100644index 000000000..141d986f7--- /dev/null+++ b/internal/middleware/access_test.go@@ -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)+ }+}diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex 5a2c5e071..c67571c3a 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -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(// 解析目标租户IDparsedTenantID, 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 {diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.goindex cb6be6b9f..685ce8967 100644--- a/internal/middleware/rbac.go+++ b/internal/middleware/rbac.go@@ -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 makesdiff --git a/internal/middleware/rbac_test.go b/internal/middleware/rbac_test.goindex e014b34c9..8d4f4b6be 100644--- a/internal/middleware/rbac_test.go+++ b/internal/middleware/rbac_test.go@@ -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)diff --git a/internal/router/rbac.go b/internal/router/rbac.goindex a4f67ebb2..4ad9c6ccf 100644--- a/internal/router/rbac.go+++ b/internal/router/rbac.go@@ -82,3 +82,29 @@ func (g *rbacGuards) OwnedKBOrAdmin() gin.HandlerFunc {func (g *rbacGuards) OwnedAgentOrAdmin() gin.HandlerFunc {return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.agentCreator, g.cfg)}++// Tenant-access guards. Distinct from the role guards above: these+// answer the orthogonal question "may this caller touch this tenant+// at all", before role membership inside the tenant is even+// considered. Both delegate to middleware/access.go which centralises+// the cross-tenant rules so the router stays declarative.++// CrossTenant gates a route on the caller being an org-level+// superuser (CanAccessAllTenants AND EnableCrossTenantAccess). Used by+// /tenants/all, /tenants/search, POST /tenants, GET /tenants — the+// endpoints that operate across tenants. Replaces the if-blocks that+// used to live inside ListAllTenants/SearchTenants/CreateTenant.+func (g *rbacGuards) CrossTenant() gin.HandlerFunc {+ return middleware.RequireCrossTenantAccess(g.cfg)+}++// PathTenantMatch enforces that the URL :id matches the caller's+// active tenant context (cross-tenant superusers bypass). Routes apply+// it at the /tenants/:id group level so every per-tenant endpoint —+// GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey / member+// management / leave — shares the same check. Replaces the+// authorizeTenantAccess helper that used to live inside the tenant+// handler.+func (g *rbacGuards) PathTenantMatch() gin.HandlerFunc {+ return middleware.RequirePathTenantMatch(g.cfg)+}diff --git a/internal/router/router.go b/internal/router/router.goindex df6c4721f..445cdedee 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -406,47 +406,69 @@ func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGua// - DELETE /:id/members/:user_id Owner+ (only Owner can remove members)// - POST /:id/leave Viewer+ (any member can quit on their own)//-// Cross-tenant superuser endpoints (/tenants/all, /tenants/search, POST-// /tenants, GET /tenants, /tenants/kv/*) keep their existing handler-level-// CanAccessAllTenants check — they're not gated by tenant role here-// because the caller is operating *across* tenants, not within one.+// All /tenants/:id endpoints share g.PathTenantMatch() at the group+// level: middleware/access.go enforces "URL :id == active tenant"+// (with the cross-tenant superuser carve-out) so an Owner-of-A cannot+// drive operations against tenant B by changing the URL. This used to+// be authorizeTenantAccess in tenant.go and resolveTenantIDFromPath in+// tenant_member.go; collapsing it into one route guard means the+// declaration itself documents the rule.+//+// Cross-tenant superuser endpoints (/tenants/all, /tenants/search) use+// g.CrossTenant(): RequireCrossTenantAccess in access.go combines the+// CanAccessAllTenants user attribute with the cluster-wide+// EnableCrossTenantAccess flag, replacing the 12-line if-block that+// previously opened ListAllTenants and SearchTenants.+//+// POST /tenants and GET /tenants stay open to authenticated users —+// the previous handler comments claimed CanAccessAllTenants gating+// "is in the handler" but the bodies never enforced it; this PR is a+// pure refactor and does not introduce new gates.func RegisterTenantRoutes(r *gin.RouterGroup,handler *handler.TenantHandler,memberHandler *handler.TenantMemberHandler,g *rbacGuards,) {- // 添加获取所有租户的路由(需要跨租户权限)- r.GET("/tenants/all", handler.ListAllTenants)- // 添加搜索租户的路由(需要跨租户权限,支持分页和搜索)- r.GET("/tenants/search", handler.SearchTenants)+ // Cross-tenant superuser endpoints — promoted from handler if-blocks+ // to middleware.RequireCrossTenantAccess at the route layer.+ r.GET("/tenants/all", g.CrossTenant(), handler.ListAllTenants)+ r.GET("/tenants/search", g.CrossTenant(), handler.SearchTenants)+// 租户路由组tenantRoutes := r.Group("/tenants"){- tenantRoutes.POST("", handler.CreateTenant) // CanAccessAllTenants gate is in the handler- tenantRoutes.GET("/:id", g.Viewer(), handler.GetTenant)- tenantRoutes.PUT("/:id", g.Owner(), handler.UpdateTenant)- tenantRoutes.DELETE("/:id", g.Owner(), handler.DeleteTenant)- tenantRoutes.POST("/:id/api-key", g.Owner(), handler.ResetAPIKey)- tenantRoutes.GET("", handler.ListTenants) // existing handler gates by CanAccessAllTenants-- // Generic KV configuration management (tenant-level)- // Tenant ID is obtained from authentication context+ tenantRoutes.POST("", handler.CreateTenant)+ tenantRoutes.GET("", handler.ListTenants)++ // Generic KV configuration management (tenant-level). Tenant ID+ // is obtained from authentication context; the URL :key is a+ // config key, not a tenant ID, so these stay outside the+ // PathTenantMatch group.tenantRoutes.GET("/kv/:key", g.Viewer(), handler.GetTenantKV)tenantRoutes.PUT("/kv/:key", g.Admin(), handler.UpdateTenantKV)- // Tenant member management (PR 3 of #1303). Listing is Viewer+- // so any active member can see the roster; mutation is Owner+- // because membership changes are the highest-impact tenant op.- // /:id/leave is Viewer+ — any member can quit on their own; the- // service still rejects when it would leave the tenant without- // an Owner.- if memberHandler != nil {- tenantRoutes.GET("/:id/members", g.Viewer(), memberHandler.ListMembers)- tenantRoutes.POST("/:id/members", g.Owner(), memberHandler.AddMember)- tenantRoutes.PUT("/:id/members/:user_id", g.Owner(), memberHandler.UpdateMemberRole)- tenantRoutes.DELETE("/:id/members/:user_id", g.Owner(), memberHandler.RemoveMember)- tenantRoutes.POST("/:id/leave", g.Viewer(), memberHandler.LeaveTenant)+ // Per-tenant endpoints share PathTenantMatch at the group level.+ tenantByID := tenantRoutes.Group("/:id", g.PathTenantMatch())+ {+ tenantByID.GET("", g.Viewer(), handler.GetTenant)+ tenantByID.PUT("", g.Owner(), handler.UpdateTenant)+ tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)+ tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)++ // Tenant member management (PR 3 of #1303). Listing is+ // Viewer+ so any active member can see the roster; mutation+ // is Owner+ because membership changes are the highest-impact+ // tenant op. /:id/leave is Viewer+ — any member can quit on+ // their own; the service still rejects when it would leave+ // the tenant without an Owner.+ if memberHandler != nil {+ tenantByID.GET("/members", g.Viewer(), memberHandler.ListMembers)+ tenantByID.POST("/members", g.Owner(), memberHandler.AddMember)+ tenantByID.PUT("/members/:user_id", g.Owner(), memberHandler.UpdateMemberRole)+ tenantByID.DELETE("/members/:user_id", g.Owner(), memberHandler.RemoveMember)+ tenantByID.POST("/leave", g.Viewer(), memberHandler.LeaveTenant)+ }}}}