package router import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "testing" "time" "hfb_sys/backend/internal/database" "hfb_sys/backend/internal/middleware" "hfb_sys/backend/internal/model" "hfb_sys/backend/internal/modules/chat" "hfb_sys/backend/internal/modules/distribution" "hfb_sys/backend/internal/sitecode" "hfb_sys/backend/internal/tenancy" "github.com/gin-gonic/gin" "gorm.io/gorm" ) func distributionQrCodeTestRouter(t *testing.T) (*gin.Engine, *gorm.DB) { t.Helper() db := database.NewTestDB() siteA, siteB := uint64(11), uint64(12) conversationID := uint64(201) now, expired := time.Now(), time.Now().Add(-time.Hour) for _, records := range []any{ &[]model.Tenant{{ID: 41, Code: "qr_parent", Name: "大锤", Status: "active"}, {ID: 42, Code: "qr_other", Name: "其他经营站", Status: "active"}}, &[]model.AdminUser{{ID: 7, Username: "qr_member", Status: "active"}, {ID: 8, Username: "qr_disabled_member", Status: "active"}, {ID: 9, Username: "qr_super", Status: "active"}}, &[]model.DistributionSite{{ID: siteA, SiteCode: "gz_dist", SiteName: "天域", Domain: "qr-a.test", Status: "active"}, {ID: siteB, SiteCode: "other_dist", SiteName: "其他分站", Domain: "qr-b.test", Status: "active"}}, &[]model.ChatSiteTenantLink{{SiteID: siteA, TenantID: 41, Enabled: true}, {SiteID: siteB, TenantID: 41, Enabled: true}}, &[]model.DistributionSiteMember{{SiteID: siteA, AdminUserID: 7, MemberType: "owner", Status: "active"}, {SiteID: siteA, AdminUserID: 8, MemberType: "owner", Status: "disabled"}}, &model.ChatConversation{ID: conversationID, TenantID: 41, DistributionSiteID: &siteA, Title: "账号群 202611290372"}, &[]model.ChatQrCode{ {ID: 101, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "/api/admin/files/object?key=qrcode%2Fown.jpg", GroupName: "天域商行对接群115", Status: "unused", CreatedBy: 7}, {ID: 102, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/used.jpg", GroupName: "天域商行对接群116", Status: "used", ConversationID: &conversationID, UsedAt: &now, CreatedBy: 7}, {ID: 103, TenantID: 41, DistributionSiteID: &siteB, ImageURL: "qrcode/other-site.jpg", Status: "unused", CreatedBy: 7}, {ID: 104, TenantID: 42, DistributionSiteID: &siteA, ImageURL: "qrcode/other-tenant.jpg", Status: "unused", CreatedBy: 7}, {ID: 105, TenantID: 41, ImageURL: "qrcode/main-site.jpg", Status: "unused", CreatedBy: 7}, {ID: 106, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/disabled.jpg", Status: "disabled", CreatedBy: 7}, {ID: 107, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/expired.jpg", Status: "unused", ExpiresAt: &expired, CreatedBy: 7}, }, &model.Role{ID: 91, Code: "super_admin", Name: "平台超管"}, &model.AdminUserRole{AdminID: 9, RoleID: 91}, } { if err := db.Create(records).Error; err != nil { t.Fatal(err) } } engine := gin.New() group := engine.Group("/distribution", func(c *gin.Context) { adminID, _ := strconv.ParseUint(c.GetHeader("X-Test-Admin"), 10, 64) c.Set(middleware.ContextAdminID, adminID) tenantID, _ := strconv.ParseUint(c.GetHeader("X-Test-Tenant"), 10, 64) ctx := tenancy.WithScope(c.Request.Context(), tenancy.Scope{TenantID: tenantID}) ctx = sitecode.WithBoundSiteCode(ctx, c.GetHeader("X-Test-Site")) c.Request = c.Request.WithContext(ctx) }) registerDistributionQrCodeRoutes(group, db, distribution.NewService(distribution.NewRepository(db)), chat.NewHandler(chat.NewService(chat.NewRepository(db, nil, nil))), func(c *gin.Context) { allowed, err := distributionQrCodeImageAuthorizer(c.Request.Context(), c.GetUint64(middleware.ContextAdminID), c.Query("key")) if err != nil || !allowed { t.Error("verified image grant rejected") } if allowed, _ := distributionQrCodeImageAuthorizer(c.Request.Context(), 99, c.Query("key")); allowed { t.Error("image grant allowed another admin") } if allowed, _ := distributionQrCodeImageAuthorizer(c.Request.Context(), 7, "qrcode/other-site.jpg"); allowed { t.Error("image grant allowed another key") } c.JSON(http.StatusOK, gin.H{"key": c.Query("key"), "tenant_id": tenancy.IDFromContext(c.Request.Context())}) }) return engine, db } func TestDistributionQrCodeReadRoutes(t *testing.T) { engine, db := distributionQrCodeTestRouter(t) request := func(path string, adminID, tenantID uint64, boundSite string) *httptest.ResponseRecorder { r := httptest.NewRequest(http.MethodGet, "/distribution/sites/"+path, nil) r.Header.Set("X-Test-Admin", fmt.Sprint(adminID)) r.Header.Set("X-Test-Tenant", fmt.Sprint(tenantID)) r.Header.Set("X-Test-Site", boundSite) w := httptest.NewRecorder() engine.ServeHTTP(w, r) return w } for _, tt := range []struct { name, path string adminID, tenantID uint64 boundSite string want int }{ {"tenantless_member", "11/qrcodes", 7, 0, "", 200}, {"parent_tenant_member", "11/qrcodes", 7, 41, "", 200}, {"bound_domain", "11/qrcodes", 7, 0, "gz_dist", 200}, {"no_login", "11/qrcodes", 0, 0, "", 401}, {"no_member", "11/qrcodes", 99, 0, "", 403}, {"disabled_member", "11/qrcodes", 8, 0, "", 403}, {"other_site", "12/qrcodes", 7, 0, "", 403}, {"other_site_stats", "12/qrcodes/stats", 7, 0, "", 403}, {"other_tenant_host", "11/qrcodes", 7, 42, "", 403}, {"other_bound_domain_even_superadmin", "11/qrcodes", 9, 0, "other_dist", 403}, {"invalid_site", "0/qrcodes", 7, 0, "", 400}, {"superadmin_selects_site", "12/qrcodes", 9, 0, "", 200}, {"own_image_ignores_forged_key", "11/qrcodes/101/image?key=qrcode/other-site.jpg", 7, 0, "", 200}, {"other_site_image", "11/qrcodes/103/image", 7, 0, "", 404}, {"other_tenant_image", "11/qrcodes/104/image", 7, 0, "", 404}, {"parent_image", "11/qrcodes/105/image", 7, 0, "", 404}, {"other_site_image_route", "12/qrcodes/103/image", 7, 0, "", 403}, {"invalid_image", "11/qrcodes/0/image", 7, 0, "", 400}, } { t.Run(tt.name, func(t *testing.T) { w := request(tt.path, tt.adminID, tt.tenantID, tt.boundSite) if w.Code != tt.want { t.Fatalf("status=%d want=%d body=%s", w.Code, tt.want, w.Body.String()) } if tt.name == "own_image_ignores_forged_key" && w.Body.String() != `{"key":"qrcode/own.jpg","tenant_id":41}` { t.Fatal(w.Body.String()) } }) } for _, tt := range []struct { query string wantTotal int64 wantID uint64 }{ {"?page=1&limit=20", 4, 107}, {"?page=1&limit=20&keyword=202611290372", 1, 102}, {"?page=1&limit=20&keyword=116", 1, 102}, {"?page=1&limit=20&status=used&bound=true", 1, 102}, {"?page=1&limit=20&bound=false", 3, 107}, {"?page=2&limit=1", 4, 106}, } { w := request("11/qrcodes"+tt.query, 7, 0, "") var result struct { Data struct { Items []chat.QrCodeListItem Total int64 } } if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { t.Fatal(err) } if w.Code != 200 || result.Data.Total != tt.wantTotal || len(result.Data.Items) == 0 || result.Data.Items[0].ID != tt.wantID { t.Fatalf("query %s: %s", tt.query, w.Body.String()) } for _, row := range result.Data.Items { if row.TenantID != 41 || row.DistributionSiteID == nil || *row.DistributionSiteID != 11 { t.Fatalf("cross-scope result: %+v", row) } if row.ID == 102 && row.BoundConversationTitle != "账号群 202611290372" { t.Fatal("missing bound group title") } } } w := request("11/qrcodes/stats", 7, 0, "") var stats struct{ Data chat.QrCodeStats } if err := json.Unmarshal(w.Body.Bytes(), &stats); err != nil { t.Fatal(err) } if w.Code != 200 || stats.Data != (chat.QrCodeStats{TotalCount: 4, UnusedCount: 1, UsedCount: 1, DisabledCount: 1}) { t.Fatalf("wrong stats: %s", w.Body.String()) } if allowed, _ := distributionQrCodeImageAuthorizer(t.Context(), 7, "qrcode/own.jpg"); allowed { t.Fatal("image allowed without verified scope") } for _, change := range []struct { table, predicate string values map[string]any }{ {"chat_site_tenant_links", "site_id = 11", map[string]any{"enabled": false}}, {"tenants", "id = 41", map[string]any{"status": "disabled"}}, {"distribution_sites", "id = 11", map[string]any{"status": "disabled"}}, } { tx := db.Begin() if err := tx.Table(change.table).Where(change.predicate).Updates(change.values).Error; err != nil { t.Fatal(err) } // 测试路由使用同一连接池,因此提交后检查,并在下一轮恢复有效值。 if err := tx.Commit().Error; err != nil { t.Fatal(err) } if w := request("11/qrcodes", 7, 0, ""); w.Code != 403 { t.Fatalf("inactive %s allowed: %s", change.table, w.Body.String()) } if change.table == "chat_site_tenant_links" { change.values["enabled"] = true } else { change.values["status"] = "active" } if err := db.Table(change.table).Where(change.predicate).Updates(change.values).Error; err != nil { t.Fatal(err) } } for _, route := range engine.Routes() { if route.Method != http.MethodGet { t.Fatalf("unexpected write route: %+v", route) } } }