fix(tenant): 隔离经营租户与旧分销站点上下文

This commit is contained in:
yml
2026-11-15 19:05:42 +08:00
parent 8744e0f391
commit 6383e15c64
10 changed files with 242 additions and 32 deletions
@@ -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 {