fix(tenant): 收紧双站运营提号与录单边界
This commit is contained in:
@@ -47,6 +47,16 @@ func privateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (b
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE user_id = ? AND object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{userID, key, tenantID, tenantID},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM chat_qrcode_pool q
|
||||
JOIN chat_conversations c ON c.id = q.conversation_id
|
||||
JOIN chat_participants p ON p.conversation_id = c.id AND p.participant_type = 'user' AND p.participant_id = ?
|
||||
WHERE (? = 0 OR c.tenant_id = ? OR EXISTS (
|
||||
SELECT 1 FROM rental_orders ro WHERE ro.id = c.order_id AND (ro.buyer_tenant_id = ? OR ro.source_tenant_id = ?)
|
||||
))
|
||||
AND (INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0)`,
|
||||
args: []any{userID, tenantID, tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM game_accounts a
|
||||
JOIN rental_listings l ON l.account_id = a.id
|
||||
@@ -138,7 +148,7 @@ WHERE w.user_id = ?
|
||||
// adminPrivateFileAuthorizer 将经营站点后台的私有文件访问限制在当前租户。
|
||||
// 历史分销后台(tenant_id=0)保留原有平台级访问语义。
|
||||
func adminPrivateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (bool, error) {
|
||||
return func(ctx context.Context, _ uint64, key string) (bool, error) {
|
||||
return func(ctx context.Context, adminID uint64, key string) (bool, error) {
|
||||
if db == nil || key == "" {
|
||||
return false, nil
|
||||
}
|
||||
@@ -152,8 +162,8 @@ func adminPrivateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, strin
|
||||
args []any
|
||||
}{
|
||||
{
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{key, tenantID, tenantID},
|
||||
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE admin_id = ? AND object_key = ? AND (? = 0 OR tenant_id = ?)",
|
||||
args: []any{adminID, key, tenantID, tenantID},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM game_accounts a
|
||||
@@ -204,6 +214,33 @@ WHERE (? = 0 OR (w.tenant_id = ? AND w.distribution_site_id = 0))
|
||||
AND (INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0 OR INSTR(w.payment_proof_url, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM chat_qrcode_pool q
|
||||
WHERE (? = 0 OR (q.tenant_id = ? AND (q.distribution_site_id IS NULL OR q.distribution_site_id = 0)))
|
||||
AND (INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0 OR INSTR(q.image_url, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
}
|
||||
if (strings.HasPrefix(key, "operating-expense/") || strings.HasPrefix(key, "manual-disbursement/")) &&
|
||||
isPlatformSuperAdmin(ctx, db, adminID) {
|
||||
queries = append(queries,
|
||||
struct {
|
||||
sql string
|
||||
args []any
|
||||
}{
|
||||
sql: `SELECT COUNT(1) FROM operating_expenses oe
|
||||
WHERE INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0 OR INSTR(oe.voucher_url, ?) > 0`,
|
||||
args: []any{key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
struct {
|
||||
sql string
|
||||
args []any
|
||||
}{
|
||||
sql: `SELECT COUNT(1) FROM manual_disbursements md
|
||||
WHERE INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0 OR INSTR(md.voucher_url, ?) > 0`,
|
||||
args: []any{key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
)
|
||||
}
|
||||
for _, query := range queries {
|
||||
var count int64
|
||||
@@ -221,10 +258,10 @@ WHERE (? = 0 OR (w.tenant_id = ? AND w.distribution_site_id = 0))
|
||||
}
|
||||
}
|
||||
|
||||
// recordPrivateFileUpload 记录用户上传的原图和变体,保证草稿状态下也仅上传者可预览。
|
||||
func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string) error {
|
||||
return func(ctx context.Context, userID uint64, objectKeys []string) error {
|
||||
if db == nil || userID == 0 || len(objectKeys) == 0 {
|
||||
// recordPrivateFileUpload 记录用户或管理员上传的原图和变体,保证业务记录保存前仅上传者可预览。
|
||||
func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, uint64, []string) error {
|
||||
return func(ctx context.Context, userID, adminID uint64, objectKeys []string) error {
|
||||
if db == nil || (userID == 0 && adminID == 0) || len(objectKeys) == 0 {
|
||||
return nil
|
||||
}
|
||||
records := make([]model.FileUploadOwner, 0, len(objectKeys))
|
||||
@@ -233,7 +270,12 @@ func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
records = append(records, model.FileUploadOwner{TenantID: tenantID, UserID: userID, ObjectKey: key})
|
||||
records = append(records, model.FileUploadOwner{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
AdminID: adminID,
|
||||
ObjectKey: key,
|
||||
})
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
@@ -241,3 +283,16 @@ func recordPrivateFileUpload(db *gorm.DB) func(context.Context, uint64, []string
|
||||
return db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&records).Error
|
||||
}
|
||||
}
|
||||
|
||||
func isPlatformSuperAdmin(ctx context.Context, db *gorm.DB, adminID uint64) bool {
|
||||
if db == nil || adminID == 0 {
|
||||
return false
|
||||
}
|
||||
var count int64
|
||||
err := db.WithContext(ctx).
|
||||
Table("admin_user_roles AS aur").
|
||||
Joins("JOIN roles AS r ON r.id = aur.role_id").
|
||||
Where("aur.admin_user_id = ? AND r.code = ?", adminID, "super_admin").
|
||||
Count(&count).Error
|
||||
return err == nil && count > 0
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package router
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
@@ -91,10 +92,10 @@ func TestRecordPrivateFileUpload(t *testing.T) {
|
||||
}
|
||||
record := recordPrivateFileUpload(db)
|
||||
keys := []string{"listing/original.jpg", "listing/original.thumb.jpg", "listing/original.medium.jpg"}
|
||||
if err := record(context.Background(), 11, keys); err != nil {
|
||||
if err := record(context.Background(), 11, 0, keys); err != nil {
|
||||
t.Fatalf("record() error = %v", err)
|
||||
}
|
||||
if err := record(context.Background(), 11, keys); err != nil {
|
||||
if err := record(context.Background(), 11, 0, keys); err != nil {
|
||||
t.Fatalf("duplicate record() error = %v", err)
|
||||
}
|
||||
var count int64
|
||||
@@ -104,6 +105,16 @@ func TestRecordPrivateFileUpload(t *testing.T) {
|
||||
if count != int64(len(keys)) {
|
||||
t.Fatalf("record count = %d, want %d", count, len(keys))
|
||||
}
|
||||
adminKeys := []string{"qrcode/admin.jpg", "qrcode/admin.thumb.jpg"}
|
||||
if err := record(context.Background(), 0, 21, adminKeys); err != nil {
|
||||
t.Fatalf("record admin uploads: %v", err)
|
||||
}
|
||||
if err := db.Model(&model.FileUploadOwner{}).Where("admin_id = ?", 21).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != int64(len(adminKeys)) {
|
||||
t.Fatalf("admin record count = %d, want %d", count, len(adminKeys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateFileAuthorizerRejectsCrossTenantOwner(t *testing.T) {
|
||||
@@ -136,8 +147,8 @@ func TestAdminPrivateFileAuthorizerScopesOperatingTenant(t *testing.T) {
|
||||
t.Fatalf("AutoMigrate() error = %v", err)
|
||||
}
|
||||
rows := []model.FileUploadOwner{
|
||||
{TenantID: 101, UserID: 11, ObjectKey: "listing/admin-tenant-a.jpg"},
|
||||
{TenantID: 202, UserID: 12, ObjectKey: "listing/admin-tenant-b.jpg"},
|
||||
{TenantID: 101, UserID: 11, AdminID: 1, ObjectKey: "listing/admin-tenant-a.jpg"},
|
||||
{TenantID: 202, UserID: 12, AdminID: 2, ObjectKey: "listing/admin-tenant-b.jpg"},
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatalf("create upload owners: %v", err)
|
||||
@@ -157,11 +168,118 @@ func TestAdminPrivateFileAuthorizerScopesOperatingTenant(t *testing.T) {
|
||||
if allowed, err := authorize(ctxB, 2, "listing/admin-tenant-b.jpg"); err != nil || !allowed {
|
||||
t.Fatalf("tenant B own file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := authorize(context.Background(), 3, "listing/admin-tenant-a.jpg"); err != nil || !allowed {
|
||||
if allowed, err := authorize(context.Background(), 1, "listing/admin-tenant-a.jpg"); err != nil || !allowed {
|
||||
t.Fatalf("legacy admin file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateFileAuthorizerAllowsDeliveredQrCodeParticipants(t *testing.T) {
|
||||
db := openAuthorizerTestDB(t)
|
||||
tenants := []model.Tenant{
|
||||
{Code: "file_tenant_a", Name: "A站", Status: "active"},
|
||||
{Code: "file_tenant_b", Name: "B站", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&tenants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tenantA := tenants[0]
|
||||
tenantB := tenants[1]
|
||||
conversations := []model.ChatConversation{
|
||||
{TenantID: tenantA.ID, Type: "listing_group", Title: "A会话", Status: "active"},
|
||||
{TenantID: tenantB.ID, Type: "listing_group", Title: "B会话", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&conversations).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conversationA := conversations[0]
|
||||
conversationB := conversations[1]
|
||||
participants := []model.ChatParticipant{
|
||||
{ConversationID: conversationA.ID, ParticipantType: "user", ParticipantID: 31, Role: "renter", JoinedAt: time.Now()},
|
||||
{ConversationID: conversationB.ID, ParticipantType: "user", ParticipantID: 32, Role: "renter", JoinedAt: time.Now()},
|
||||
}
|
||||
if err := db.Create(&participants).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
qrcodes := []model.ChatQrCode{
|
||||
{TenantID: tenantA.ID, ImageURL: "/api/files/object?key=qrcode%2Fa.png", ConversationID: &conversationA.ID, Status: "used"},
|
||||
{TenantID: tenantB.ID, ImageURL: "/api/files/object?key=qrcode%2Fb.png", ConversationID: &conversationB.ID, Status: "used"},
|
||||
}
|
||||
if err := db.Create(&qrcodes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
userAuthorize := privateFileAuthorizer(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantA.ID})
|
||||
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantB.ID})
|
||||
if allowed, err := userAuthorize(ctxA, 31, "qrcode/a.png"); err != nil || !allowed {
|
||||
t.Fatalf("A participant qrcode allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := userAuthorize(ctxA, 32, "qrcode/b.png"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatal("cross-tenant qrcode must be denied")
|
||||
}
|
||||
|
||||
adminAuthorize := adminPrivateFileAuthorizer(db)
|
||||
if allowed, err := adminAuthorize(ctxA, 1, "qrcode/a.png"); err != nil || !allowed {
|
||||
t.Fatalf("A admin qrcode allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := adminAuthorize(ctxB, 1, "qrcode/a.png"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatal("cross-tenant admin qrcode must be denied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminPrivateFileAuthorizerAllowsOnlySuperAdminFinanceVouchers(t *testing.T) {
|
||||
db := openAuthorizerTestDB(t)
|
||||
roles := []model.Role{
|
||||
{Code: "super_admin", Name: "超级管理员"},
|
||||
{Code: "finance", Name: "财务"},
|
||||
}
|
||||
if err := db.Create(&roles).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admins := []model.AdminUser{
|
||||
{Username: "file-root", PasswordHash: "x", Status: "active"},
|
||||
{Username: "file-finance", PasswordHash: "x", Status: "active"},
|
||||
}
|
||||
if err := db.Create(&admins).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&[]model.AdminUserRole{
|
||||
{AdminID: admins[0].ID, RoleID: roles[0].ID, TenantID: 0},
|
||||
{AdminID: admins[1].ID, RoleID: roles[1].ID, TenantID: 101},
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO operating_expenses
|
||||
(expense_no, category, payee_name, amount_cent, occurred_at, remark, voucher_url, status, created_by)
|
||||
VALUES ('OE-FILE', '推广', '测试', 100, NOW(), '测试', ?, 'paid', ?)`,
|
||||
"/api/files/object?key=operating-expense%2Fvoucher.webp", admins[0].ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO manual_disbursements
|
||||
(disbursement_no, category, payee_name, amount_cent, paid_at, remark, voucher_url, status, created_by)
|
||||
VALUES ('OD-FILE', 'other', '测试', 100, NOW(), '测试', ?, 'paid', ?)`,
|
||||
"/api/files/object?key=manual-disbursement%2Fvoucher.webp", admins[0].ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
authorize := adminPrivateFileAuthorizer(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
for _, key := range []string{"operating-expense/voucher.webp", "manual-disbursement/voucher.webp"} {
|
||||
if allowed, err := authorize(ctxA, admins[0].ID, key); err != nil || !allowed {
|
||||
t.Fatalf("super admin %s allowed=%v err=%v", key, allowed, err)
|
||||
}
|
||||
if allowed, err := authorize(ctxA, admins[1].ID, key); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if allowed {
|
||||
t.Fatalf("tenant finance must not read %s", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
|
||||
@@ -479,6 +479,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
requirePerm := func(code string) gin.HandlerFunc {
|
||||
return middleware.RequirePermission(code, deps.Redis)
|
||||
}
|
||||
requirePlatformSuperAdmin := middleware.RequirePlatformSuperAdmin(deps.DB)
|
||||
requireAnyPerm := func(codes ...string) gin.HandlerFunc {
|
||||
return middleware.RequireAnyPermission(deps.Redis, codes...)
|
||||
}
|
||||
@@ -952,11 +953,11 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
adminRoutes.GET("/finance/dashboard", requirePerm("wallet:view"), adminFinanceHandler.Dashboard)
|
||||
adminRoutes.GET("/finance/details", requirePerm("wallet:view"), adminFinanceHandler.Details)
|
||||
adminRoutes.GET("/finance/disbursements", requirePerm("wallet:view"), adminFinanceHandler.Disbursements)
|
||||
adminRoutes.POST("/finance/manual-disbursements", requirePerm("finance:manual_disbursement"), adminFinanceHandler.CreateManualDisbursement)
|
||||
adminRoutes.POST("/finance/manual-disbursements/:id/void", requirePerm("finance:manual_disbursement"), adminFinanceHandler.VoidManualDisbursement)
|
||||
adminRoutes.GET("/finance/operating-expenses", requirePerm("finance:operating_expense"), adminFinanceHandler.OperatingExpenses)
|
||||
adminRoutes.POST("/finance/operating-expenses", requirePerm("finance:operating_expense"), adminFinanceHandler.CreateOperatingExpense)
|
||||
adminRoutes.POST("/finance/operating-expenses/:id/void", requirePerm("finance:operating_expense"), adminFinanceHandler.VoidOperatingExpense)
|
||||
adminRoutes.POST("/finance/manual-disbursements", requirePlatformSuperAdmin, requirePerm("finance:manual_disbursement"), adminFinanceHandler.CreateManualDisbursement)
|
||||
adminRoutes.POST("/finance/manual-disbursements/:id/void", requirePlatformSuperAdmin, requirePerm("finance:manual_disbursement"), adminFinanceHandler.VoidManualDisbursement)
|
||||
adminRoutes.GET("/finance/operating-expenses", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.OperatingExpenses)
|
||||
adminRoutes.POST("/finance/operating-expenses", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.CreateOperatingExpense)
|
||||
adminRoutes.POST("/finance/operating-expenses/:id/void", requirePlatformSuperAdmin, requirePerm("finance:operating_expense"), adminFinanceHandler.VoidOperatingExpense)
|
||||
adminRoutes.GET("/wallet/ledger", requirePerm("wallet:view"), walletHandler.AdminLedger)
|
||||
adminRoutes.GET("/payments", requirePerm("wallet:view"), paymentHandler.AdminList)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user