feat(tenant): 按租户隔离用户身份与后台权限
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/logging"
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -78,6 +79,11 @@ func Auth(jwtManager *auth.JWTManager, validate UserTokenValidatorFunc) gin.Hand
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !userTokenTenantMatches(c, claims.TenantID) {
|
||||
response.Unauthorized(c, "访问令牌不属于当前站点")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if validate != nil {
|
||||
if err := validate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
|
||||
if errors.Is(err, auth.ErrDependencyUnavailable) {
|
||||
@@ -114,6 +120,10 @@ func OptionalAuth(jwtManager *auth.JWTManager, validate UserTokenValidatorFunc)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if !userTokenTenantMatches(c, claims.TenantID) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if validate != nil {
|
||||
if err := validate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
|
||||
c.Next()
|
||||
@@ -132,26 +142,30 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
|
||||
// 1. 优先尝试管理员鉴权(Header Bearer 或 Admin Cookie)
|
||||
if tokenText, tokenSource := extractAdminToken(c); tokenText != "" {
|
||||
if claims, err := jwtManager.ParseSubject(tokenText, "access", "admin"); err == nil {
|
||||
username := claims.Phone
|
||||
passwordMustChange := false
|
||||
validAdmin := true
|
||||
if adminValidate != nil {
|
||||
tokenContext, err := adminValidate(c.Request.Context(), claims.UserID, claims.TokenVersion)
|
||||
if err != nil {
|
||||
RecordAdminAuthFailure(c, "invalid", tokenSource, 0, 0)
|
||||
validAdmin = false
|
||||
} else {
|
||||
username = tokenContext.Username
|
||||
passwordMustChange = tokenContext.PasswordMustChange
|
||||
if !adminTokenTenantMatches(c, claims.TenantID) {
|
||||
RecordAdminAuthFailure(c, "tenant_mismatch", tokenSource, 0, 0)
|
||||
} else {
|
||||
username := claims.Phone
|
||||
passwordMustChange := false
|
||||
validAdmin := true
|
||||
if adminValidate != nil {
|
||||
tokenContext, err := adminValidate(c.Request.Context(), claims.UserID, claims.TokenVersion)
|
||||
if err != nil {
|
||||
RecordAdminAuthFailure(c, "invalid", tokenSource, 0, 0)
|
||||
validAdmin = false
|
||||
} else {
|
||||
username = tokenContext.Username
|
||||
passwordMustChange = tokenContext.PasswordMustChange
|
||||
}
|
||||
}
|
||||
if validAdmin {
|
||||
c.Set(ContextAdminID, claims.UserID)
|
||||
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
|
||||
c.Set(ContextUsername, username)
|
||||
c.Set(ContextPasswordMustChange, passwordMustChange)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
if validAdmin {
|
||||
c.Set(ContextAdminID, claims.UserID)
|
||||
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
|
||||
c.Set(ContextUsername, username)
|
||||
c.Set(ContextPasswordMustChange, passwordMustChange)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,6 +189,11 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !userTokenTenantMatches(c, claims.TenantID) {
|
||||
response.Unauthorized(c, "访问令牌不属于当前站点")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if userValidate != nil {
|
||||
if err := userValidate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
|
||||
if errors.Is(err, auth.ErrDependencyUnavailable) {
|
||||
@@ -193,6 +212,14 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
|
||||
}
|
||||
}
|
||||
|
||||
func userTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool {
|
||||
requestTenantID := tenancy.IDFromContext(c.Request.Context())
|
||||
if tokenTenantID == 0 {
|
||||
return true
|
||||
}
|
||||
return requestTenantID > 0 && requestTenantID == tokenTenantID
|
||||
}
|
||||
|
||||
func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
tokenText, tokenSource := extractAdminToken(c)
|
||||
@@ -210,6 +237,12 @@ func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gi
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !adminTokenTenantMatches(c, claims.TenantID) {
|
||||
RecordAdminAuthFailure(c, "tenant_mismatch", tokenSource, 0, 0)
|
||||
response.Unauthorized(c, "后台访问令牌不属于当前站点")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Set(ContextAdminID, claims.UserID)
|
||||
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
|
||||
username := claims.Phone
|
||||
@@ -238,6 +271,14 @@ func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gi
|
||||
}
|
||||
}
|
||||
|
||||
func adminTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool {
|
||||
requestTenantID := tenancy.IDFromContext(c.Request.Context())
|
||||
if tokenTenantID == 0 {
|
||||
return true
|
||||
}
|
||||
return requestTenantID > 0 && requestTenantID == tokenTenantID
|
||||
}
|
||||
|
||||
type authFailureReasonCarrier interface {
|
||||
AuthFailureReason() string
|
||||
}
|
||||
|
||||
@@ -7,10 +7,19 @@ import (
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func useRequestTenant(tenantID uint64) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := tenancy.WithScope(c.Request.Context(), tenancy.Scope{TenantID: tenantID})
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAuthRejectsQueryToken(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
manager := auth.NewJWTManager("test-jwt-secret-for-query-token-rejection")
|
||||
@@ -63,3 +72,42 @@ func TestAuthRejectsRevokedUserToken(t *testing.T) {
|
||||
t.Fatalf("响应状态 = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAndAdminTokensRejectCrossTenantRequests(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
manager := auth.NewJWTManager("cross-tenant-auth-test-secret")
|
||||
userPair, err := manager.GenerateTenantPairWithVersion(1, "13800000000", "user", 1, 101)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adminPair, err := manager.GenerateTenantPairWithVersion(2, "admin", "admin", 1, 101)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
userEngine := gin.New()
|
||||
userEngine.Use(useRequestTenant(202))
|
||||
userEngine.GET("/protected", Auth(manager, nil), func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
userRequest := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||
userRequest.Header.Set("Authorization", "Bearer "+userPair.AccessToken)
|
||||
userResponse := httptest.NewRecorder()
|
||||
userEngine.ServeHTTP(userResponse, userRequest)
|
||||
if userResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("cross-tenant user token status = %d, want 401", userResponse.Code)
|
||||
}
|
||||
|
||||
adminEngine := gin.New()
|
||||
adminEngine.Use(useRequestTenant(202))
|
||||
adminEngine.GET("/protected", AdminAuth(manager, nil), func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
adminRequest := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||
adminRequest.Header.Set("Authorization", "Bearer "+adminPair.AccessToken)
|
||||
adminResponse := httptest.NewRecorder()
|
||||
adminEngine.ServeHTTP(adminResponse, adminRequest)
|
||||
if adminResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("cross-tenant admin token status = %d, want 401", adminResponse.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -89,7 +91,7 @@ func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string,
|
||||
if rdb == nil {
|
||||
return nil, errors.New("redis unavailable")
|
||||
}
|
||||
key := fmt.Sprintf("admin:perms:%d", adminID)
|
||||
key := adminPermissionCacheKey(c.Request.Context(), adminID)
|
||||
raw, err := rdb.Get(c.Request.Context(), key).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, nil // 缓存未命中,视为无权限
|
||||
@@ -103,3 +105,11 @@ func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string,
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
func adminPermissionCacheKey(ctx context.Context, adminID uint64) string {
|
||||
key := fmt.Sprintf("admin:perms:%d", adminID)
|
||||
if scope := tenancy.ScopeKey(ctx); scope != "" {
|
||||
key += ":" + scope
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
@@ -9,10 +9,22 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestAdminPermissionCacheKeyIncludesTenant(t *testing.T) {
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
if got := adminPermissionCacheKey(ctx, 7); got != "admin:perms:7:tenant:101" {
|
||||
t.Fatalf("tenant permission cache key = %q", got)
|
||||
}
|
||||
if got := adminPermissionCacheKey(context.Background(), 7); got != "admin:perms:7" {
|
||||
t.Fatalf("legacy permission cache key = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAnyPermission(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
|
||||
@@ -23,11 +23,15 @@ type TenantResolver interface {
|
||||
ResolveCode(ctx context.Context, code string) (*tenancy.Scope, error)
|
||||
}
|
||||
|
||||
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) gin.HandlerFunc {
|
||||
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger, defaultTenantCodes ...string) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
return func(c *gin.Context) { c.Next() }
|
||||
}
|
||||
production := config.IsProductionEnv(appEnv)
|
||||
defaultTenantCode := ""
|
||||
if len(defaultTenantCodes) > 0 {
|
||||
defaultTenantCode = strings.TrimSpace(defaultTenantCodes[0])
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
var (
|
||||
scope *tenancy.Scope
|
||||
@@ -42,9 +46,16 @@ func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) g
|
||||
if scope == nil && err == nil {
|
||||
scope, err = resolver.ResolveHost(c.Request.Context(), c.Request.Host)
|
||||
}
|
||||
host := sitecode.ExtractHost(c.Request.Host)
|
||||
if scope == nil && err == nil && defaultTenantCode != "" && sitecode.FromRequest(c) != "" {
|
||||
scope, err = resolver.ResolveCode(c.Request.Context(), defaultTenantCode)
|
||||
}
|
||||
if scope == nil && err == nil && !production && sitecode.IsLocalHost(host) && defaultTenantCode != "" {
|
||||
scope, err = resolver.ResolveCode(c.Request.Context(), defaultTenantCode)
|
||||
}
|
||||
if err != nil && logger != nil {
|
||||
logger.Warn("经营租户解析失败,按旧站点上下文继续",
|
||||
zap.String("host", sitecode.ExtractHost(c.Request.Host)),
|
||||
zap.String("host", host),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user