diff --git a/backend/internal/middleware/auth.go b/backend/internal/middleware/auth.go index 503ddb83..41de055a 100644 --- a/backend/internal/middleware/auth.go +++ b/backend/internal/middleware/auth.go @@ -8,6 +8,7 @@ import ( "hfb_sys/backend/internal/logging" "hfb_sys/backend/internal/modules/auth" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "hfb_sys/backend/pkg/response" @@ -217,7 +218,11 @@ func userTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool { if tokenTenantID == 0 { return true } - return requestTenantID > 0 && requestTenantID == tokenTenantID + if requestTenantID > 0 { + return requestTenantID == tokenTenantID + } + // 历史分销用户的 tenant_id 可能仍指向大锤,具体归属由令牌校验时的站点过滤确认。 + return sitecode.BoundSiteCodeFromContext(c.Request.Context()) != "" } func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gin.HandlerFunc { diff --git a/backend/internal/middleware/auth_test.go b/backend/internal/middleware/auth_test.go index b5cddf3a..9fa7bcae 100644 --- a/backend/internal/middleware/auth_test.go +++ b/backend/internal/middleware/auth_test.go @@ -7,6 +7,7 @@ import ( "testing" "hfb_sys/backend/internal/modules/auth" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" @@ -20,6 +21,14 @@ func useRequestTenant(tenantID uint64) gin.HandlerFunc { } } +func useBoundSiteCode(code string) gin.HandlerFunc { + return func(c *gin.Context) { + ctx := sitecode.WithBoundSiteCode(c.Request.Context(), code) + 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") @@ -111,3 +120,39 @@ func TestUserAndAdminTokensRejectCrossTenantRequests(t *testing.T) { t.Fatalf("cross-tenant admin token status = %d, want 401", adminResponse.Code) } } + +func TestUserAuthAllowsLegacyTenantTokenOnBoundDistributionSite(t *testing.T) { + gin.SetMode(gin.TestMode) + manager := auth.NewJWTManager("legacy-distribution-auth-test-secret") + pair, err := manager.GenerateTenantPairWithVersion(1, "13800000000", "user", 1, 101) + if err != nil { + t.Fatal(err) + } + + newEngine := func(boundSiteCode string) *gin.Engine { + engine := gin.New() + if boundSiteCode != "" { + engine.Use(useBoundSiteCode(boundSiteCode)) + } + engine.GET("/protected", Auth(manager, nil), func(c *gin.Context) { + c.Status(http.StatusNoContent) + }) + return engine + } + + request := httptest.NewRequest(http.MethodGet, "/protected", nil) + request.Header.Set("Authorization", "Bearer "+pair.AccessToken) + boundResponse := httptest.NewRecorder() + newEngine("legacy_site_a").ServeHTTP(boundResponse, request) + if boundResponse.Code != http.StatusNoContent { + t.Fatalf("bound distribution token status = %d, want 204", boundResponse.Code) + } + + request = httptest.NewRequest(http.MethodGet, "/protected", nil) + request.Header.Set("Authorization", "Bearer "+pair.AccessToken) + unboundResponse := httptest.NewRecorder() + newEngine("").ServeHTTP(unboundResponse, request) + if unboundResponse.Code != http.StatusUnauthorized { + t.Fatalf("unbound distribution token status = %d, want 401", unboundResponse.Code) + } +} diff --git a/backend/internal/middleware/site_domain_fallback.go b/backend/internal/middleware/site_domain_fallback.go index ed5e2df7..33a8fa21 100644 --- a/backend/internal/middleware/site_domain_fallback.go +++ b/backend/internal/middleware/site_domain_fallback.go @@ -77,10 +77,22 @@ func SiteDomainFallback(resolver SiteDomainResolver, logger *zap.Logger) gin.Han } // 已登记的站点域名是权威来源。即使前端带着旧站点头或 query, // 也必须先确认当前 Host 属于哪个分销站点,否则后续 known-host 校验会误拒绝请求。 - if code := resolveSiteCodeByHost(c, resolver, cache, logger); code != "" { + hostCode := resolveSiteCodeByHost(c, resolver, cache, logger) + code := hostCode + if code != "" { c.Request.Header.Del(sitecode.LegacyHeaderName) c.Request.Header.Set(sitecode.HeaderName, code) - c.Request = c.Request.WithContext(sitecode.WithDomainScope(c.Request.Context())) + } else { + // 未登记域名仍允许通过显式站点参数访问预览或开发环境, + // 但后续鉴权会继续校验令牌用户是否确实属于该站点。 + code = sitecode.FromRequest(c) + } + if code != "" { + ctx := sitecode.WithBoundSiteCode(c.Request.Context(), code) + if hostCode != "" { + ctx = sitecode.WithDomainScope(ctx) + } + c.Request = c.Request.WithContext(ctx) } c.Next() } diff --git a/backend/internal/middleware/site_domain_fallback_test.go b/backend/internal/middleware/site_domain_fallback_test.go index 41681407..95f7d5fb 100644 --- a/backend/internal/middleware/site_domain_fallback_test.go +++ b/backend/internal/middleware/site_domain_fallback_test.go @@ -71,6 +71,24 @@ func TestSiteDomainFallbackResolvesByHost(t *testing.T) { } } +func TestSiteDomainFallbackBindsResolvedSiteCodeToContext(t *testing.T) { + resolver := &fakeSiteDomainResolver{byDomain: map[string]string{"tysh.hao858.com": "gz_dist"}} + gin.SetMode(gin.TestMode) + engine := gin.New() + engine.Use(SiteDomainFallback(resolver, nil)) + engine.GET("/probe", func(c *gin.Context) { + c.String(http.StatusOK, sitecode.BoundSiteCodeFromContext(c.Request.Context())) + }) + + req := httptest.NewRequest(http.MethodGet, "/probe", nil) + req.Host = "tysh.hao858.com" + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, req) + if got := recorder.Body.String(); got != "gz_dist" { + t.Fatalf("bound site code = %q, want gz_dist", got) + } +} + func TestSiteDomainFallbackKnownHostOverridesExplicitSiteCode(t *testing.T) { resolver := &fakeSiteDomainResolver{byDomain: map[string]string{"tysh.hao858.com": "gz_dist"}} engine := newSiteFallbackRouter(resolver) diff --git a/backend/internal/modules/auth/repository.go b/backend/internal/modules/auth/repository.go index f74fe76f..da775c53 100644 --- a/backend/internal/modules/auth/repository.go +++ b/backend/internal/modules/auth/repository.go @@ -8,6 +8,7 @@ import ( "time" "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "gorm.io/gorm" @@ -32,12 +33,23 @@ func NewUserRepository(db *gorm.DB) *UserRepository { return &UserRepository{db: db} } +func scopeUserQueryToBoundSite(ctx context.Context, query *gorm.DB) *gorm.DB { + code := sitecode.BoundSiteCodeFromContext(ctx) + if code == "" { + return query + } + return query. + Joins("JOIN distribution_sites AS auth_site ON auth_site.id = users.distribution_site_id"). + Where("auth_site.site_code = ? AND auth_site.status = ?", code, "active") +} + func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User, error) { var user model.User query := r.db.WithContext(ctx) if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID) } + query = scopeUserQueryToBoundSite(ctx, query) if err := query.First(&user, id).Error; err != nil { return nil, err } @@ -54,8 +66,9 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID) } + query = scopeUserQueryToBoundSite(ctx, query) if err := query. - Select("id, phone, status, token_version"). + Select("users.id, users.phone, users.status, users.token_version"). First(&user, id).Error; err != nil { return nil, err } @@ -73,6 +86,7 @@ func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID) } + query = scopeUserQueryToBoundSite(ctx, query) if err := query.Updates(map[string]any{ "nickname": nickname, "avatar_url": avatarURL, @@ -187,6 +201,7 @@ func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash st if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID) } + query = scopeUserQueryToBoundSite(ctx, query) return query.Updates(map[string]any{ "password_hash": hash, "token_version": gorm.Expr("token_version + 1"), @@ -199,6 +214,7 @@ func (r *UserRepository) RevokeTokens(ctx context.Context, userID uint64) error if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID) } + query = scopeUserQueryToBoundSite(ctx, query) return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error } diff --git a/backend/internal/modules/auth/service.go b/backend/internal/modules/auth/service.go index a86fdecb..5944255a 100644 --- a/backend/internal/modules/auth/service.go +++ b/backend/internal/modules/auth/service.go @@ -14,6 +14,7 @@ import ( smsprovider "hfb_sys/backend/internal/integrations/sms" "hfb_sys/backend/internal/logging" "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "github.com/redis/go-redis/v9" @@ -260,7 +261,9 @@ func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (TokenP } tenantID := tenancy.IDFromContext(ctx) if claims.TenantID > 0 && claims.TenantID != tenantID { - return TokenPair{}, ErrTokenVersionMismatch + if tenantID != 0 || sitecode.BoundSiteCodeFromContext(ctx) == "" { + return TokenPair{}, ErrTokenVersionMismatch + } } user, err := s.users.FindActiveForToken(ctx, claims.UserID, claims.TokenVersion) if err != nil { diff --git a/backend/internal/modules/auth/tenant_scope_test.go b/backend/internal/modules/auth/tenant_scope_test.go index 38be1c6b..027ef27e 100644 --- a/backend/internal/modules/auth/tenant_scope_test.go +++ b/backend/internal/modules/auth/tenant_scope_test.go @@ -6,6 +6,7 @@ import ( "hfb_sys/backend/internal/database" "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" ) @@ -122,3 +123,47 @@ func TestLegacyDistributionUserCannotEnterTenantSite(t *testing.T) { t.Fatalf("legacy distribution domain login failed: %v", err) } } + +func TestLegacyDistributionUserSessionIsScopedToBoundSite(t *testing.T) { + db := database.NewTestDB() + sites := []model.DistributionSite{ + {SiteCode: "legacy_session_a", SiteName: "历史分销 A", Domain: "legacy-session-a.example.com", Status: "active"}, + {SiteCode: "legacy_session_b", SiteName: "历史分销 B", Domain: "legacy-session-b.example.com", Status: "active"}, + } + if err := db.Create(&sites).Error; err != nil { + t.Fatal(err) + } + legacy := model.User{ + TenantID: 101, Phone: "13600000019", Status: "active", + DistributionSiteID: sites[0].ID, TokenVersion: 1, + } + if err := db.Create(&legacy).Error; err != nil { + t.Fatal(err) + } + + repo := NewUserRepository(db) + ctxA := sitecode.WithBoundSiteCode(context.Background(), sites[0].SiteCode) + ctxB := sitecode.WithBoundSiteCode(context.Background(), sites[1].SiteCode) + if _, err := repo.FindActiveForToken(ctxA, legacy.ID, legacy.TokenVersion); err != nil { + t.Fatalf("bound own site token validation failed: %v", err) + } + if _, err := repo.FindActiveForToken(ctxB, legacy.ID, legacy.TokenVersion); !IsNotFound(err) { + t.Fatalf("cross-site token validation error = %v, want not found", err) + } + if _, err := repo.FindActiveForToken(authTenantContext(legacy.TenantID), legacy.ID, legacy.TokenVersion); !IsNotFound(err) { + t.Fatalf("tenant-site token validation error = %v, want not found", err) + } + + manager := NewJWTManager("legacy-distribution-session-test-secret") + pair, err := manager.GenerateTenantPairWithVersion(legacy.ID, legacy.Phone, "user", legacy.TokenVersion, legacy.TenantID) + if err != nil { + t.Fatal(err) + } + service := NewService(repo, nil, manager, nil, nil) + if _, err := service.RefreshToken(ctxA, pair.RefreshToken); err != nil { + t.Fatalf("bound own site refresh failed: %v", err) + } + if _, err := service.RefreshToken(ctxB, pair.RefreshToken); err == nil { + t.Fatal("cross-site refresh must fail") + } +} diff --git a/backend/internal/sitecode/sitecode.go b/backend/internal/sitecode/sitecode.go index e94d0142..95d5b4f6 100644 --- a/backend/internal/sitecode/sitecode.go +++ b/backend/internal/sitecode/sitecode.go @@ -27,6 +27,7 @@ const LegacyHeaderName = "X-Site-Code" type tenantScopeContextKey struct{} type domainScopeContextKey struct{} +type boundSiteCodeContextKey struct{} // WithTenantScope 标记当前请求已识别为经营租户。 // 经营租户与历史分销站点使用不同归属模型,识别成功后必须忽略旧分销站点编码。 @@ -50,6 +51,17 @@ func HasDomainScope(ctx context.Context) bool { return enabled } +// WithBoundSiteCode 记录本次请求已绑定的历史分销站点编码。 +// 与请求头不同,该值位于服务端上下文,可供鉴权校验用户是否属于本站。 +func WithBoundSiteCode(ctx context.Context, code string) context.Context { + return context.WithValue(ctx, boundSiteCodeContextKey{}, strings.TrimSpace(code)) +} + +func BoundSiteCodeFromContext(ctx context.Context) string { + code, _ := ctx.Value(boundSiteCodeContextKey{}).(string) + return strings.TrimSpace(code) +} + // FromRequest 按权威优先级解析站点编码: // X-Distribution-Site-Code 头 → X-Site-Code 旧头 → distribution_site_code / site_code query。 // 所有来源均做 TrimSpace,返回空串表示主站。经营租户请求始终返回空串,