fix(auth): 修复站点权限缓存过期导致轮播保存失败
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestTenantCarouselSaveReloadsMissingPermissions(t *testing.T) {
|
||||
rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:16379", DB: 13})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
ctx := t.Context()
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
t.Skipf("跳过测试:未检测到测试 Redis: %v", err)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
for _, tenant := range []model.Tenant{
|
||||
{ID: 101, Code: "dachui", Name: "大锤商行", Status: "active"},
|
||||
{ID: 202, Code: "jieyou", Name: "解忧商行", Status: "active"},
|
||||
} {
|
||||
if err := db.Create(&tenant).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.Create(&model.TenantDomain{
|
||||
TenantID: 202, Host: "zuhaox.com", DomainType: "storefront", Status: "active",
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roles := []model.Role{
|
||||
{Code: "super_admin", Name: "超级管理员"},
|
||||
{Code: "banner_editor", Name: "轮播编辑"},
|
||||
{Code: "banner_viewer", Name: "轮播只读"},
|
||||
}
|
||||
if err := db.Create(&roles).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
permissions := []model.Permission{
|
||||
{Code: "system_config:view", Name: "查看配置", Resource: "system_config", Action: "view"},
|
||||
{Code: "system_config:update", Name: "更新配置", Resource: "system_config", Action: "update"},
|
||||
}
|
||||
if err := db.Create(&permissions).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&[]model.RolePermission{
|
||||
{RoleID: roles[1].ID, PermissionID: permissions[0].ID},
|
||||
{RoleID: roles[1].ID, PermissionID: permissions[1].ID},
|
||||
{RoleID: roles[2].ID, PermissionID: permissions[0].ID},
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
admins := []model.AdminUser{
|
||||
{Username: "carousel-root", PasswordHash: "x", Status: "active", TokenVersion: 1},
|
||||
{Username: "carousel-editor", PasswordHash: "x", Status: "active", TokenVersion: 1},
|
||||
{Username: "carousel-viewer", PasswordHash: "x", Status: "active", TokenVersion: 1},
|
||||
}
|
||||
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: 202},
|
||||
{AdminID: admins[2].ID, RoleID: roles[2].ID, TenantID: 202},
|
||||
{AdminID: admins[2].ID, RoleID: roles[1].ID, TenantID: 101},
|
||||
}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyFor := func(adminID uint64, scope string) string {
|
||||
return fmt.Sprintf("admin:perms:%d:%s", adminID, scope)
|
||||
}
|
||||
for _, admin := range admins {
|
||||
keys := []string{keyFor(admin.ID, "tenant:202"), keyFor(admin.ID, "tenant:101"), keyFor(admin.ID, "platform")}
|
||||
if err := rdb.Del(ctx, keys...).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = rdb.Del(context.Background(), keys...).Err() })
|
||||
}
|
||||
for _, scope := range []string{"tenant:101", "tenant:202", "platform"} {
|
||||
if err := rdb.Set(ctx, keyFor(admins[0].ID, scope), `["*"]`, time.Hour).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// 同一账号在大锤能编辑,在解忧只能查看;不能借用其他站点的缓存。
|
||||
if err := rdb.Set(ctx, keyFor(admins[2].ID, "tenant:101"), `["system_config:update"]`, time.Hour).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const configKey = "mobile.home_banners"
|
||||
const original = `[{"title":"原轮播","image_url":"https://cdn.example/original.png"}]`
|
||||
for _, tenantID := range []uint64{0, 101, 202} {
|
||||
if err := db.Create(&model.SystemConfig{TenantID: tenantID, Key: configKey, Value: original}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cfg := testConfig()
|
||||
engine := New(cfg, Dependencies{DB: db, Redis: rdb}, zap.NewNop())
|
||||
jwt := auth.NewJWTManager(cfg.JWTSecret)
|
||||
request := func(admin model.AdminUser, method, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
pair, err := jwt.GenerateTenantPairWithVersion(admin.ID, admin.Username, "admin", 1, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/api/admin/system-configs"
|
||||
if method == http.MethodPut {
|
||||
path += "/" + configKey
|
||||
}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Host = "zuhaox.com"
|
||||
req.Header.Set("Authorization", "Bearer "+pair.AccessToken)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// 经营站点域名优先于历史分销请求头。
|
||||
req.Header.Set("X-Distribution-Site-Code", "legacy-dachui")
|
||||
rec := httptest.NewRecorder()
|
||||
engine.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
if rec := request(admins[0], http.MethodGet, ""); rec.Code != http.StatusOK {
|
||||
t.Fatalf("load carousel before cache expiry: status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if err := rdb.PExpire(ctx, keyFor(admins[0].ID, "tenant:202"), -time.Second).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lastSaved := original
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
admin model.AdminUser
|
||||
status int
|
||||
}{
|
||||
{"super_admin_after_cache_expiry", admins[0], http.StatusOK},
|
||||
{"super_admin_cache_hit", admins[0], http.StatusOK},
|
||||
{"tenant_editor_without_cache", admins[1], http.StatusOK},
|
||||
{"viewer_cannot_borrow_other_tenant_permission", admins[2], http.StatusForbidden},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
value := fmt.Sprintf(`[{"title":%q,"image_url":"https://cdn.example/new.png"}]`, tc.name)
|
||||
payload, err := json.Marshal(map[string]string{"value": value, "description": "移动端首页轮播图 JSON 数组"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := request(tc.admin, http.MethodPut, string(payload))
|
||||
if rec.Code != tc.status {
|
||||
t.Fatalf("save carousel: status=%d want=%d body=%s", rec.Code, tc.status, rec.Body.String())
|
||||
}
|
||||
if tc.status == http.StatusOK {
|
||||
lastSaved = value
|
||||
}
|
||||
for _, tenantID := range []uint64{0, 101, 202} {
|
||||
var row model.SystemConfig
|
||||
if err := db.Where("tenant_id = ? AND `key` = ?", tenantID, configKey).First(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := original
|
||||
if tenantID == 202 {
|
||||
want = lastSaved
|
||||
}
|
||||
if row.Value != want {
|
||||
t.Fatalf("tenant %d carousel=%s want=%s", tenantID, row.Value, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
var cached []string
|
||||
if raw, err := rdb.Get(ctx, keyFor(admins[0].ID, "tenant:202")).Result(); err != nil {
|
||||
t.Fatalf("permissions were not cached again: %v", err)
|
||||
} else if err := json.Unmarshal([]byte(raw), &cached); err != nil || len(cached) != 1 || cached[0] != "*" {
|
||||
t.Fatalf("reloaded super admin permissions=%q err=%v", raw, err)
|
||||
}
|
||||
if ttl, err := rdb.TTL(ctx, keyFor(admins[0].ID, "tenant:202")).Result(); err != nil || ttl <= 0 {
|
||||
t.Fatalf("reloaded permission cache TTL=%v err=%v", ttl, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user