From 2d04b5bab5b0637a09590936cf54e7425966f830 Mon Sep 17 00:00:00 2001 From: yml Date: Sun, 29 Nov 2026 20:31:08 +0800 Subject: [PATCH] =?UTF-8?q?fix(auth):=20=E4=BF=AE=E5=A4=8D=E7=AB=99?= =?UTF-8?q?=E7=82=B9=E6=9D=83=E9=99=90=E7=BC=93=E5=AD=98=E8=BF=87=E6=9C=9F?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=E8=BD=AE=E6=92=AD=E4=BF=9D=E5=AD=98=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/middleware/permission.go | 31 +-- .../internal/middleware/permission_test.go | 105 +++++++++- .../adminauth/permission_cache_test.go | 73 +++++++ .../internal/modules/adminauth/repository.go | 28 ++- backend/internal/router/router.go | 14 +- .../router/system_config_permissions_test.go | 183 ++++++++++++++++++ 6 files changed, 410 insertions(+), 24 deletions(-) create mode 100644 backend/internal/modules/adminauth/permission_cache_test.go create mode 100644 backend/internal/router/system_config_permissions_test.go diff --git a/backend/internal/middleware/permission.go b/backend/internal/middleware/permission.go index d502cec0..22c889a5 100644 --- a/backend/internal/middleware/permission.go +++ b/backend/internal/middleware/permission.go @@ -16,11 +16,14 @@ import ( "gorm.io/gorm" ) +// PermissionLoaderFunc 在权限缓存缺失时,按请求上下文中的站点或平台范围重新加载权限。 +type PermissionLoaderFunc func(context.Context, uint64) ([]string, error) + // RequirePermission 检查当前管理员是否拥有指定权限。 // 超级管理员(拥有 super_admin 角色的管理员)自动放行。 -func RequirePermission(permCode string, rdb *redis.Client) gin.HandlerFunc { +func RequirePermission(permCode string, rdb *redis.Client, loader PermissionLoaderFunc) gin.HandlerFunc { return func(c *gin.Context) { - if checkPermission(c, permCode, rdb) { + if checkPermission(c, permCode, rdb, loader) { c.Next() } } @@ -28,21 +31,21 @@ func RequirePermission(permCode string, rdb *redis.Client) gin.HandlerFunc { // RequireAnyPermission 检查当前管理员是否拥有任意一个指定的权限。 // 超级管理员(拥有 super_admin 角色或 * 权限)自动放行。 -func RequireAnyPermission(rdb *redis.Client, permCodes ...string) gin.HandlerFunc { +func RequireAnyPermission(rdb *redis.Client, loader PermissionLoaderFunc, permCodes ...string) gin.HandlerFunc { return func(c *gin.Context) { - if checkAnyPermission(c, rdb, permCodes...) { + if checkAnyPermission(c, rdb, loader, permCodes...) { c.Next() } } } -func RequirePermissionIf(permCode string, rdb *redis.Client, predicate func(*gin.Context) bool) gin.HandlerFunc { +func RequirePermissionIf(permCode string, rdb *redis.Client, loader PermissionLoaderFunc, predicate func(*gin.Context) bool) gin.HandlerFunc { return func(c *gin.Context) { if predicate == nil || !predicate(c) { c.Next() return } - if checkPermission(c, permCode, rdb) { + if checkPermission(c, permCode, rdb, loader) { c.Next() } } @@ -88,7 +91,7 @@ func RequirePlatformSuperAdmin(db *gorm.DB) gin.HandlerFunc { } } -func checkAnyPermission(c *gin.Context, rdb *redis.Client, permCodes ...string) bool { +func checkAnyPermission(c *gin.Context, rdb *redis.Client, loader PermissionLoaderFunc, permCodes ...string) bool { value, ok := c.Get(ContextAdminID) if !ok { response.Unauthorized(c, "缺少管理员上下文") @@ -102,7 +105,7 @@ func checkAnyPermission(c *gin.Context, rdb *redis.Client, permCodes ...string) return false } - codes, err := getPermCodes(c, rdb, adminID) + codes, err := getPermCodes(c, rdb, adminID, loader) if err != nil { response.Error(c, http.StatusInternalServerError, "perm_check_failed", "权限校验服务暂时不可用") c.Abort() @@ -126,18 +129,22 @@ func checkAnyPermission(c *gin.Context, rdb *redis.Client, permCodes ...string) return false } -func checkPermission(c *gin.Context, permCode string, rdb *redis.Client) bool { - return checkAnyPermission(c, rdb, permCode) +func checkPermission(c *gin.Context, permCode string, rdb *redis.Client, loader PermissionLoaderFunc) bool { + return checkAnyPermission(c, rdb, loader, permCode) } -func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string, error) { +func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64, loader PermissionLoaderFunc) ([]string, error) { if rdb == nil { return nil, errors.New("redis unavailable") } key := adminPermissionCacheKey(c.Request.Context(), adminID) raw, err := rdb.Get(c.Request.Context(), key).Result() if errors.Is(err, redis.Nil) { - return nil, nil // 缓存未命中,视为无权限 + if loader == nil { + return nil, errors.New("permission loader unavailable") + } + // 会话可能仍有效,不能把缓存过期当成权限被撤销。 + return loader(c.Request.Context(), adminID) } if err != nil { return nil, err diff --git a/backend/internal/middleware/permission_test.go b/backend/internal/middleware/permission_test.go index c2d7537a..a0c6050c 100644 --- a/backend/internal/middleware/permission_test.go +++ b/backend/internal/middleware/permission_test.go @@ -3,6 +3,7 @@ package middleware import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -118,7 +119,7 @@ func TestRequireAnyPermission(t *testing.T) { c.Set(ContextAdminID, adminID) c.Next() }) - r.GET("/test-any", RequireAnyPermission(rdb, "distribution:site_view", "qrcode:view"), func(c *gin.Context) { + r.GET("/test-any", RequireAnyPermission(rdb, nil, "distribution:site_view", "qrcode:view"), func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true, "all_tenants": tenancy.HasAdminAllTenantScope(c.Request.Context())}) }) return r @@ -169,3 +170,105 @@ func TestRequireAnyPermission(t *testing.T) { t.Fatalf("super admin all-tenant scope marker missing: %v", payload) } } + +func TestPermissionCacheMissReloadsCurrentScope(t *testing.T) { + gin.SetMode(gin.TestMode) + rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:16379", DB: 14}) + t.Cleanup(func() { _ = rdb.Close() }) + ctx := t.Context() + if err := rdb.Ping(ctx).Err(); err != nil { + t.Skipf("跳过测试:未检测到测试 Redis: %v", err) + } + const adminID = uint64(73001) + for _, tc := range []struct { + name string + kind string + cached string + loaded []string + loadErr error + platform bool + noLoader bool + redisError bool + wantStatus int + wantCalls int + wantAll bool + }{ + {name: "expired_tenant_permission", loaded: []string{"system_config:update"}, wantStatus: 200, wantCalls: 1}, + {name: "expired_super_admin_permission", loaded: []string{"*"}, wantStatus: 200, wantCalls: 1, wantAll: true}, + {name: "expired_platform_permission", platform: true, loaded: []string{"*"}, wantStatus: 200, wantCalls: 1, wantAll: true}, + {name: "permission_still_denied", loaded: []string{"system_config:view"}, wantStatus: 403, wantCalls: 1}, + {name: "platform_cannot_borrow_tenant_cache", platform: true, wantStatus: 403, wantCalls: 1}, + {name: "cache_hit", cached: "[\"system_config:update\"]", wantStatus: 200}, + {name: "cached_empty_permissions", cached: "[]", loaded: []string{"*"}, wantStatus: 403}, + {name: "database_error", loaded: []string{"*"}, loadErr: errors.New("database unavailable"), wantStatus: 500, wantCalls: 1}, + {name: "malformed_cache", cached: "not-json", loaded: []string{"*"}, wantStatus: 500}, + {name: "redis_error", redisError: true, loaded: []string{"*"}, wantStatus: 500}, + {name: "missing_loader", noLoader: true, wantStatus: 500}, + {name: "any_permission_miss", kind: "any", loaded: []string{"system_config:update"}, wantStatus: 200, wantCalls: 1}, + {name: "conditional_permission_miss", kind: "conditional", loaded: []string{"system_config:update"}, wantStatus: 200, wantCalls: 1}, + {name: "conditional_permission_not_required", kind: "skip", wantStatus: 200}, + } { + t.Run(tc.name, func(t *testing.T) { + requestCtx := tenancy.WithScope(ctx, tenancy.Scope{TenantID: 202}) + if tc.platform { + requestCtx = platformscope.WithScope(ctx) + } + key := adminPermissionCacheKey(requestCtx, adminID) + if err := rdb.Del(ctx, key).Err(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = rdb.Del(context.Background(), key).Err() }) + if tc.platform { + tenantKey := fmt.Sprintf("admin:perms:%d:tenant:202", adminID) + if err := rdb.Set(ctx, tenantKey, "[\"*\"]", time.Minute).Err(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = rdb.Del(context.Background(), tenantKey).Err() }) + } + if tc.cached != "" { + if err := rdb.Set(ctx, key, tc.cached, time.Minute).Err(); err != nil { + t.Fatal(err) + } + } + calls := 0 + var loader PermissionLoaderFunc = func(gotCtx context.Context, id uint64) ([]string, error) { + calls++ + if id != adminID || platformscope.IsScope(gotCtx) != tc.platform || + tenancy.IDFromContext(gotCtx) != tenancy.IDFromContext(requestCtx) { + t.Fatalf("permission loader received wrong admin or scope") + } + return tc.loaded, tc.loadErr + } + if tc.noLoader { + loader = nil + } + client := rdb + if tc.redisError { + client = redis.NewClient(&redis.Options{Addr: "127.0.0.1:16379", DB: 14}) + _ = client.Close() + } + guard := RequirePermission("system_config:update", client, loader) + switch tc.kind { + case "any": + guard = RequireAnyPermission(client, loader, "system_config:create", "system_config:update") + case "conditional", "skip": + guard = RequirePermissionIf("system_config:update", client, loader, func(*gin.Context) bool { return tc.kind == "conditional" }) + } + engine := gin.New() + engine.Use(func(c *gin.Context) { c.Set(ContextAdminID, adminID) }) + engine.PUT("/carousel", guard, func(c *gin.Context) { + if tenancy.HasAdminAllTenantScope(c.Request.Context()) != tc.wantAll || + tenancy.IDFromContext(c.Request.Context()) != tenancy.IDFromContext(requestCtx) { + t.Fatal("permission check changed the tenant or wildcard scope") + } + c.Status(http.StatusOK) + }) + req := httptest.NewRequest(http.MethodPut, "/carousel", nil).WithContext(requestCtx) + rec := httptest.NewRecorder() + engine.ServeHTTP(rec, req) + if rec.Code != tc.wantStatus || calls != tc.wantCalls { + t.Fatalf("status=%d want=%d loader calls=%d want=%d body=%s", rec.Code, tc.wantStatus, calls, tc.wantCalls, rec.Body.String()) + } + }) + } +} diff --git a/backend/internal/modules/adminauth/permission_cache_test.go b/backend/internal/modules/adminauth/permission_cache_test.go new file mode 100644 index 00000000..2772629f --- /dev/null +++ b/backend/internal/modules/adminauth/permission_cache_test.go @@ -0,0 +1,73 @@ +package adminauth + +import ( + "context" + "errors" + "testing" + "time" + + "hfb_sys/backend/internal/database" + "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/platformscope" + + "github.com/redis/go-redis/v9" + "gorm.io/gorm" +) + +func TestFindByIDPropagatesPermissionQueryErrors(t *testing.T) { + db := database.NewTestDB() + admin := model.AdminUser{Username: "permission-error", PasswordHash: "x", Status: "active"} + if err := db.Create(&admin).Error; err != nil { + t.Fatal(err) + } + queryErr := errors.New("permission query failed") + for _, table := range []string{"roles", "permissions"} { + t.Run(table, func(t *testing.T) { + const callback = "test:permission_query_error" + if err := db.Callback().Query().Before("gorm:query").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == table { + tx.AddError(queryErr) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + repo := NewRepository(db, nil, nil) + if dto, err := repo.FindByID(adminTenantContext(202), admin.ID); !errors.Is(err, queryErr) || dto != nil { + t.Fatalf("FindByID returned dto=%+v err=%v, want query error", dto, err) + } + }) + } +} + +func TestCacheEmptyPermissionsPreservesScope(t *testing.T) { + rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:16379", DB: 13}) + t.Cleanup(func() { _ = rdb.Close() }) + if err := rdb.Ping(t.Context()).Err(); err != nil { + t.Skipf("跳过测试:未检测到测试 Redis: %v", err) + } + repo := NewRepository(nil, rdb, nil) + const adminID = uint64(74001) + contexts := []context.Context{adminTenantContext(101), adminTenantContext(202), platformscope.WithScope(t.Context())} + for _, ctx := range contexts { + key := adminPermissionCacheKey(ctx, adminID) + if err := rdb.Set(ctx, key, "[\"*\"]", time.Hour).Err(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = rdb.Del(context.Background(), key).Err() }) + } + cachePermissions(contexts[1], repo, adminID, nil) + for i, ctx := range contexts { + key := adminPermissionCacheKey(ctx, adminID) + want := "[\"*\"]" + if i == 1 { + want = "[]" + } + if raw, err := rdb.Get(ctx, key).Result(); err != nil || raw != want { + t.Fatalf("permission cache %s=%q want=%q err=%v", key, raw, want, err) + } + if ttl, err := rdb.TTL(ctx, key).Result(); err != nil || ttl <= 0 { + t.Fatalf("permission cache %s TTL=%v err=%v", key, ttl, err) + } + } +} diff --git a/backend/internal/modules/adminauth/repository.go b/backend/internal/modules/adminauth/repository.go index f674aeaf..6a773f45 100644 --- a/backend/internal/modules/adminauth/repository.go +++ b/backend/internal/modules/adminauth/repository.go @@ -102,7 +102,9 @@ func (r *Repository) Login(ctx context.Context, username string, password string } dto := toDTO(admin) dto.TenantID = tenantID - r.loadRolesAndPerms(ctx, &dto) + if err := r.loadRolesAndPerms(ctx, &dto); err != nil { + return LoginResult{}, err + } return LoginResult{Admin: dto, Tokens: tokens}, nil } @@ -184,7 +186,9 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*AdminDTO, error) } dto := toDTO(admin) dto.TenantID = tenancy.IDFromContext(ctx) - r.loadRolesAndPerms(ctx, &dto) + if err := r.loadRolesAndPerms(ctx, &dto); err != nil { + return nil, err + } return &dto, nil } @@ -224,9 +228,9 @@ func toDTO(admin model.AdminUser) AdminDTO { } } -func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) { +func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) error { if r.db == nil { - return + return ErrDependencyUnavailable } // 加载角色 var roles []RoleDTO @@ -238,7 +242,9 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) { } else if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { roleQuery = roleQuery.Where("(aur.tenant_id = ? OR roles.code = ?)", tenantID, "super_admin") } - roleQuery.Find(&roles) + if err := roleQuery.Find(&roles).Error; err != nil { + return err + } dto.Roles = roles dto.PasswordMustChange = dto.PasswordMustChange && rolesRequireInitialPasswordChange(roles) @@ -247,7 +253,7 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) { if role.Code == "super_admin" { dto.Permissions = []string{"*"} cachePermissions(ctx, r, dto.ID, dto.Permissions) - return + return nil } } @@ -260,11 +266,14 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) { if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { permQuery = permQuery.Where("aur.tenant_id = ?", tenantID) } - permQuery.Pluck("code", &permCodes) + if err := permQuery.Pluck("code", &permCodes).Error; err != nil { + return err + } dto.Permissions = permCodes // 缓存权限到 Redis cachePermissions(ctx, r, dto.ID, permCodes) + return nil } func rolesRequireInitialPasswordChange(roles []RoleDTO) bool { @@ -277,9 +286,12 @@ func rolesRequireInitialPasswordChange(roles []RoleDTO) bool { } func cachePermissions(ctx context.Context, r *Repository, adminID uint64, permCodes []string) { - if r.redis == nil || len(permCodes) == 0 { + if r.redis == nil { return } + if permCodes == nil { + permCodes = []string{} + } key := adminPermissionCacheKey(ctx, adminID) raw, _ := json.Marshal(permCodes) r.redis.Set(ctx, key, string(raw), 2*time.Hour) diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index aa851ac3..ca289fea 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -495,7 +495,15 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { requireUserProfile := middleware.Auth(jwtManager, validateUserProfile) optionalAuth := middleware.OptionalAuth(jwtManager, validateUserToken) var validateAdminToken middleware.AdminTokenValidatorFunc + var loadAdminPermissions middleware.PermissionLoaderFunc if adminAuthRepo != nil { + loadAdminPermissions = func(ctx context.Context, adminID uint64) ([]string, error) { + admin, err := adminAuthRepo.FindByID(ctx, adminID) + if err != nil { + return nil, err + } + return admin.Permissions, nil + } validateAdminToken = func(ctx context.Context, adminID uint64, tokenVersion int64) (middleware.AdminTokenContext, error) { admin, err := adminAuthRepo.FindActiveForPasswordGate(ctx, adminID, tokenVersion) if err != nil { @@ -511,11 +519,11 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { requireFileAuth := middleware.AuthUserOrAdmin(jwtManager, validateUserToken, validateAdminToken) requireRealname := middleware.RequireRealname(userRepo) requirePerm := func(code string) gin.HandlerFunc { - return middleware.RequirePermission(code, deps.Redis) + return middleware.RequirePermission(code, deps.Redis, loadAdminPermissions) } requirePlatformSuperAdmin := middleware.RequirePlatformSuperAdmin(deps.DB) requireAnyPerm := func(codes ...string) gin.HandlerFunc { - return middleware.RequireAnyPermission(deps.Redis, codes...) + return middleware.RequireAnyPermission(deps.Redis, loadAdminPermissions, codes...) } api := engine.Group("/api") @@ -1016,7 +1024,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { adminRoutes.GET("/payment-configs", requirePerm("payment_config:list"), paymentConfigHandler.List) adminRoutes.GET("/payment-configs/export", requirePerm("payment_config:view_secret"), paymentConfigHandler.ExportBackup) adminRoutes.POST("/payment-configs/import", requirePerm("payment_config:view_secret"), paymentConfigHandler.ImportBackup) - adminRoutes.GET("/payment-configs/:id", requirePerm("payment_config:list"), middleware.RequirePermissionIf("payment_config:view_secret", deps.Redis, func(c *gin.Context) bool { + adminRoutes.GET("/payment-configs/:id", requirePerm("payment_config:list"), middleware.RequirePermissionIf("payment_config:view_secret", deps.Redis, loadAdminPermissions, func(c *gin.Context) bool { return c.Query("include_secret") == "true" }), paymentConfigHandler.Get) adminRoutes.POST("/payment-configs", requirePerm("payment_config:create"), paymentConfigHandler.Create) diff --git a/backend/internal/router/system_config_permissions_test.go b/backend/internal/router/system_config_permissions_test.go new file mode 100644 index 00000000..faec85cb --- /dev/null +++ b/backend/internal/router/system_config_permissions_test.go @@ -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) + } +}