package storefrontshell import ( "context" "net/http" "net/http/httptest" "strings" "testing" "hfb_sys/backend/internal/middleware" "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" "go.uber.org/zap" "gorm.io/datatypes" ) type fakeTenantResolver struct{} func (fakeTenantResolver) ResolveHost(_ context.Context, host string) (*tenancy.Scope, error) { if strings.Contains(host, "zuhaox.com") { return &tenancy.Scope{ TenantID: 2, TenantCode: "jieyou", TenantName: "解忧商行", TenantStatus: "active", Host: host, }, nil } return nil, nil } func (fakeTenantResolver) ResolveCode(context.Context, string) (*tenancy.Scope, error) { return nil, nil } type staticProvider struct { body []byte err error } func (p staticProvider) Get(context.Context) ([]byte, error) { return p.body, p.err } func TestBuildMetaJieyouFallbacks(t *testing.T) { meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/") if meta.Title != "解忧商行 - 官方租号平台" { t.Fatalf("Title = %q", meta.Title) } if meta.FaviconURL != "/jieyou-favicon.svg" { t.Fatalf("FaviconURL = %q", meta.FaviconURL) } if meta.AppleIconURL != "/jieyou-apple-touch-icon.png" { t.Fatalf("AppleIconURL = %q", meta.AppleIconURL) } if meta.ThemeColor != "#a64332" { t.Fatalf("ThemeColor = %q", meta.ThemeColor) } if meta.Canonical != "https://zuhaox.com/" { t.Fatalf("Canonical = %q", meta.Canonical) } } func TestBuildMetaRejectsUnsafeAssetURL(t *testing.T) { meta := BuildMeta(map[string]any{ "site_name": "测试站", "favicon_url": "javascript:alert(1)", "logo_url": "data:text/html,", }, "custom", "", "https", "example.com", "/") if meta.FaviconURL != "" { t.Fatalf("FaviconURL = %q, want empty", meta.FaviconURL) } if meta.OGImageURL != "" { t.Fatalf("OGImageURL = %q, want empty", meta.OGImageURL) } } func TestBuildMetaEscapesProfileValues(t *testing.T) { meta := BuildMeta( map[string]any{"site_name": ``}, "custom", "", "https", "example.com", "/", ) block := meta.HTML(true) if strings.Contains(block, "`) meta := BuildMeta(nil, "jieyou", "解忧商行", "https", "zuhaox.com", "/") out := string(Inject(shell, meta)) if strings.Count(out, "") != 1 { t.Fatalf("expected exactly one title tag, got: %s", out) } if !strings.Contains(out, "<title>解忧商行 - 官方租号平台") { t.Fatalf("title was not replaced: %s", out) } if !strings.Contains(out, `name="description"`) { t.Fatalf("description was not injected: %s", out) } shellMarker := strings.Index(out, `name="site-shell"`) script := strings.Index(out, "site-bootstrap.js") if shellMarker < 0 || script < 0 || shellMarker > script { t.Fatalf("site-shell marker must appear before site-bootstrap.js: %s", out) } } func TestProviderRevalidatesWithETag(t *testing.T) { requests := 0 conditional := "" server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests++ if r.Header.Get("If-None-Match") == `"v1"` { conditional = r.Header.Get("If-None-Match") w.WriteHeader(http.StatusNotModified) return } w.Header().Set("ETag", `"v1"`) _, _ = w.Write([]byte(`shell`)) })) defer server.Close() provider := NewProvider(server.URL, zap.NewNop()) provider.ttl = 0 first, err := provider.Get(context.Background()) if err != nil { t.Fatalf("first Get: %v", err) } second, err := provider.Get(context.Background()) if err != nil { t.Fatalf("second Get: %v", err) } if string(first) != string(second) { t.Fatalf("cached body changed: %q vs %q", first, second) } if requests != 2 { t.Fatalf("requests = %d, want 2", requests) } if conditional != `"v1"` { t.Fatalf("conditional header = %q", conditional) } } func TestHandlerServesTenantShell(t *testing.T) { gin.SetMode(gin.TestMode) handler := NewHandler(staticProvider{body: []byte( `官方租号平台
`, )}, zap.NewNop()) recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) req := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/listings/1", nil) req.Header.Set("X-Forwarded-Proto", "https") req = req.WithContext(tenancy.WithScope(req.Context(), tenancy.Scope{ TenantID: 2, TenantCode: "jieyou", TenantName: "解忧商行", ProfileJSON: datatypes.JSON([]byte(`{"site_name":"解忧商行"}`)), })) c.Request = req handler.Serve(c) if recorder.Code != http.StatusOK { t.Fatalf("status = %d, want 200", recorder.Code) } body := recorder.Body.String() if !strings.Contains(body, "解忧商行 - 官方租号平台") { t.Fatalf("body missing tenant title: %s", body) } if !strings.Contains(body, `href="/jieyou-apple-touch-icon.png"`) { t.Fatalf("body missing tenant apple icon: %s", body) } if !strings.Contains(body, `rel="canonical" href="https://zuhaox.com/listings/1"`) { t.Fatalf("body missing canonical: %s", body) } if got := recorder.Header().Get("Vary"); got != "Host" { t.Fatalf("Vary = %q, want Host", got) } if got := recorder.Header().Get("Cache-Control"); got != "no-cache" { t.Fatalf("Cache-Control = %q, want no-cache", got) } if got := recorder.Header().Get("ETag"); got == "" { t.Fatal("ETag is empty") } } func TestHandlerSupportsConditionalRequest(t *testing.T) { gin.SetMode(gin.TestMode) handler := NewHandler(staticProvider{body: []byte( `官方租号平台`, )}, zap.NewNop()) first := httptest.NewRecorder() firstContext, _ := gin.CreateTestContext(first) firstRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) firstRequest = firstRequest.WithContext(tenancy.WithScope(firstRequest.Context(), tenancy.Scope{ TenantID: 2, TenantCode: "jieyou", TenantName: "解忧商行", })) firstContext.Request = firstRequest handler.Serve(firstContext) etag := first.Header().Get("ETag") if etag == "" { t.Fatal("first response has no ETag") } second := httptest.NewRecorder() secondContext, _ := gin.CreateTestContext(second) secondRequest := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) secondRequest.Header.Set("If-None-Match", etag) secondRequest = secondRequest.WithContext(tenancy.WithScope(secondRequest.Context(), tenancy.Scope{ TenantID: 2, TenantCode: "jieyou", TenantName: "解忧商行", })) secondContext.Request = secondRequest handler.Serve(secondContext) if second.Code != http.StatusNotModified { t.Fatalf("status = %d, want 304 (etag=%q responseETag=%q ifNoneMatch=%q)", second.Code, etag, second.Header().Get("ETag"), secondRequest.Header.Get("If-None-Match")) } if second.Body.Len() != 0 { t.Fatalf("304 body = %q, want empty", second.Body.String()) } } func TestHandlerRejectsAPIPath(t *testing.T) { gin.SetMode(gin.TestMode) handler := NewHandler(staticProvider{body: []byte("")}, zap.NewNop()) recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/api/unknown", nil) handler.Serve(c) if recorder.Code != http.StatusNotFound { t.Fatalf("status = %d, want 404", recorder.Code) } if !strings.Contains(recorder.Header().Get("Content-Type"), "application/json") { t.Fatalf("content type = %q, want JSON", recorder.Header().Get("Content-Type")) } } func TestHandlerReturnsUnavailableWhenShellFails(t *testing.T) { gin.SetMode(gin.TestMode) handler := NewHandler(staticProvider{err: context.DeadlineExceeded}, zap.NewNop()) recorder := httptest.NewRecorder() c, _ := gin.CreateTestContext(recorder) c.Request = httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) handler.Serve(c) if recorder.Code != http.StatusServiceUnavailable { t.Fatalf("status = %d, want 503", recorder.Code) } if !strings.Contains(recorder.Body.String(), "页面暂时不可用") { t.Fatalf("body = %q", recorder.Body.String()) } } func TestNoRouteUsesTenantContext(t *testing.T) { gin.SetMode(gin.TestMode) engine := gin.New() engine.Use(middleware.TenantContext(fakeTenantResolver{}, "production", zap.NewNop(), "dachui")) handler := NewHandler(staticProvider{body: []byte( `官方租号平台`, )}, zap.NewNop()) engine.NoRoute(handler.Serve) recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "http://zuhaox.com/", nil) request.Header.Set("X-Forwarded-Proto", "https") engine.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("status = %d, want 200", recorder.Code) } if !strings.Contains(recorder.Body.String(), "解忧商行 - 官方租号平台") { t.Fatalf("body missing tenant title: %s", recorder.Body.String()) } }