订单接口最小化与私有文件访问加固

- 订单列表使用独立最小 DTO 并分页,号主待办提供独立接口与统计
- 用户 token 增加版本控制,冻结/改密/退出即时撤销会话
- 移除 URL token 传参,SSE 与接口统一使用 HttpOnly Cookie
- 私有文件按上传归属与业务关联授权,收款凭证转私有访问并校验归属
- 公开商品接口返回最小字段,隐藏号主身份与内部状态
- 每日清理超过 30 天未关联业务的上传归属,上传归属失败时补偿删除对象
This commit is contained in:
yml2213
2026-08-16 21:47:46 +08:00
parent f48da14ed2
commit 85332df2bd
63 changed files with 1827 additions and 290 deletions
+108
View File
@@ -1,11 +1,119 @@
package router
import (
"context"
"net/url"
"strings"
"hfb_sys/backend/internal/model"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Dependencies struct {
DB *gorm.DB
Redis *redis.Client
}
// privateFileAuthorizer 仅允许对象所属用户、订单参与者或聊天成员读取私有文件。
// 未能关联到业务记录的对象默认拒绝,避免随机 key 成为访问凭证。
func privateFileAuthorizer(db *gorm.DB) func(context.Context, uint64, string) (bool, error) {
return func(ctx context.Context, userID uint64, key string) (bool, error) {
if db == nil || userID == 0 || key == "" {
return false, nil
}
encodedKey := url.QueryEscape(key)
var count int64
queries := []struct {
sql string
args []any
}{
{
sql: "SELECT COUNT(1) FROM file_upload_owners WHERE user_id = ? AND object_key = ?",
args: []any{userID, key},
},
{
sql: `SELECT COUNT(1) FROM game_accounts a
WHERE a.owner_id = ?
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
args: []any{userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM game_accounts a
JOIN rental_orders o ON o.account_id = a.id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM order_checkouts c
JOIN rental_orders o ON o.id = c.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM disputes d
JOIN rental_orders o ON o.id = d.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM handoff_records h
JOIN rental_orders o ON o.id = h.order_id
WHERE (o.owner_id = ? OR o.renter_id = ?)
AND (INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0)`,
args: []any{userID, userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM chat_messages m
JOIN chat_participants p ON p.conversation_id = m.conversation_id
WHERE p.participant_type = 'user' AND p.participant_id = ?
AND (INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0)`,
args: []any{userID, key, encodedKey},
},
{
sql: `SELECT COUNT(1) FROM user_payment_accounts p
WHERE p.user_id = ?
AND (INSTR(p.certificate_urls, ?) > 0 OR INSTR(p.certificate_urls, ?) > 0)`,
args: []any{userID, key, encodedKey},
},
}
for _, query := range queries {
if err := db.WithContext(ctx).Raw(query.sql, query.args...).Scan(&count).Error; err != nil {
// 旧库缺少新表时继续检查其他可用关联,其他数据库错误则安全拒绝。
if strings.Contains(strings.ToLower(err.Error()), "no such table") || strings.Contains(strings.ToLower(err.Error()), "doesn't exist") {
continue
}
return false, err
}
if count > 0 {
return true, nil
}
}
return false, nil
}
}
// 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 {
return nil
}
records := make([]model.FileUploadOwner, 0, len(objectKeys))
for _, key := range objectKeys {
if key == "" {
continue
}
records = append(records, model.FileUploadOwner{UserID: userID, ObjectKey: key})
}
if len(records) == 0 {
return nil
}
return db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&records).Error
}
}
@@ -0,0 +1,115 @@
package router
import (
"context"
"testing"
"hfb_sys/backend/internal/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func TestPrivateFileAuthorizer(t *testing.T) {
db := openAuthorizerTestDB(t)
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
createAuthorizerBusinessTables(t, db)
if err := db.Create(&model.FileUploadOwner{UserID: 11, ObjectKey: "listing/draft.jpg"}).Error; err != nil {
t.Fatalf("create upload owner error = %v", err)
}
if err := db.Exec("INSERT INTO game_accounts (id, owner_id, screenshot_urls) VALUES (1, 21, ?), (2, 23, ?)", `["/api/files/object?key=listing%2Faccount.jpg"]`, `["/api/files/object?key=listing%2Fno-order.jpg"]`).Error; err != nil {
t.Fatalf("create account error = %v", err)
}
if err := db.Exec("INSERT INTO rental_orders (id, account_id, owner_id, renter_id) VALUES (1, 1, 21, 22)").Error; err != nil {
t.Fatalf("create order error = %v", err)
}
if err := db.Exec("INSERT INTO chat_messages (id, conversation_id, attachment_urls) VALUES (1, 8, ?)", `["/api/files/object?key=chat%2Fmessage.jpg"]`).Error; err != nil {
t.Fatalf("create chat message error = %v", err)
}
if err := db.Exec("INSERT INTO chat_participants (id, conversation_id, participant_type, participant_id) VALUES (1, 8, 'user', 31)").Error; err != nil {
t.Fatalf("create chat participant error = %v", err)
}
if err := db.Exec("INSERT INTO user_payment_accounts (id, user_id, certificate_urls) VALUES (1, 41, ?)", `["/api/files/object?key=payment-cert%2Fqr.jpg"]`).Error; err != nil {
t.Fatalf("create payment account error = %v", err)
}
authorize := privateFileAuthorizer(db)
cases := []struct {
name string
userID uint64
key string
allowed bool
}{
{name: "上传者可预览草稿", userID: 11, key: "listing/draft.jpg", allowed: true},
{name: "账号所有者可读取未出租账号截图", userID: 23, key: "listing/no-order.jpg", allowed: true},
{name: "订单参与人可读取截图", userID: 22, key: "listing/account.jpg", allowed: true},
{name: "聊天成员可读取附件", userID: 31, key: "chat/message.jpg", allowed: true},
{name: "收款账号所有者可读取凭证", userID: 41, key: "payment-cert/qr.jpg", allowed: true},
{name: "无关联用户被拒绝", userID: 99, key: "listing/account.jpg", allowed: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
allowed, err := authorize(context.Background(), tc.userID, tc.key)
if err != nil {
t.Fatalf("authorize() error = %v", err)
}
if allowed != tc.allowed {
t.Fatalf("authorize() = %v, want %v", allowed, tc.allowed)
}
})
}
}
func TestRecordPrivateFileUpload(t *testing.T) {
db := openAuthorizerTestDB(t)
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
}
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 {
t.Fatalf("record() error = %v", err)
}
if err := record(context.Background(), 11, keys); err != nil {
t.Fatalf("duplicate record() error = %v", err)
}
var count int64
if err := db.Model(&model.FileUploadOwner{}).Where("user_id = ?", 11).Count(&count).Error; err != nil {
t.Fatalf("count records error = %v", err)
}
if count != int64(len(keys)) {
t.Fatalf("record count = %d, want %d", count, len(keys))
}
}
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Fatalf("open sqlite error = %v", err)
}
return db
}
func createAuthorizerBusinessTables(t *testing.T, db *gorm.DB) {
t.Helper()
statements := []string{
"CREATE TABLE game_accounts (id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL, screenshot_urls TEXT)",
"CREATE TABLE rental_orders (id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, owner_id INTEGER NOT NULL, renter_id INTEGER NOT NULL)",
"CREATE TABLE order_checkouts (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, evidence_urls TEXT)",
"CREATE TABLE disputes (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, evidence_urls TEXT)",
"CREATE TABLE handoff_records (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, attachment_urls TEXT)",
"CREATE TABLE chat_messages (id INTEGER PRIMARY KEY, conversation_id INTEGER NOT NULL, attachment_urls TEXT)",
"CREATE TABLE chat_participants (id INTEGER PRIMARY KEY, conversation_id INTEGER NOT NULL, participant_type TEXT NOT NULL, participant_id INTEGER NOT NULL)",
"CREATE TABLE user_payment_accounts (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, certificate_urls TEXT)",
}
for _, statement := range statements {
if err := db.Exec(statement).Error; err != nil {
t.Fatalf("create test table error = %v", err)
}
}
}
+12 -4
View File
@@ -355,7 +355,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
}
}
fileService := filemodule.NewService(fileStorage)
fileHandler := filemodule.NewHandler(fileService, fileStorage)
fileHandler := filemodule.NewHandler(fileService, fileStorage, privateFileAuthorizer(deps.DB), recordPrivateFileUpload(deps.DB))
listingService := listing.NewService(listingRepo, systemConfigRepo)
listingHandler := listing.NewHandler(listingService, fileStorage, listing.HandlerOptions{
ExternalUploadSecret: cfg.ExternalUploadSecret,
@@ -367,7 +367,14 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
}
announcementService := announcement.NewService(announcementRepo)
announcementHandler := announcement.NewHandler(announcementService)
requireAuth := middleware.Auth(jwtManager)
var validateUserToken middleware.UserTokenValidatorFunc
if userRepo != nil {
validateUserToken = func(ctx context.Context, userID uint64, tokenVersion int64) error {
_, err := userRepo.FindActiveForToken(ctx, userID, tokenVersion)
return err
}
}
requireAuth := middleware.Auth(jwtManager, validateUserToken)
var validateAdminToken middleware.AdminTokenValidatorFunc
if adminAuthRepo != nil {
validateAdminToken = func(ctx context.Context, adminID uint64, tokenVersion int64) (middleware.AdminTokenContext, error) {
@@ -416,7 +423,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
authRoutes.POST("/password/register", authHandler.Register)
authRoutes.POST("/password/reset", authHandler.ResetPassword)
authRoutes.POST("/refresh", authHandler.Refresh)
authRoutes.POST("/logout", authHandler.Logout)
authRoutes.POST("/logout", requireAuth, authHandler.Logout)
}
api.GET("/me", requireAuth, userHandler.Me)
@@ -474,6 +481,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
{
orderRoutes.POST("", requireRealname, orderHandler.Create)
orderRoutes.GET("", orderHandler.List)
orderRoutes.GET("/handoffs", orderHandler.ListSellerHandoffs)
orderRoutes.GET("/:id", orderHandler.Detail)
orderRoutes.GET("/:id/chat", chatHandler.OrderConversation)
orderRoutes.POST("/:id/pay", orderHandler.Pay)
@@ -589,7 +597,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
adminRoutes.POST("/users/:id/manual-realname", requirePerm("user:manual_realname"), adminUserHandler.ManualRealname)
adminRoutes.POST("/users/:id/revoke-realname", requirePerm("user:revoke_realname"), adminUserHandler.RevokeRealname)
adminRoutes.POST("/users/:id/wallet/adjust", requirePerm("user:wallet_adjust"), adminUserHandler.AdjustWallet)
adminRoutes.GET("/orders", requirePerm("order:view"), orderHandler.AdminList)
adminRoutes.GET("/orders", requirePerm("order:list"), orderHandler.AdminList)
adminRoutes.GET("/listing-orders/:id/latest", requirePerm("order:view"), orderHandler.AdminLatestByListing)
adminRoutes.GET("/orders/:id", requirePerm("order:view"), orderHandler.AdminDetail)
adminRoutes.GET("/orders/:id/handoff-records", requirePerm("order:view"), orderHandler.AdminHandoffRecords)