refactor(tenant_member): simplify tenant ID resolution in handlers

Removed the resolveTenantIDFromPath method from TenantMemberHandler, consolidating tenant ID parsing directly into the ListMembers, AddMember, UpdateMemberRole, and RemoveMember methods. This change streamlines the code by utilizing the existing parseTenantIDFromPath function, enhancing readability and reducing redundancy. No functional changes were introduced, maintaining the existing behavior of tenant ID resolution.
This commit is contained in:
wizardchen
2026-05-14 13:32:51 +08:00
committed by lyingbug
parent 2082b63951
commit 9e1c2c2546
4 changed files with 87 additions and 49 deletions
+5 -19
View File
@@ -84,20 +84,6 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
return v, true
}
// 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 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) {
return parseTenantIDFromPath(c)
}
// ListMembers godoc
// @Summary 列出租户成员
// @Description 返回当前租户内全部 active 成员(含每位成员的角色、邮箱、头像)
@@ -109,7 +95,7 @@ func (h *TenantMemberHandler) resolveTenantIDFromPath(c *gin.Context) (uint64, b
// @Router /tenants/{id}/members [get]
func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := h.resolveTenantIDFromPath(c)
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
@@ -177,7 +163,7 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
// @Router /tenants/{id}/members [post]
func (h *TenantMemberHandler) AddMember(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := h.resolveTenantIDFromPath(c)
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
@@ -273,7 +259,7 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) {
// @Router /tenants/{id}/members/{user_id} [put]
func (h *TenantMemberHandler) UpdateMemberRole(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := h.resolveTenantIDFromPath(c)
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
@@ -324,7 +310,7 @@ func (h *TenantMemberHandler) UpdateMemberRole(c *gin.Context) {
// @Router /tenants/{id}/members/{user_id} [delete]
func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := h.resolveTenantIDFromPath(c)
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
@@ -366,7 +352,7 @@ func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
// @Router /tenants/{id}/leave [post]
func (h *TenantMemberHandler) LeaveTenant(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := h.resolveTenantIDFromPath(c)
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
return
}
+18 -13
View File
@@ -2,11 +2,11 @@ package middleware
import (
"context"
"net/http"
"strconv"
"strings"
"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"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -38,6 +38,15 @@ import (
// 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.
//
// Rejections are reported via c.Error(*apperrors.AppError) + c.Abort(),
// not c.JSON: this keeps the response shape consistent with the
// {success,error:{code,message,details}} envelope that ErrorHandler
// renders for the rest of the API. The handler-level checks these
// guards replaced (authorizeTenantAccess, resolveTenantIDFromPath,
// ListAllTenants/SearchTenants if-blocks) all used that envelope, so
// preserving it avoids breaking SDK / frontend consumers that key off
// `error.code`.
// IsCrossTenantSuperuser reports whether ctx carries a user that is
// authorised for cross-tenant access at this moment. Both the user
@@ -110,9 +119,7 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
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.Error(apperrors.NewForbiddenError("Cross-tenant access is disabled"))
c.Abort()
return
}
@@ -122,9 +129,8 @@ func RequireCrossTenantAccess(cfg *config.Config) gin.HandlerFunc {
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.Error(apperrors.NewForbiddenError(
"Insufficient permissions for cross-tenant operation"))
c.Abort()
return
}
@@ -150,13 +156,13 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
ctx := c.Request.Context()
raw := strings.TrimSpace(c.Param("id"))
if raw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant id is required"})
_ = c.Error(apperrors.NewValidationError("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.Error(apperrors.NewValidationError("tenant id must be a positive integer"))
c.Abort()
return
}
@@ -166,7 +172,7 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
// 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.Error(apperrors.NewUnauthorizedError("tenant context missing"))
c.Abort()
return
}
@@ -182,9 +188,8 @@ func RequirePathTenantMatch(cfg *config.Config) gin.HandlerFunc {
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.Error(apperrors.NewForbiddenError(
"Access denied: URL tenant does not match the active tenant"))
c.Abort()
}
}
+63
View File
@@ -2,12 +2,14 @@ package middleware
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
@@ -154,6 +156,10 @@ func TestIsTenantAccessible_NilMemberServiceRejectsNonHome(t *testing.T) {
func runCrossTenantHandler(cfg *config.Config, user *types.User) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
// ErrorHandler renders c.Error() into the standard envelope and
// sets the status from AppError.HTTPCode. Mounting it here mirrors
// the production router so the tests assert what real clients see.
r.Use(ErrorHandler())
r.Use(func(c *gin.Context) {
if user != nil {
ctx := context.WithValue(c.Request.Context(), types.UserContextKey, user)
@@ -209,6 +215,7 @@ func runPathTenantHandler(
) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(ErrorHandler()) // see runCrossTenantHandler for rationale
r.Use(func(c *gin.Context) {
ctx := c.Request.Context()
if ctxTenantID != 0 {
@@ -289,3 +296,59 @@ func TestRequirePathTenantMatch_ZeroIDRejects(t *testing.T) {
t.Fatalf(":id=0 must 400, got %d", w.Code)
}
}
// TestAccessMiddleware_ResponseEnvelope pins the wire format produced
// by RequireCrossTenantAccess and RequirePathTenantMatch when they
// reject. Both used to live in handlers that called
// c.Error(apperrors.NewForbiddenError(...)) and rendered through
// ErrorHandler — clients (frontend axios interceptor, Go SDK) key off
// `success` and `error.code`. If a future change drops c.Error in
// favour of a raw c.JSON, this test catches the regression.
func TestAccessMiddleware_ResponseEnvelope(t *testing.T) {
t.Run("RequireCrossTenantAccess_FlagOff", func(t *testing.T) {
w := runCrossTenantHandler(cfgCrossTenant(false),
&types.User{ID: "u1", CanAccessAllTenants: true})
assertEnvelope(t, w, http.StatusForbidden, apperrors.ErrForbidden)
})
t.Run("RequirePathTenantMatch_Mismatch", func(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(false), 7, nil, "/tenants/9")
assertEnvelope(t, w, http.StatusForbidden, apperrors.ErrForbidden)
})
t.Run("RequirePathTenantMatch_NonNumeric", func(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(true), 7, nil, "/tenants/abc")
// NewValidationError uses ErrValidation, not ErrBadRequest — both
// surface as HTTP 400 but the code in the body is ErrValidation.
assertEnvelope(t, w, http.StatusBadRequest, apperrors.ErrValidation)
})
t.Run("RequirePathTenantMatch_NoCtxTenant", func(t *testing.T) {
w := runPathTenantHandler(cfgCrossTenant(true), 0, nil, "/tenants/7")
assertEnvelope(t, w, http.StatusUnauthorized, apperrors.ErrUnauthorized)
})
}
func assertEnvelope(t *testing.T, w *httptest.ResponseRecorder, wantStatus int, wantCode apperrors.ErrorCode) {
t.Helper()
if w.Code != wantStatus {
t.Fatalf("status: got %d, want %d (body=%s)", w.Code, wantStatus, w.Body.String())
}
var body struct {
Success bool `json:"success"`
Error struct {
Code apperrors.ErrorCode `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("body is not the standard envelope: %v (body=%s)", err, w.Body.String())
}
if body.Success {
t.Fatalf("envelope success must be false on rejection, got body=%s", w.Body.String())
}
if body.Error.Code != wantCode {
t.Fatalf("envelope error.code: got %d, want %d (body=%s)",
body.Error.Code, wantCode, w.Body.String())
}
if body.Error.Message == "" {
t.Fatalf("envelope error.message must be non-empty, got body=%s", w.Body.String())
}
}
+1 -17
View File
@@ -47,22 +47,6 @@ func isNoAuthAPI(path string, method string) bool {
return false
}
// 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 认证中间件
func Auth(
tenantService interfaces.TenantService,
@@ -105,7 +89,7 @@ func Auth(
// 检查用户是否有权限访问目标租户:自家租户、跨租户超管、或
// 有 active membership 行——三选一,由 IsTenantAccessible
// 统一判定。
if canAccessTenant(c.Request.Context(), user, parsedTenantID, memberService, cfg) {
if IsTenantAccessible(c.Request.Context(), user, parsedTenantID, memberService, cfg) {
// 验证目标租户是否存在
targetTenant, err := tenantService.GetTenantByID(c.Request.Context(), parsedTenantID)
if err == nil && targetTenant != nil {