9e11f8f007
按"同一能力只保留一个主入口、框架不替上层吞错、安全路径默认 fail-closed"原则, 收敛历史双轨 API。自定义 CacheService/Storage 实现需同步更新签名(编译失败即迁移信号)。 cache: - CacheService.Get/Exists 改为 (bool, error):命中 (true,nil)、未命中 (false,nil)、 Redis 未就绪/命令错误/反序列化失败返回 (false,err) - 删除 cache.GetE/cache.ExistsE/CacheGetter/CacheExistChecker/redisCache.GetE/redisCache.ExistsE (不保留 deprecated wrapper) - 新增包级 cache.Get/cache.Exists(带 error);GetWithPrefix 改为 (bool,error) jwt: - TokenBlacklist.IsBlacklisted 改为 (bool, error),删除 IsBlacklistedE - IsTokenRevoked 改为 (bool, error) - ParseToken 默认从 fail-open 改为 fail-closed:黑名单后端不可检查时返回 ErrBlacklistUnavailable 拒绝该 Token(无 Redis 部署不再支持可靠撤销) - 删除 ParseTokenFailClosed(主 API 已 fail-closed) - 保留 ParseTokenWithBlacklistPolicy + BlacklistPolicy/BlacklistFailOpen/BlacklistFailClosed 供显式 fail-open(仅无 Redis 或低安全场景) storage: - Storage.Exists 改为 (bool, error):存在 (true,nil)、不存在 (false,nil)、 未初始化/路径非法/穿越/后端错误返回 (false,err) - LocalStorage.Exists 区分 os.IsNotExist 与其他 Stat 错误 - OSSStorage.Exists 区分 OSS 404/NoSuchKey 与鉴权/网络错误 - 包级 storage.Exists 同步签名,未初始化返回 ErrStorageNotInitialized - 新增 ErrReadTooLarge:Local/OSSStorage.Get 读取超 maxReadBytes 上限原误用 ErrInvalidPath(语义不贴切),改为 ErrReadTooLarge ratelimit: - NewRedisRateLimiter 加 opts ...RedisRateLimiterOption,新增 WithFailClosed(bool) 替代原 NewRedisRateLimiterFailClosed - RedisRateLimit/CustomRedisRateLimit/RedisRateLimitWithIdentifier 同步加 opts 参数 - 删除 NewRedisRateLimiterFailClosed/RedisRateLimitFailClosed/CustomRedisRateLimitFailClosed - UploadRedisRateLimit 由 fail-open 改为 fail-closed(资源敏感操作,Redis 故障时拒绝) 测试与文档: - cache_m10_internal_test.go 重写 4 个 M10 测试为 Get/Exists 契约测试,新增 mock 编译覆盖 - jwt_test.go 改 4 处;jwt_c9c_internal_test.go 改 IsTokenRevoked 2-value - examples/full/main_test.go 加 miniredis 注入(ParseToken fail-closed 后认证需 Redis) - middleware_test.go 改 5 处 FailClosed 调用为 WithFailClosed(true);auth_test.go 加 Redis - storage 测试改 6 处 Exists/Get 断言为新签名/错误类型 - README/GUIDE 同步示例为新签名;CHANGELOG 新增 Breaking 升级说明与迁移示例 验证:go build / go vet / go test -race -count=1 ./... 全绿。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
199 lines
6.6 KiB
Go
199 lines
6.6 KiB
Go
package middleware_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/EthanCodeCraft/xlgo-core/config"
|
|
"github.com/EthanCodeCraft/xlgo-core/jwt"
|
|
"github.com/EthanCodeCraft/xlgo-core/middleware"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func performAuthMiddlewareRequest(m gin.HandlerFunc, setup func(*gin.Context)) *httptest.ResponseRecorder {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
if setup != nil {
|
|
setup(c)
|
|
}
|
|
})
|
|
r.Use(m)
|
|
r.GET("/test", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
})
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
r.ServeHTTP(w, req)
|
|
return w
|
|
}
|
|
|
|
func setAuthUser(userType, role string) func(*gin.Context) {
|
|
return func(c *gin.Context) {
|
|
c.Set(middleware.ContextKeyUserID, uint(1))
|
|
c.Set(middleware.ContextKeyUsername, "tester")
|
|
c.Set(middleware.ContextKeyRole, role)
|
|
c.Set(middleware.ContextKeyUserType, userType)
|
|
}
|
|
}
|
|
|
|
func TestAuthRequiredAcceptsCaseInsensitiveBearer_M8(t *testing.T) {
|
|
setupMiddlewareMiniRedis(t)
|
|
if err := config.Set(&config.Config{
|
|
JWT: config.JWTConfig{
|
|
Secret: "test-secret-key-1234567890123456789012",
|
|
Expire: time.Hour,
|
|
},
|
|
}); err != nil {
|
|
t.Fatalf("set config: %v", err)
|
|
}
|
|
token, err := jwt.GenerateToken(1, "tester", "owner", "tenant_admin")
|
|
if err != nil {
|
|
t.Fatalf("GenerateToken: %v", err)
|
|
}
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(middleware.AuthRequired())
|
|
r.GET("/test", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
})
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/test", nil)
|
|
req.Header.Set("Authorization", "bearer "+token)
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d, body %s", w.Code, w.Body.String())
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"ok":true`) {
|
|
t.Fatalf("expected request to pass, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRequireUserTypes(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(middleware.RequireUserTypes("tenant_admin"), setAuthUser("tenant_admin", "owner"))
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"ok":true`) {
|
|
t.Fatalf("expected request to pass, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRequireUserTypesRejectsOtherTypes(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(middleware.RequireUserTypes("tenant_admin"), setAuthUser("staff", "owner"))
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected business error over status 200, got %d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"code":403`) {
|
|
t.Fatalf("expected forbidden response, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRequireRoles(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(middleware.RequireRoles("owner"), setAuthUser("tenant_admin", "owner"))
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"ok":true`) {
|
|
t.Fatalf("expected request to pass, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRequireAuthCustomChecker(t *testing.T) {
|
|
checker := func(user middleware.AuthUser, c *gin.Context) bool {
|
|
return user.UserID == 1 && user.UserType == "merchant" && user.Role == "owner"
|
|
}
|
|
|
|
w := performAuthMiddlewareRequest(middleware.RequireAuth(checker), setAuthUser("merchant", "owner"))
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status 200, got %d", w.Code)
|
|
}
|
|
if !strings.Contains(w.Body.String(), `"ok":true`) {
|
|
t.Fatalf("expected request to pass, got body %s", w.Body.String())
|
|
}
|
|
|
|
w = performAuthMiddlewareRequest(middleware.RequireAuth(checker, "需要商户所有者权限"), setAuthUser("merchant", "staff"))
|
|
if !strings.Contains(w.Body.String(), "需要商户所有者权限") {
|
|
t.Fatalf("expected custom forbidden message, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestDefaultRoleShortcuts(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
mw gin.HandlerFunc
|
|
userType string
|
|
wantPass bool
|
|
}{
|
|
{"admin allows super admin", middleware.AdminRequired(), middleware.DefaultUserTypeSuperAdmin, true},
|
|
{"admin allows admin", middleware.AdminRequired(), middleware.DefaultUserTypeAdmin, true},
|
|
{"admin rejects staff", middleware.AdminRequired(), middleware.DefaultUserTypeStaff, false},
|
|
{"super admin allows super admin", middleware.SuperAdminRequired(), middleware.DefaultUserTypeSuperAdmin, true},
|
|
{"super admin rejects admin", middleware.SuperAdminRequired(), middleware.DefaultUserTypeAdmin, false},
|
|
{"staff allows staff", middleware.StaffRequired(), middleware.DefaultUserTypeStaff, true},
|
|
{"any allows staff", middleware.AnyUserRequired(), middleware.DefaultUserTypeStaff, true},
|
|
{"any rejects external", middleware.AnyUserRequired(), "external", false},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(tt.mw, setAuthUser(tt.userType, "role"))
|
|
body := w.Body.String()
|
|
if tt.wantPass && !strings.Contains(body, `"ok":true`) {
|
|
t.Fatalf("expected pass, got body %s", body)
|
|
}
|
|
if !tt.wantPass && !strings.Contains(body, `"code":403`) {
|
|
t.Fatalf("expected forbidden, got body %s", body)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRequireAuthRejectsMissingContext(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(middleware.RequireUserTypes("admin"), nil)
|
|
if !strings.Contains(w.Body.String(), `"code":401`) || !strings.Contains(w.Body.String(), "请先登录") {
|
|
t.Fatalf("expected unauthorized login response, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestRequireAuthRejectsMalformedContext(t *testing.T) {
|
|
w := performAuthMiddlewareRequest(middleware.RequireUserTypes("admin"), func(c *gin.Context) {
|
|
c.Set(middleware.ContextKeyUserID, uint(1))
|
|
c.Set(middleware.ContextKeyUsername, "tester")
|
|
c.Set(middleware.ContextKeyRole, "owner")
|
|
c.Set(middleware.ContextKeyUserType, 123)
|
|
})
|
|
if !strings.Contains(w.Body.String(), `"code":401`) || !strings.Contains(w.Body.String(), "用户信息异常") {
|
|
t.Fatalf("expected malformed user response, got body %s", w.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestGetAuthUser(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
|
setAuthUser("tenant_admin", "owner")(c)
|
|
|
|
user, ok := middleware.GetAuthUser(c)
|
|
if !ok {
|
|
t.Fatal("expected auth user")
|
|
}
|
|
if user.UserID != 1 || user.Username != "tester" || user.UserType != "tenant_admin" || user.Role != "owner" {
|
|
t.Fatalf("unexpected auth user: %+v", user)
|
|
}
|
|
if middleware.GetRole(c) != "owner" {
|
|
t.Fatalf("expected role owner, got %q", middleware.GetRole(c))
|
|
}
|
|
|
|
c.Set(middleware.ContextKeyUserID, "bad")
|
|
if _, ok := middleware.GetAuthUser(c); ok {
|
|
t.Fatal("expected malformed auth user to fail")
|
|
}
|
|
}
|