Files
hfb_sys/backend/internal/middleware/permission_test.go
T

165 lines
4.5 KiB
Go

package middleware
import (
"context"
"encoding/json"
"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, "distribution:site_view", "qrcode:view"), func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
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)
}
}