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() tenant := model.Tenant{Code: "dachui", Name: "大锤商行", Status: "active"} if err := db.Create(&tenant).Error; err != nil { t.Fatalf("create tenant: %v", err) } repo := tenancy.NewRepository(db) if err := repo.UpsertDomain(t.Context(), tenant.Code, "hao858.com", "storefront"); err != nil { t.Fatalf("create domain: %v", err) } gin.SetMode(gin.TestMode) engine := gin.New() engine.Use(TenantContext(repo, appEnv, nil)) engine.GET("/probe", func(c *gin.Context) { scope, ok := tenancy.FromContext(c.Request.Context()) if !ok { c.JSON(http.StatusNotFound, gin.H{"found": false}) return } c.JSON(http.StatusOK, gin.H{"tenant_id": scope.TenantID, "tenant_code": scope.TenantCode}) }) return engine, tenant } func TestTenantContextResolvesHost(t *testing.T) { engine, tenant := newTenantContextTestEngine(t, "production") req := httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "hao858.com" rec := httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String()) } if body := rec.Body.String(); body == "" || !contains(body, `"tenant_id":`) { t.Fatalf("unexpected body: %s", body) } if tenant.ID == 0 { t.Fatal("tenant ID should not be zero") } } func TestTenantContextAllowsDevelopmentCodeAndIgnoresItInProduction(t *testing.T) { engine, _ := newTenantContextTestEngine(t, "development") req := httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "localhost" req.Header.Set(tenantCodeHeader, "dachui") rec := httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusOK { t.Fatalf("development code status = %d, body=%s", rec.Code, rec.Body.String()) } engine, _ = newTenantContextTestEngine(t, "production") req = httptest.NewRequest(http.MethodGet, "/probe", nil) req.Host = "localhost" req.Header.Set(tenantCodeHeader, "dachui") rec = httptest.NewRecorder() engine.ServeHTTP(rec, req) if rec.Code != http.StatusNotFound { t.Fatalf("production header status = %d, want 404", rec.Code) } } 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 TestTenantContextIgnoresClientCancellation(t *testing.T) { gin.SetMode(gin.TestMode) engine := gin.New() engine.Use(TenantContext( &fakeTenantResolver{hostErr: context.Canceled}, "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" ctx, cancel := context.WithCancel(req.Context()) cancel() req = req.WithContext(ctx) rec := httptest.NewRecorder() engine.ServeHTTP(rec, req) if handlerCalled { t.Fatal("客户端取消后业务处理器不应继续执行") } if rec.Code == http.StatusServiceUnavailable { t.Fatalf("客户端取消不应返回 503, 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 { return true } } return false }