fix(tenant): 封堵审计文件与历史用户跨站访问

This commit is contained in:
yml
2026-11-15 22:46:58 +08:00
parent 0cb385d84f
commit 1108df195d
28 changed files with 531 additions and 60 deletions
+7
View File
@@ -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)
}
}