275 lines
9.2 KiB
Go
275 lines
9.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"hfb_sys/backend/internal/database"
|
|
"hfb_sys/backend/internal/model"
|
|
"hfb_sys/backend/internal/platformscope"
|
|
"hfb_sys/backend/internal/tenancy"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func TestAdminPermissionCacheKeyIncludesTenant(t *testing.T) {
|
|
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
|
|
if got := adminPermissionCacheKey(ctx, 7); got != "admin:perms:7:tenant:101" {
|
|
t.Fatalf("tenant permission cache key = %q", got)
|
|
}
|
|
platformCtx := platformscope.WithScope(context.Background())
|
|
if got := adminPermissionCacheKey(platformCtx, 7); got != "admin:perms:7:platform" {
|
|
t.Fatalf("platform permission cache key = %q", got)
|
|
}
|
|
if got := adminPermissionCacheKey(context.Background(), 7); got != "admin:perms:7" {
|
|
t.Fatalf("legacy permission cache key = %q", got)
|
|
}
|
|
}
|
|
|
|
func TestRequirePlatformSuperAdmin(t *testing.T) {
|
|
db := database.NewTestDB()
|
|
roles := []model.Role{
|
|
{Code: "super_admin", Name: "超级管理员"},
|
|
{Code: "finance", Name: "财务"},
|
|
}
|
|
if err := db.Create(&roles).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
admins := []model.AdminUser{
|
|
{Username: "platform-root", PasswordHash: "x", Status: "active"},
|
|
{Username: "tenant-finance", PasswordHash: "x", Status: "active"},
|
|
}
|
|
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: 101},
|
|
}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
engine := gin.New()
|
|
engine.Use(func(c *gin.Context) {
|
|
if c.GetHeader("X-Test-Admin") == "1" {
|
|
c.Set(ContextAdminID, admins[0].ID)
|
|
} else {
|
|
c.Set(ContextAdminID, admins[1].ID)
|
|
}
|
|
c.Next()
|
|
})
|
|
engine.GET("/probe", RequirePlatformSuperAdmin(db), func(c *gin.Context) {
|
|
c.Status(http.StatusNoContent)
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
|
req.Header.Set("X-Test-Admin", "1")
|
|
rec := httptest.NewRecorder()
|
|
engine.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusNoContent {
|
|
t.Fatalf("super admin status = %d, want %d", rec.Code, http.StatusNoContent)
|
|
}
|
|
|
|
rec = httptest.NewRecorder()
|
|
engine.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/probe", nil))
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Fatalf("tenant admin status = %d, want %d", rec.Code, http.StatusForbidden)
|
|
}
|
|
}
|
|
|
|
func TestRequireAnyPermission(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
rdb := redis.NewClient(&redis.Options{
|
|
Addr: "127.0.0.1:16379",
|
|
DB: 14,
|
|
})
|
|
ctx := t.Context()
|
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
|
t.Skipf("跳过测试:未检测到测试 Redis: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
_ = rdb.FlushDB(context.Background()).Err()
|
|
_ = rdb.Close()
|
|
})
|
|
_ = rdb.FlushDB(ctx)
|
|
|
|
adminID := uint64(101)
|
|
permKey := fmt.Sprintf("admin:perms:%d", adminID)
|
|
|
|
setPerms := func(perms []string) {
|
|
raw, err := json.Marshal(perms)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := rdb.Set(ctx, permKey, string(raw), time.Minute).Err(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
setupRouter := func() *gin.Engine {
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
c.Set(ContextAdminID, adminID)
|
|
c.Next()
|
|
})
|
|
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
|
|
}
|
|
|
|
router := setupRouter()
|
|
|
|
// 1. 无任何权限 -> 403
|
|
setPerms([]string{"dashboard:view"})
|
|
req := httptest.NewRequest(http.MethodGet, "/test-any", nil)
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("expected 403, got %d", w.Code)
|
|
}
|
|
|
|
// 2. 具备 qrcode:view -> 200
|
|
setPerms([]string{"qrcode:view"})
|
|
req = httptest.NewRequest(http.MethodGet, "/test-any", nil)
|
|
w = httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", w.Code)
|
|
}
|
|
|
|
// 3. 具备 distribution:site_view -> 200
|
|
setPerms([]string{"distribution:site_view"})
|
|
req = httptest.NewRequest(http.MethodGet, "/test-any", nil)
|
|
w = httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", w.Code)
|
|
}
|
|
|
|
// 4. 超管通配符 * -> 200
|
|
setPerms([]string{"*"})
|
|
req = httptest.NewRequest(http.MethodGet, "/test-any", nil)
|
|
w = httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", w.Code)
|
|
}
|
|
var payload map[string]any
|
|
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
|
|
t.Fatalf("decode wildcard response: %v", err)
|
|
}
|
|
if payload["all_tenants"] != true {
|
|
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())
|
|
}
|
|
})
|
|
}
|
|
}
|