fix(auth): 修复站点权限缓存过期导致轮播保存失败
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user