From 6383e15c64dd36eccf0a9cc95f05a08be1dc8514 Mon Sep 17 00:00:00 2001 From: yml Date: Sun, 15 Nov 2026 19:05:42 +0800 Subject: [PATCH] =?UTF-8?q?fix(tenant):=20=E9=9A=94=E7=A6=BB=E7=BB=8F?= =?UTF-8?q?=E8=90=A5=E7=A7=9F=E6=88=B7=E4=B8=8E=E6=97=A7=E5=88=86=E9=94=80?= =?UTF-8?q?=E7=AB=99=E7=82=B9=E4=B8=8A=E4=B8=8B=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../middleware/site_domain_fallback.go | 9 +- backend/internal/middleware/tenant_context.go | 31 ++-- .../middleware/tenant_context_test.go | 132 ++++++++++++++++++ backend/internal/modules/auth/handler.go | 27 ++-- backend/internal/modules/chat/handler_user.go | 5 +- .../internal/modules/distribution/handler.go | 4 + .../internal/modules/order/handler_user.go | 2 +- backend/internal/router/router.go | 10 +- backend/internal/sitecode/sitecode.go | 24 +++- backend/internal/sitecode/sitecode_test.go | 30 ++++ 10 files changed, 242 insertions(+), 32 deletions(-) diff --git a/backend/internal/middleware/site_domain_fallback.go b/backend/internal/middleware/site_domain_fallback.go index e9110f66..8a800671 100644 --- a/backend/internal/middleware/site_domain_fallback.go +++ b/backend/internal/middleware/site_domain_fallback.go @@ -7,6 +7,7 @@ import ( "time" "hfb_sys/backend/internal/sitecode" + "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" "go.uber.org/zap" @@ -57,14 +58,18 @@ func (c *siteDomainCache) set(host, code string) { // // 背景:站点归属此前完全依赖前端注入的 X-Distribution-Site-Code 头, // 首屏探测失败或漏带就会把分站写入当成主站(2026-10-10 之前已因此丢过一批注册归属)。 -// 显式头/query 始终优先,本中间件只在两者都为空时兜底;数据库异常时不阻断请求, -// 退化为原有行为(视为主站)。 +// 经营租户请求不参与旧分销域名兜底。显式头/query 始终优先,本中间件只在两者都为空时兜底; +// 旧分销域名解析异常时不阻断请求,退化为原有行为(视为主站)。 func SiteDomainFallback(resolver SiteDomainResolver, logger *zap.Logger) gin.HandlerFunc { if resolver == nil { return func(c *gin.Context) { c.Next() } } cache := newSiteDomainCache() return func(c *gin.Context) { + if _, ok := tenancy.FromContext(c.Request.Context()); ok || sitecode.HasTenantScope(c.Request.Context()) { + c.Next() + return + } if sitecode.FromRequest(c) != "" { c.Next() return diff --git a/backend/internal/middleware/tenant_context.go b/backend/internal/middleware/tenant_context.go index ca7d485b..c49a0302 100644 --- a/backend/internal/middleware/tenant_context.go +++ b/backend/internal/middleware/tenant_context.go @@ -7,6 +7,7 @@ import ( "hfb_sys/backend/internal/config" "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" + "hfb_sys/backend/pkg/response" "github.com/gin-gonic/gin" "go.uber.org/zap" @@ -47,20 +48,30 @@ func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger, d 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) != "" { + legacySiteCode := sitecode.FromRequest(c) + if scope == nil && err == nil && + !production && + legacySiteCode == "" && + sitecode.IsLocalHost(host) && + defaultTenantCode != "" { 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", host), - zap.Error(err), - ) + if err != nil { + if logger != nil { + logger.Error("经营租户解析失败,拒绝按旧站点上下文继续", + zap.String("host", host), + zap.Error(err), + ) + } + response.RecordError(c, err) + response.ServiceUnavailable(c, "站点信息暂时不可用,请稍后重试") + c.Abort() + return } if scope != nil { - c.Request = c.Request.WithContext(tenancy.WithScope(c.Request.Context(), *scope)) + ctx := tenancy.WithScope(c.Request.Context(), *scope) + ctx = sitecode.WithTenantScope(ctx) + c.Request = c.Request.WithContext(ctx) c.Set(ContextTenantID, scope.TenantID) c.Set(ContextTenantCode, scope.TenantCode) } diff --git a/backend/internal/middleware/tenant_context_test.go b/backend/internal/middleware/tenant_context_test.go index fb5cf74e..d05f1666 100644 --- a/backend/internal/middleware/tenant_context_test.go +++ b/backend/internal/middleware/tenant_context_test.go @@ -1,17 +1,37 @@ package middleware import ( + "context" + "errors" "net/http" "net/http/httptest" "testing" "hfb_sys/backend/internal/database" "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" ) +type fakeTenantResolver struct { + hostScope *tenancy.Scope + hostErr error + codeScope *tenancy.Scope + codeErr error + codeCalls int +} + +func (f *fakeTenantResolver) ResolveHost(context.Context, string) (*tenancy.Scope, error) { + return f.hostScope, f.hostErr +} + +func (f *fakeTenantResolver) ResolveCode(context.Context, string) (*tenancy.Scope, error) { + f.codeCalls++ + return f.codeScope, f.codeErr +} + func newTenantContextTestEngine(t *testing.T, appEnv string) (*gin.Engine, model.Tenant) { t.Helper() db := database.NewTestDB() @@ -77,6 +97,118 @@ func TestTenantContextAllowsDevelopmentCodeAndIgnoresItInProduction(t *testing.T } } +func TestTenantContextFailsClosedOnResolveError(t *testing.T) { + gin.SetMode(gin.TestMode) + engine := gin.New() + engine.Use(TenantContext( + &fakeTenantResolver{hostErr: errors.New("database unavailable")}, + "production", + nil, + )) + handlerCalled := false + engine.GET("/probe", func(c *gin.Context) { + handlerCalled = true + c.Status(http.StatusNoContent) + }) + + req := httptest.NewRequest(http.MethodGet, "/probe", nil) + req.Host = "jieyou.example.com" + rec := httptest.NewRecorder() + engine.ServeHTTP(rec, req) + + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503, body=%s", rec.Code, rec.Body.String()) + } + if handlerCalled { + t.Fatal("租户解析失败后业务处理器不应继续执行") + } + if !contains(rec.Body.String(), `"code":"service_unavailable"`) { + t.Fatalf("unexpected body: %s", rec.Body.String()) + } +} + +func TestTenantContextSkipsLegacyDistributionFallback(t *testing.T) { + tenantResolver := &fakeTenantResolver{ + hostScope: &tenancy.Scope{TenantID: 202, TenantCode: "jieyou", TenantName: "解忧商行"}, + } + legacyResolver := &fakeSiteDomainResolver{ + byDomain: map[string]string{"jieyou.example.com": "legacy_jieyou"}, + } + + gin.SetMode(gin.TestMode) + engine := gin.New() + engine.Use(TenantContext(tenantResolver, "production", nil)) + engine.Use(SiteDomainFallback(legacyResolver, nil)) + engine.GET("/probe", func(c *gin.Context) { + scope, ok := tenancy.FromContext(c.Request.Context()) + c.JSON(http.StatusOK, gin.H{ + "tenant_code": scope.TenantCode, + "tenant_ok": ok, + "site_code": sitecode.FromRequest(c), + }) + }) + + req := httptest.NewRequest(http.MethodGet, "/probe?distribution_site_code=legacy_query", nil) + req.Host = "jieyou.example.com" + req.Header.Set(sitecode.LegacyHeaderName, "legacy_header") + rec := httptest.NewRecorder() + engine.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String()) + } + if !contains(rec.Body.String(), `"tenant_ok":true`) || + !contains(rec.Body.String(), `"tenant_code":"jieyou"`) || + !contains(rec.Body.String(), `"site_code":""`) { + t.Fatalf("经营租户上下文未正确优先: %s", rec.Body.String()) + } + if legacyResolver.calls != 0 { + t.Fatalf("经营租户请求不应触发旧分销域名兜底, calls = %d", legacyResolver.calls) + } +} + +func TestTenantContextLocalFallbackDoesNotCaptureLegacySiteRequests(t *testing.T) { + gin.SetMode(gin.TestMode) + scopeRead := func(resolver *fakeTenantResolver, headers map[string]string) (int, bool) { + engine := gin.New() + engine.Use(TenantContext(resolver, "development", nil, "dachui")) + engine.GET("/probe", func(c *gin.Context) { + _, ok := tenancy.FromContext(c.Request.Context()) + if ok { + c.Status(http.StatusOK) + return + } + c.Status(http.StatusNotFound) + }) + + req := httptest.NewRequest(http.MethodGet, "/probe", nil) + req.Host = "localhost:5191" + for key, value := range headers { + req.Header.Set(key, value) + } + rec := httptest.NewRecorder() + engine.ServeHTTP(rec, req) + return rec.Code, resolver.codeCalls > 0 + } + + mainResolver := &fakeTenantResolver{ + codeScope: &tenancy.Scope{TenantID: 101, TenantCode: "dachui"}, + } + if status, resolved := scopeRead(mainResolver, nil); status != http.StatusOK || !resolved { + t.Fatalf("普通本地请求应回退大锤经营租户, status=%d resolved=%v", status, resolved) + } + + legacyResolver := &fakeTenantResolver{ + codeScope: &tenancy.Scope{TenantID: 101, TenantCode: "dachui"}, + } + status, resolved := scopeRead(legacyResolver, map[string]string{ + sitecode.HeaderName: "test_1", + }) + if status != http.StatusNotFound || resolved { + t.Fatalf("显式旧分销站点请求不应被本地经营租户兜底捕获, status=%d resolved=%v", status, resolved) + } +} + func contains(value, target string) bool { for i := 0; i+len(target) <= len(value); i++ { if value[i:i+len(target)] == target { diff --git a/backend/internal/modules/auth/handler.go b/backend/internal/modules/auth/handler.go index 94904737..73010ff9 100644 --- a/backend/internal/modules/auth/handler.go +++ b/backend/internal/modules/auth/handler.go @@ -99,18 +99,21 @@ func (h *Handler) SendSMS(c *gin.Context) { } siteCode := sitecode.FromRequest(c) - if siteCode == "" { - siteCode = strings.TrimSpace(req.SiteCode) - } - domain := strings.TrimSpace(firstNonEmpty( - c.GetHeader("X-Distribution-Domain"), - c.Query("distribution_domain"), - c.Query("domain"), - )) - if siteCode == "" && domain == "" { - host := sitecode.ExtractHost(c.Request.Host) - if host != "" && !sitecode.IsLocalHost(host) { - domain = host + domain := "" + if !sitecode.HasTenantScope(c.Request.Context()) { + if siteCode == "" { + siteCode = strings.TrimSpace(req.SiteCode) + } + domain = strings.TrimSpace(firstNonEmpty( + c.GetHeader("X-Distribution-Domain"), + c.Query("distribution_domain"), + c.Query("domain"), + )) + if siteCode == "" && domain == "" { + host := sitecode.ExtractHost(c.Request.Host) + if host != "" && !sitecode.IsLocalHost(host) { + domain = host + } } } diff --git a/backend/internal/modules/chat/handler_user.go b/backend/internal/modules/chat/handler_user.go index b9636dac..8212eb8a 100644 --- a/backend/internal/modules/chat/handler_user.go +++ b/backend/internal/modules/chat/handler_user.go @@ -1,6 +1,7 @@ package chat import ( + "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/pkg/response" "github.com/gin-gonic/gin" @@ -67,7 +68,9 @@ func (h *Handler) EnsureSupportConversation(c *gin.Context) { // scene 可选;空 body 仍按平台客服处理 _ = c.ShouldBindJSON(&req) siteCode := parseSiteCode(c) - if siteCode == "" && req.DistributionSiteCode != "" { + if siteCode == "" && + req.DistributionSiteCode != "" && + !sitecode.HasTenantScope(c.Request.Context()) { siteCode = req.DistributionSiteCode } item, err := h.service.EnsureSupportConversation(c.Request.Context(), userID, req.Scene, siteCode) diff --git a/backend/internal/modules/distribution/handler.go b/backend/internal/modules/distribution/handler.go index 33c5cd3a..3fa66428 100644 --- a/backend/internal/modules/distribution/handler.go +++ b/backend/internal/modules/distribution/handler.go @@ -387,6 +387,10 @@ func (h *Handler) ListPublicSiteListings(c *gin.Context) { } func (h *Handler) GetPublicSiteInfo(c *gin.Context) { + if sitecode.HasTenantScope(c.Request.Context()) { + response.NotFound(c, "经营租户站点不使用分销站点信息") + return + } code := sitecode.FromQueryThenHeader(c) domain := strings.TrimSpace(c.Query("domain")) if code == "" && domain == "" { diff --git a/backend/internal/modules/order/handler_user.go b/backend/internal/modules/order/handler_user.go index 129a1f48..746810b9 100644 --- a/backend/internal/modules/order/handler_user.go +++ b/backend/internal/modules/order/handler_user.go @@ -20,7 +20,7 @@ func (h *Handler) Create(c *gin.Context) { response.BadRequest(c, "订单信息不完整") return } - if strings.TrimSpace(req.DistributionSiteCode) == "" { + if sitecode.HasTenantScope(c.Request.Context()) || strings.TrimSpace(req.DistributionSiteCode) == "" { req.DistributionSiteCode = sitecode.FromRequest(c) } item, err := h.service.Create(c.Request.Context(), userID, req) diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index 107ead83..b598664a 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -356,14 +356,14 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { authService.SetSiteSMSResolver(distributionService) } } - // 站点归属兜底:请求未携带站点编码时按访问域名判定站点(前端首屏探测/漏带场景), - // 避免注册等写入把分站用户记成主站。必须注册在任何业务路由之前。 - if distributionRepo != nil { - engine.Use(middleware.SiteDomainFallback(distributionRepo, logger)) - } + // 先识别经营租户,再兼容旧分销站点。经营租户识别成功后,后续旧分销参数和域名兜底均不生效。 if tenantRepo != nil { engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger, "dachui")) } + // 旧分销站点归属兜底:请求未携带站点编码时按访问域名判定站点(前端首屏探测/漏带场景)。 + if distributionRepo != nil { + engine.Use(middleware.SiteDomainFallback(distributionRepo, logger)) + } distributionHandler := distribution.NewHandler(distributionService) if invitationHandler != nil && distributionService != nil { invitationHandler.SetSiteScoper(distributionService) diff --git a/backend/internal/sitecode/sitecode.go b/backend/internal/sitecode/sitecode.go index 8690441c..757fd88c 100644 --- a/backend/internal/sitecode/sitecode.go +++ b/backend/internal/sitecode/sitecode.go @@ -12,6 +12,7 @@ package sitecode import ( + "context" "net" "strings" @@ -24,10 +25,28 @@ const HeaderName = "X-Distribution-Site-Code" // LegacyHeaderName 是历史版本使用的站点编码请求头,仅作兜底兼容。 const LegacyHeaderName = "X-Site-Code" +type tenantScopeContextKey struct{} + +// WithTenantScope 标记当前请求已识别为经营租户。 +// 经营租户与历史分销站点使用不同归属模型,识别成功后必须忽略旧分销站点编码。 +func WithTenantScope(ctx context.Context) context.Context { + return context.WithValue(ctx, tenantScopeContextKey{}, true) +} + +// HasTenantScope 判断当前请求是否已识别为经营租户。 +func HasTenantScope(ctx context.Context) bool { + enabled, _ := ctx.Value(tenantScopeContextKey{}).(bool) + return enabled +} + // FromRequest 按权威优先级解析站点编码: // X-Distribution-Site-Code 头 → X-Site-Code 旧头 → distribution_site_code / site_code query。 -// 所有来源均做 TrimSpace,返回空串表示主站。 +// 所有来源均做 TrimSpace,返回空串表示主站。经营租户请求始终返回空串, +// 防止历史分销参数把经营租户重新带回旧站点查询。 func FromRequest(c *gin.Context) string { + if HasTenantScope(c.Request.Context()) { + return "" + } return firstNonEmpty( c.GetHeader(HeaderName), c.GetHeader(LegacyHeaderName), @@ -40,6 +59,9 @@ func FromRequest(c *gin.Context) string { // 显式 query 参数优先于会话头。SPA 探测新站点时会话头里还是上一个站点的编码, // 必须让 query 压过它,否则从主站跳转到分站时会探测到错误站点。 func FromQueryThenHeader(c *gin.Context) string { + if HasTenantScope(c.Request.Context()) { + return "" + } return firstNonEmpty( c.Query("code"), c.Query("site_code"), diff --git a/backend/internal/sitecode/sitecode_test.go b/backend/internal/sitecode/sitecode_test.go index 7012eb56..29b111b0 100644 --- a/backend/internal/sitecode/sitecode_test.go +++ b/backend/internal/sitecode/sitecode_test.go @@ -1,6 +1,7 @@ package sitecode import ( + "context" "net/http/httptest" "testing" @@ -45,6 +46,22 @@ func TestFromRequest(t *testing.T) { } } +func TestFromRequestIgnoresLegacySiteCodeInTenantScope(t *testing.T) { + c := newTestContext( + "GET", + "/api/listings?distribution_site_code=query_site", + map[string]string{ + HeaderName: "new_site", + LegacyHeaderName: "legacy_site", + }, + ) + c.Request = c.Request.WithContext(WithTenantScope(context.Background())) + + if got := FromRequest(c); got != "" { + t.Fatalf("经营租户请求不应解析旧分销站点编码, got %q", got) + } +} + func TestFromQueryThenHeader(t *testing.T) { cases := []struct { name string @@ -67,6 +84,19 @@ func TestFromQueryThenHeader(t *testing.T) { } } +func TestFromQueryThenHeaderIgnoresLegacySiteCodeInTenantScope(t *testing.T) { + c := newTestContext( + "GET", + "/distribution/site-info?code=probe_site&distribution_site_code=legacy_site", + map[string]string{HeaderName: "header_site"}, + ) + c.Request = c.Request.WithContext(WithTenantScope(context.Background())) + + if got := FromQueryThenHeader(c); got != "" { + t.Fatalf("经营租户请求不应探测旧分销站点, got %q", got) + } +} + func TestExtractHost(t *testing.T) { cases := []struct { raw string