fix(tenant): 封堵审计文件与历史用户跨站访问
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
@@ -16,6 +17,7 @@ type Meta struct {
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
TenantID uint64
|
||||
ActorType string
|
||||
ActorID uint64
|
||||
Action string
|
||||
@@ -31,7 +33,12 @@ func Append(tx *gorm.DB, entry Entry) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantID := entry.TenantID
|
||||
if tenantID == 0 && tx.Statement != nil && tx.Statement.Context != nil {
|
||||
tenantID = tenancy.IDFromContext(tx.Statement.Context)
|
||||
}
|
||||
row := model.AuditLog{
|
||||
TenantID: tenantID,
|
||||
ActorType: entry.ActorType,
|
||||
ActorID: entry.ActorID,
|
||||
Action: entry.Action,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestAppendUsesTenantFromTransactionContext(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
|
||||
var row model.AuditLog
|
||||
if err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return Append(tx, Entry{
|
||||
ActorType: "admin",
|
||||
ActorID: 1,
|
||||
Action: "test.tenant_audit",
|
||||
BizType: "test",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Where("action = ?", "test.tenant_audit").First(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if row.TenantID != 101 {
|
||||
t.Fatalf("audit tenant = %d, want 101", row.TenantID)
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,7 @@ func appendManagedTimeoutNotification(tx *gorm.DB, order *model.RentalOrder, tit
|
||||
return nil
|
||||
}
|
||||
return adminnotification.Append(tx, adminnotification.Entry{
|
||||
TenantID: order.BuyerTenantID,
|
||||
AdminUserID: *order.ManagedAdminID,
|
||||
Type: "timeout",
|
||||
Title: title,
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
type AuditLog struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;default:0;index:idx_audit_logs_tenant_created" json:"tenant_id"`
|
||||
ActorType string `gorm:"size:32;not null" json:"actor_type"`
|
||||
ActorID uint64 `gorm:"not null;index" json:"actor_id"`
|
||||
Action string `gorm:"size:64;not null" json:"action"`
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
@@ -26,6 +27,10 @@ func (r *Repository) List(ctx context.Context, query Query) (*PaginatedResult, e
|
||||
Joins("LEFT JOIN admin_users AS au ON au.id = al.actor_id AND al.actor_type = ?", "admin")
|
||||
|
||||
countDB := r.db.WithContext(ctx).Model(&model.AuditLog{})
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
db = db.Where("al.tenant_id = ?", tenantID)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if query.ActorID > 0 {
|
||||
db = db.Where("al.actor_id = ?", query.ActorID)
|
||||
countDB = countDB.Where("actor_id = ?", query.ActorID)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package adminaudit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
func TestListIsScopedByOperatingTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
rows := []model.AuditLog{
|
||||
{TenantID: 101, ActorType: "admin", ActorID: 1, Action: "tenant.a", BizType: "test"},
|
||||
{TenantID: 202, ActorType: "admin", ActorID: 2, Action: "tenant.b", BizType: "test"},
|
||||
{TenantID: 0, ActorType: "admin", ActorID: 3, Action: "platform", BizType: "test"},
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
result, err := NewRepository(db).List(ctx, Query{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items := result.Items.([]LogDTO)
|
||||
if result.Total != 1 || len(items) != 1 || items[0].Action != "tenant.a" {
|
||||
t.Fatalf("tenant audit list = %+v", result)
|
||||
}
|
||||
}
|
||||
@@ -104,17 +104,8 @@ func Append(tx *gorm.DB, entries ...Entry) error {
|
||||
continue
|
||||
}
|
||||
tenantID := entry.TenantID
|
||||
if tenantID == 0 {
|
||||
var row struct {
|
||||
TenantID uint64
|
||||
}
|
||||
if err := tx.Table("admin_user_roles").
|
||||
Select("tenant_id").
|
||||
Where("admin_user_id = ? AND tenant_id > 0", entry.AdminUserID).
|
||||
Order("tenant_id ASC").
|
||||
Take(&row).Error; err == nil {
|
||||
tenantID = row.TenantID
|
||||
}
|
||||
if tenantID == 0 && tx.Statement != nil && tx.Statement.Context != nil {
|
||||
tenantID = tenancy.IDFromContext(tx.Statement.Context)
|
||||
}
|
||||
row := model.AdminNotification{
|
||||
TenantID: tenantID,
|
||||
|
||||
@@ -7,6 +7,9 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||
@@ -103,3 +106,31 @@ func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||
t.Fatalf("MarkRead() error = %v, want ErrNotificationNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendUsesExplicitOrContextTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 202})
|
||||
appendNotification := func(entry Entry) {
|
||||
t.Helper()
|
||||
if err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
return Append(tx, entry)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
appendNotification(Entry{AdminUserID: 7, Type: "system", Title: "上下文站点", Content: "x"})
|
||||
appendNotification(Entry{TenantID: 101, AdminUserID: 7, Type: "system", Title: "显式站点", Content: "y"})
|
||||
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||
return Append(tx, Entry{AdminUserID: 7, Type: "platform", Title: "平台站点", Content: "z"})
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var rows []model.AdminNotification
|
||||
if err := db.Order("id ASC").Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 3 || rows[0].TenantID != 202 || rows[1].TenantID != 101 || rows[2].TenantID != 0 {
|
||||
t.Fatalf("admin notification tenants = %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +168,11 @@ func (r *Repository) adminListBase(ctx context.Context, query AnnouncementListQu
|
||||
Select("a.id, a.distribution_site_id, COALESCE(s.site_name, '') AS distribution_site_name, a.title, a.content, a.category, a.priority, a.is_pinned, a.is_important, a.is_popup, a.view_count, a.status, a.published_at, a.created_at, a.updated_at").
|
||||
Joins("LEFT JOIN distribution_sites AS s ON s.id = a.distribution_site_id")
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
base = base.Where("a.tenant_id = ?", tenantID)
|
||||
base = base.
|
||||
Where("a.tenant_id = ?", tenantID).
|
||||
Where("(a.distribution_site_id = 0 OR a.distribution_site_id IS NULL)")
|
||||
} else if query.AdminSiteID != nil {
|
||||
base = base.Where("a.distribution_site_id = ?", *query.AdminSiteID)
|
||||
}
|
||||
|
||||
if query.Status != "" {
|
||||
@@ -177,9 +181,6 @@ func (r *Repository) adminListBase(ctx context.Context, query AnnouncementListQu
|
||||
if query.Category != "" {
|
||||
base = base.Where("a.category = ?", query.Category)
|
||||
}
|
||||
if query.AdminSiteID != nil {
|
||||
base = base.Where("a.distribution_site_id = ?", *query.AdminSiteID)
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
@@ -199,9 +200,13 @@ func (r *Repository) AdminGetByID(ctx context.Context, id uint64) (*Announcement
|
||||
|
||||
// Create 创建公告
|
||||
func (r *Repository) Create(ctx context.Context, req CreateAnnouncementRequest, createdBy uint64) (*AnnouncementDTO, error) {
|
||||
siteID := req.DistributionSiteID
|
||||
if tenancy.IDFromContext(ctx) > 0 {
|
||||
siteID = 0
|
||||
}
|
||||
announcement := model.Announcement{
|
||||
TenantID: tenancy.IDFromContext(ctx),
|
||||
DistributionSiteID: req.DistributionSiteID,
|
||||
DistributionSiteID: siteID,
|
||||
Title: req.Title,
|
||||
Content: req.Content,
|
||||
Category: req.Category,
|
||||
@@ -241,7 +246,9 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAnnounceme
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
if err := query.Updates(updates).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -255,7 +262,9 @@ func (r *Repository) Publish(ctx context.Context, id uint64) error {
|
||||
now := time.Now()
|
||||
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
return query.
|
||||
Updates(map[string]interface{}{
|
||||
@@ -268,7 +277,9 @@ func (r *Repository) Publish(ctx context.Context, id uint64) error {
|
||||
func (r *Repository) Archive(ctx context.Context, id uint64) error {
|
||||
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
return query.
|
||||
Update("status", "archived").Error
|
||||
@@ -279,7 +290,9 @@ func (r *Repository) Unarchive(ctx context.Context, id uint64) error {
|
||||
now := time.Now()
|
||||
query := r.db.WithContext(ctx).Model(&model.Announcement{}).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
return query.
|
||||
Updates(map[string]interface{}{
|
||||
@@ -292,7 +305,9 @@ func (r *Repository) Unarchive(ctx context.Context, id uint64) error {
|
||||
func (r *Repository) Delete(ctx context.Context, id uint64) error {
|
||||
query := r.db.WithContext(ctx).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.
|
||||
Where("tenant_id = ?", tenantID).
|
||||
Where("(distribution_site_id = 0 OR distribution_site_id IS NULL)")
|
||||
}
|
||||
return query.Delete(&model.Announcement{}).Error
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
)
|
||||
|
||||
// TestPublicScopeAndSiteIsolation 覆盖公告中心的分站可见范围:
|
||||
@@ -175,6 +176,47 @@ func TestAdminListFiltersBySite(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAdminAnnouncementsExcludeLegacyDistributionSite(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
repo := NewRepository(db)
|
||||
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "ann_legacy_tenant", SiteName: "历史公告站",
|
||||
Domain: "ann-legacy-tenant.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := []model.Announcement{
|
||||
{TenantID: 101, Title: "本站公告", Content: "x", Category: "notice", Status: "draft"},
|
||||
{TenantID: 101, DistributionSiteID: site.ID, Title: "历史分销公告", Content: "y", Category: "notice", Status: "draft"},
|
||||
{TenantID: 202, Title: "其他站点公告", Content: "z", Category: "notice", Status: "draft"},
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := repo.AdminList(ctx, AnnouncementListQuery{
|
||||
AdminSiteID: &site.ID, Page: 1, PageSize: 20,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items := result.Items.([]AnnouncementDTO)
|
||||
if result.Total != 1 || len(items) != 1 || items[0].Title != "本站公告" {
|
||||
t.Fatalf("tenant announcement list = %+v", result)
|
||||
}
|
||||
|
||||
created, err := repo.Create(ctx, CreateAnnouncementRequest{
|
||||
DistributionSiteID: site.ID, Title: "强制本站", Content: "content", Category: "notice",
|
||||
}, 9)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.TenantID != 101 || created.DistributionSiteID != 0 {
|
||||
t.Fatalf("tenant announcement scope = %+v", created)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublicPopupSelection 覆盖弹窗公告的选取口径:
|
||||
// 只有 published + is_popup 才参与,站点范围内按优先级取最高的一条,无候选时返回 nil。
|
||||
func TestPublicPopupSelection(t *testing.T) {
|
||||
|
||||
@@ -311,6 +311,8 @@ func writeAuthError(c *gin.Context, err error) {
|
||||
response.Error(c, http.StatusTooManyRequests, "login_locked", "登录失败次数过多,请 15 分钟后再试")
|
||||
case errors.Is(err, ErrUserAlreadyExists):
|
||||
response.BadRequest(c, "该手机号已注册,请直接登录或使用短信验证码登录")
|
||||
case errors.Is(err, ErrLegacyDistributionUser):
|
||||
response.Error(c, http.StatusForbidden, "legacy_distribution_user", "该手机号属于历史分销渠道,请从原分销站点登录")
|
||||
default:
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "服务暂时不可用")
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User,
|
||||
var user model.User
|
||||
query := r.db.WithContext(ctx)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&user, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -52,7 +52,7 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
|
||||
var user model.User
|
||||
query := r.db.WithContext(ctx)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.
|
||||
Select("id, phone, status, token_version").
|
||||
@@ -71,7 +71,7 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
|
||||
func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname string, avatarURL string) (*model.User, error) {
|
||||
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.Updates(map[string]any{
|
||||
"nickname": nickname,
|
||||
@@ -98,6 +98,29 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
now := time.Now()
|
||||
code := sanitizeTrackCode(trackCode)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID > 0 {
|
||||
var existing model.User
|
||||
query := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id = 0", tenantID, phone)
|
||||
if err := query.First(&existing).Error; err == nil {
|
||||
_ = r.db.WithContext(ctx).Model(&existing).Updates(map[string]any{
|
||||
"last_login_at": now,
|
||||
"updated_at": now,
|
||||
}).Error
|
||||
return &existing, nil
|
||||
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
var legacyCount int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenantID, phone).
|
||||
Count(&legacyCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
var siteID uint64
|
||||
if len(siteCode) > 0 {
|
||||
siteID = r.resolveSiteID(ctx, siteCode[0])
|
||||
@@ -131,7 +154,7 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
|
||||
var found model.User
|
||||
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&found).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -143,9 +166,20 @@ func (r *UserRepository) FindByPhone(ctx context.Context, phone string) (*model.
|
||||
var user model.User
|
||||
query := r.db.WithContext(ctx).Where("phone = ?", phone)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
if err := query.First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) && tenancy.IDFromContext(ctx) > 0 {
|
||||
var legacyCount int64
|
||||
if countErr := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenancy.IDFromContext(ctx), phone).
|
||||
Count(&legacyCount).Error; countErr != nil {
|
||||
return nil, countErr
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
@@ -154,7 +188,7 @@ func (r *UserRepository) FindByPhone(ctx context.Context, phone string) (*model.
|
||||
func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash string) error {
|
||||
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
return query.Updates(map[string]any{
|
||||
"password_hash": hash,
|
||||
@@ -166,7 +200,7 @@ func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash st
|
||||
func (r *UserRepository) RevokeTokens(ctx context.Context, userID uint64) error {
|
||||
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
|
||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||
}
|
||||
return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
|
||||
}
|
||||
@@ -175,6 +209,17 @@ func (r *UserRepository) RegisterWithPassword(ctx context.Context, phone string,
|
||||
now := time.Now()
|
||||
code := sanitizeTrackCode(trackCode)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID > 0 {
|
||||
var legacyCount int64
|
||||
if err := r.db.WithContext(ctx).Model(&model.User{}).
|
||||
Where("tenant_id = ? AND phone = ? AND distribution_site_id > 0", tenantID, phone).
|
||||
Count(&legacyCount).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if legacyCount > 0 {
|
||||
return nil, ErrLegacyDistributionUser
|
||||
}
|
||||
}
|
||||
var siteID uint64
|
||||
if len(siteCode) > 0 {
|
||||
siteID = r.resolveSiteID(ctx, siteCode[0])
|
||||
|
||||
@@ -22,20 +22,21 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidPhone = errors.New("invalid phone")
|
||||
ErrCaptchaInvalid = errors.New("captcha invalid")
|
||||
ErrCodeRateLimited = errors.New("sms code rate limited")
|
||||
ErrCodeInvalid = errors.New("sms code invalid")
|
||||
ErrSMSSendFailed = errors.New("sms send failed")
|
||||
ErrUserDisabled = errors.New("user disabled")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrInvalidOldPassword = errors.New("invalid old password")
|
||||
ErrPasswordNotSet = errors.New("password not set")
|
||||
ErrPasswordTooWeak = errors.New("password too weak")
|
||||
ErrLoginLocked = errors.New("login locked")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrTokenVersionMismatch = errors.New("user token version mismatch")
|
||||
ErrDependencyUnavailable = errors.New("dependency unavailable")
|
||||
ErrInvalidPhone = errors.New("invalid phone")
|
||||
ErrCaptchaInvalid = errors.New("captcha invalid")
|
||||
ErrCodeRateLimited = errors.New("sms code rate limited")
|
||||
ErrCodeInvalid = errors.New("sms code invalid")
|
||||
ErrSMSSendFailed = errors.New("sms send failed")
|
||||
ErrUserDisabled = errors.New("user disabled")
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrInvalidOldPassword = errors.New("invalid old password")
|
||||
ErrPasswordNotSet = errors.New("password not set")
|
||||
ErrPasswordTooWeak = errors.New("password too weak")
|
||||
ErrLoginLocked = errors.New("login locked")
|
||||
ErrUserAlreadyExists = errors.New("user already exists")
|
||||
ErrLegacyDistributionUser = errors.New("user belongs to legacy distribution channel")
|
||||
ErrTokenVersionMismatch = errors.New("user token version mismatch")
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
@@ -85,3 +86,39 @@ func TestTenantUsersRemainSeparateRows(t *testing.T) {
|
||||
t.Fatalf("same phone user count = %d, want 2", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyDistributionUserCannotEnterTenantSite(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
site := model.DistributionSite{
|
||||
SiteCode: "legacy_auth_scope", SiteName: "历史分销测试站",
|
||||
Domain: "legacy-auth-scope.example.com", Status: "active",
|
||||
}
|
||||
if err := db.Create(&site).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacy := model.User{
|
||||
TenantID: 101, Phone: "13600000009", Status: "active",
|
||||
DistributionSiteID: site.ID, TokenVersion: 1,
|
||||
}
|
||||
if err := db.Create(&legacy).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewUserRepository(db)
|
||||
ctx := authTenantContext(101)
|
||||
|
||||
if _, err := repo.FindByID(ctx, legacy.ID); err == nil {
|
||||
t.Fatal("tenant site must not load legacy distribution user")
|
||||
}
|
||||
if _, err := repo.FindByPhone(ctx, legacy.Phone); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy phone login error = %v", err)
|
||||
}
|
||||
if _, err := repo.FindOrCreateByPhone(ctx, legacy.Phone, ""); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy SMS login error = %v", err)
|
||||
}
|
||||
if _, err := repo.RegisterWithPassword(ctx, legacy.Phone, "hash", ""); !errors.Is(err, ErrLegacyDistributionUser) {
|
||||
t.Fatalf("legacy registration error = %v", err)
|
||||
}
|
||||
if _, err := repo.FindByPhone(context.Background(), legacy.Phone); err != nil {
|
||||
t.Fatalf("legacy distribution domain login failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,6 +416,7 @@ func appendPlatformManagedAdminNotification(tx *gorm.DB, order model.RentalOrder
|
||||
return nil
|
||||
}
|
||||
return adminnotification.Append(tx, adminnotification.Entry{
|
||||
TenantID: order.BuyerTenantID,
|
||||
AdminUserID: *order.ManagedAdminID,
|
||||
Type: typ,
|
||||
Title: title,
|
||||
|
||||
@@ -14,24 +14,33 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
storage *Storage
|
||||
objectAuthorizer ObjectAuthorizer
|
||||
uploadOwnerRecorder UploadOwnerRecorder
|
||||
service *Service
|
||||
storage *Storage
|
||||
objectAuthorizer ObjectAuthorizer
|
||||
adminObjectAuthorizer AdminObjectAuthorizer
|
||||
uploadOwnerRecorder UploadOwnerRecorder
|
||||
}
|
||||
|
||||
// ObjectAuthorizer 校验用户是否可读取指定私有对象。
|
||||
type ObjectAuthorizer func(ctx context.Context, userID uint64, key string) (bool, error)
|
||||
|
||||
// AdminObjectAuthorizer 校验管理员是否可在当前经营站点读取指定私有对象。
|
||||
type AdminObjectAuthorizer func(ctx context.Context, adminID uint64, key string) (bool, error)
|
||||
|
||||
// UploadOwnerRecorder 保存用户上传私有文件的归属。
|
||||
type UploadOwnerRecorder func(ctx context.Context, userID uint64, objectKeys []string) error
|
||||
|
||||
func NewHandler(service *Service, storage *Storage, objectAuthorizer ObjectAuthorizer, uploadOwnerRecorder UploadOwnerRecorder) *Handler {
|
||||
func NewHandler(service *Service, storage *Storage, objectAuthorizer ObjectAuthorizer, uploadOwnerRecorder UploadOwnerRecorder, adminObjectAuthorizers ...AdminObjectAuthorizer) *Handler {
|
||||
var adminObjectAuthorizer AdminObjectAuthorizer
|
||||
if len(adminObjectAuthorizers) > 0 {
|
||||
adminObjectAuthorizer = adminObjectAuthorizers[0]
|
||||
}
|
||||
return &Handler{
|
||||
service: service,
|
||||
storage: storage,
|
||||
objectAuthorizer: objectAuthorizer,
|
||||
uploadOwnerRecorder: uploadOwnerRecorder,
|
||||
service: service,
|
||||
storage: storage,
|
||||
objectAuthorizer: objectAuthorizer,
|
||||
adminObjectAuthorizer: adminObjectAuthorizer,
|
||||
uploadOwnerRecorder: uploadOwnerRecorder,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +108,22 @@ func (h *Handler) writeObject(c *gin.Context, publicOnly bool) {
|
||||
return
|
||||
}
|
||||
if !publicOnly {
|
||||
if _, isAdmin := c.Get("admin_id"); !isAdmin {
|
||||
if adminIDValue, isAdmin := c.Get("admin_id"); isAdmin {
|
||||
adminID, ok := adminIDValue.(uint64)
|
||||
if !ok || h.adminObjectAuthorizer == nil {
|
||||
response.Error(c, http.StatusForbidden, "forbidden", "无权访问该文件")
|
||||
return
|
||||
}
|
||||
allowed, err := h.adminObjectAuthorizer(c.Request.Context(), adminID, key)
|
||||
if err != nil {
|
||||
response.ServiceUnavailable(c, "文件权限校验失败")
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
response.Error(c, http.StatusForbidden, "forbidden", "无权访问该文件")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
userID, ok := c.Get("user_id")
|
||||
if !ok {
|
||||
response.Unauthorized(c, "缺少用户上下文")
|
||||
|
||||
@@ -182,7 +182,7 @@ func Append(tx *gorm.DB, entries ...Entry) error {
|
||||
} else if entry.BizType == "dispute" && entry.BizID != nil && *entry.BizID > 0 {
|
||||
var orderSiteID *uint64
|
||||
var mode string
|
||||
row := tx.Table("order_disputes d").Joins("JOIN rental_orders o ON o.id = d.order_id").Where("d.id = ?", *entry.BizID).Select("o.distribution_site_id, o.distribution_mode").Row()
|
||||
row := tx.Table("disputes d").Joins("JOIN rental_orders o ON o.id = d.order_id").Where("d.id = ?", *entry.BizID).Select("o.distribution_site_id, o.distribution_mode").Row()
|
||||
if err := row.Scan(&orderSiteID, &mode); err == nil && orderSiteID != nil && mode != "two_party_distributor_receive" {
|
||||
siteID = orderSiteID
|
||||
}
|
||||
|
||||
@@ -191,6 +191,27 @@ func TestNotificationTenantIsolation(t *testing.T) {
|
||||
if autoNotif.DistributionSiteID == nil || *autoNotif.DistributionSiteID != siteID {
|
||||
t.Fatalf("autoNotif.DistributionSiteID = %v, want %d", autoNotif.DistributionSiteID, siteID)
|
||||
}
|
||||
dispute := model.Dispute{
|
||||
OrderID: orderID, InitiatorID: 20, InitiatorType: "user",
|
||||
TargetUserID: 21, Type: "cannot_login", Status: "open",
|
||||
}
|
||||
if err := db.Create(&dispute).Error; err != nil {
|
||||
t.Fatalf("create dispute error: %v", err)
|
||||
}
|
||||
disputeID := dispute.ID
|
||||
if err := Append(db, Entry{
|
||||
UserID: 20, Type: "dispute", Title: "申诉自动关联分站", Content: "自动读取申诉订单站点",
|
||||
BizType: "dispute", BizID: &disputeID,
|
||||
}); err != nil {
|
||||
t.Fatalf("Append dispute auto lookup error: %v", err)
|
||||
}
|
||||
var disputeNotif model.Notification
|
||||
if err := db.Where("biz_id = ? AND biz_type = 'dispute'", disputeID).First(&disputeNotif).Error; err != nil {
|
||||
t.Fatalf("find dispute notification error: %v", err)
|
||||
}
|
||||
if disputeNotif.DistributionSiteID == nil || *disputeNotif.DistributionSiteID != siteID {
|
||||
t.Fatalf("dispute notification site = %v, want %d", disputeNotif.DistributionSiteID, siteID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationTenantScopeAndAppendDerivation(t *testing.T) {
|
||||
|
||||
@@ -34,6 +34,7 @@ func appendManagedAdminNotification(tx *gorm.DB, order model.RentalOrder, typ st
|
||||
return nil
|
||||
}
|
||||
return adminnotification.Append(tx, adminnotification.Entry{
|
||||
TenantID: order.BuyerTenantID,
|
||||
AdminUserID: adminID,
|
||||
Type: typ,
|
||||
Title: title,
|
||||
|
||||
@@ -135,6 +135,92 @@ 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) {
|
||||
if db == nil || key == "" {
|
||||
return false, nil
|
||||
}
|
||||
encodedKey := url.QueryEscape(key)
|
||||
basePrefix := strings.TrimSuffix(strings.TrimSuffix(key, ".medium.jpg"), ".thumb.jpg")
|
||||
encodedBasePrefix := url.QueryEscape(basePrefix)
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
|
||||
queries := []struct {
|
||||
sql string
|
||||
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 game_accounts a
|
||||
JOIN rental_listings l ON l.account_id = a.id
|
||||
WHERE (? = 0 OR (l.source_tenant_id = ? AND (l.distribution_site_id IS NULL OR l.distribution_site_id = 0)))
|
||||
AND (INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0 OR INSTR(a.screenshot_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM order_checkouts c
|
||||
JOIN rental_orders o ON o.id = c.order_id
|
||||
WHERE (? = 0 OR (o.buyer_tenant_id = ? AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0)))
|
||||
AND (INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0 OR INSTR(c.evidence_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM disputes d
|
||||
JOIN rental_orders o ON o.id = d.order_id
|
||||
WHERE (? = 0 OR (o.buyer_tenant_id = ? AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0)))
|
||||
AND (INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0 OR INSTR(d.evidence_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM handoff_records h
|
||||
JOIN rental_orders o ON o.id = h.order_id
|
||||
WHERE (? = 0 OR ((o.buyer_tenant_id = ? OR o.source_tenant_id = ?)
|
||||
AND (o.distribution_site_id IS NULL OR o.distribution_site_id = 0)))
|
||||
AND (INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0 OR INSTR(h.attachment_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM chat_messages m
|
||||
JOIN chat_conversations c ON c.id = m.conversation_id
|
||||
WHERE (? = 0 OR c.tenant_id = ?)
|
||||
AND (INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0 OR INSTR(m.attachment_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM user_payment_accounts p
|
||||
JOIN users u ON u.id = p.user_id
|
||||
WHERE (? = 0 OR (p.tenant_id = ? AND u.tenant_id = ? AND u.distribution_site_id = 0))
|
||||
AND (INSTR(p.certificate_urls, ?) > 0 OR INSTR(p.certificate_urls, ?) > 0 OR INSTR(p.certificate_urls, ?) > 0 OR INSTR(p.certificate_urls, ?) > 0)`,
|
||||
args: []any{tenantID, tenantID, tenantID, key, encodedKey, basePrefix, encodedBasePrefix},
|
||||
},
|
||||
{
|
||||
sql: `SELECT COUNT(1) FROM withdrawal_requests w
|
||||
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},
|
||||
},
|
||||
}
|
||||
for _, query := range queries {
|
||||
var count int64
|
||||
if err := db.WithContext(ctx).Raw(query.sql, query.args...).Scan(&count).Error; err != nil {
|
||||
if 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 {
|
||||
|
||||
@@ -130,6 +130,38 @@ func TestPrivateFileAuthorizerRejectsCrossTenantOwner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminPrivateFileAuthorizerScopesOperatingTenant(t *testing.T) {
|
||||
db := openAuthorizerTestDB(t)
|
||||
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||
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"},
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatalf("create upload owners: %v", err)
|
||||
}
|
||||
authorize := adminPrivateFileAuthorizer(db)
|
||||
ctxA := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
||||
ctxB := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 202})
|
||||
|
||||
if allowed, err := authorize(ctxA, 1, "listing/admin-tenant-a.jpg"); err != nil || !allowed {
|
||||
t.Fatalf("tenant A own file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
if allowed, err := authorize(ctxA, 1, "listing/admin-tenant-b.jpg"); err != nil {
|
||||
t.Fatalf("tenant A cross file error=%v", err)
|
||||
} else if allowed {
|
||||
t.Fatal("tenant A must not read tenant B file")
|
||||
}
|
||||
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 {
|
||||
t.Fatalf("legacy admin file allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
|
||||
@@ -426,7 +426,13 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
}
|
||||
}
|
||||
fileService := filemodule.NewService(fileStorage)
|
||||
fileHandler := filemodule.NewHandler(fileService, fileStorage, privateFileAuthorizer(deps.DB), recordPrivateFileUpload(deps.DB))
|
||||
fileHandler := filemodule.NewHandler(
|
||||
fileService,
|
||||
fileStorage,
|
||||
privateFileAuthorizer(deps.DB),
|
||||
recordPrivateFileUpload(deps.DB),
|
||||
adminPrivateFileAuthorizer(deps.DB),
|
||||
)
|
||||
listingService := listing.NewService(listingRepo, systemConfigRepo)
|
||||
listingHandler := listing.NewHandler(listingService, fileStorage, listing.HandlerOptions{
|
||||
ExternalUploadSecret: cfg.ExternalUploadSecret,
|
||||
|
||||
Reference in New Issue
Block a user