Files
pangolin/server/internal/auth/ratelimit_test.go
T
wangjia a5e25b444f feat(auth): 验证码/注册/登录/JWT 鉴权模块 (tsk_2PFfyviECIXh)
实现 server/internal/auth 控制面鉴权底座,对应 doc/02 §4.1、doc/06 §3:

- POST /v1/auth/code:IP+邮箱双维度 Redis 滑窗限频(同邮箱 1/min、同 IP 10/h)
  + 一次性邮箱域黑名单(embed 词表)→ 6 位数字码写 auth:code:{email} TTL 10min
  → 异步发信(SMTP / 开发态 log mailer)。
- POST /v1/auth/register:验码(一次性,删 key;超次数烧码)→ 单事务建号
  (uuid + dp_uuid 应用层生成、argon2id)+ 7 天 PRO 试用(source='trial')→ 签发 JWT。
- POST /v1/auth/login:argon2id 校验(失败恒定时、未知用户走 dummy hash);
  失败计数限流 rl:login:{email} + 锁定;banned 拒绝。
- POST /v1/auth/refresh:RS256,access 15min + refresh 30d 落 Redis 白名单
  jwt:refresh:{jti},旋转时删旧写新;JWT 头带 kid,验证端接受新旧公钥支持轮换。
- RequireAuth 中间件:解析 Bearer access,注入 user id(复用 codes.CtxKeyUserID
  避免循环依赖)+ uuid + claims 到 context。
- 错误体统一走 internal/apierr 的 {code, message_zh, message_en},文案双语脱敏。
- 文件拆分:handler/service/password/token/ratelimit/emailcheck/store/mailer/
  middleware/errors/keyloader;config 增加可选 JWT PEM 路径/kid 加载。

测试:password/token/ratelimit/emailcheck/service/handler/middleware 单测
(miniredis,含注册全流程、重复邮箱 409、验证码错误/过期/复用/烧码、限频 429
带 Retry-After、登录失败锁定、banned 拒绝、refresh 旋转后旧 token 失效),
go test -race 通过;集成测试 integration_test.go(testcontainers MySQL8+Redis,
register→login→refresh→受保护接口全链路,构建 tag integration)与 codes 模块同构。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 12:19:10 +08:00

98 lines
2.6 KiB
Go

package auth
import (
"context"
"testing"
"time"
)
func TestRateLimiter_SlidingWindow(t *testing.T) {
rdb, _ := newMiniRedis(t)
base := time.Unix(1_700_000_000, 0)
clock := base
rl := NewRateLimiter(rdb, func() time.Time { return clock })
ctx := context.Background()
// limit 1 per minute.
ok, _, err := rl.Allow(ctx, "code:email", "a@b.com", 1, time.Minute)
if err != nil || !ok {
t.Fatalf("first attempt should pass: ok=%v err=%v", ok, err)
}
// Second attempt within the window is denied with a Retry-After.
ok, ra, err := rl.Allow(ctx, "code:email", "a@b.com", 1, time.Minute)
if err != nil {
t.Fatalf("err: %v", err)
}
if ok {
t.Fatal("second attempt within window should be denied")
}
if ra <= 0 || ra > time.Minute {
t.Fatalf("retry-after = %v, want (0, 1m]", ra)
}
// After the window passes, attempts are allowed again.
clock = base.Add(61 * time.Second)
ok, _, err = rl.Allow(ctx, "code:email", "a@b.com", 1, time.Minute)
if err != nil || !ok {
t.Fatalf("attempt after window should pass: ok=%v err=%v", ok, err)
}
}
func TestRateLimiter_DistinctKeysIndependent(t *testing.T) {
rdb, _ := newMiniRedis(t)
rl := NewRateLimiter(rdb, nil)
ctx := context.Background()
if ok, _, _ := rl.Allow(ctx, "code:email", "a@b.com", 1, time.Minute); !ok {
t.Fatal("a@b.com first should pass")
}
if ok, _, _ := rl.Allow(ctx, "code:email", "c@d.com", 1, time.Minute); !ok {
t.Fatal("c@d.com first should pass (independent key)")
}
}
func TestRateLimiter_FailureCounter(t *testing.T) {
rdb, mr := newMiniRedis(t)
rl := NewRateLimiter(rdb, nil)
ctx := context.Background()
for i := 1; i <= 3; i++ {
n, err := rl.RecordFailure(ctx, "login", "a@b.com", 15*time.Minute)
if err != nil {
t.Fatalf("RecordFailure: %v", err)
}
if n != int64(i) {
t.Fatalf("count = %d, want %d", n, i)
}
}
count, ttl, err := rl.FailureCount(ctx, "login", "a@b.com")
if err != nil {
t.Fatalf("FailureCount: %v", err)
}
if count != 3 {
t.Fatalf("count = %d, want 3", count)
}
if ttl <= 0 {
t.Fatalf("ttl = %v, want > 0", ttl)
}
// Clear resets the counter.
if err := rl.ClearFailures(ctx, "login", "a@b.com"); err != nil {
t.Fatalf("ClearFailures: %v", err)
}
count, _, _ = rl.FailureCount(ctx, "login", "a@b.com")
if count != 0 {
t.Fatalf("count after clear = %d, want 0", count)
}
// Counter expires after its window.
_, _ = rl.RecordFailure(ctx, "login", "x@y.com", 15*time.Minute)
mr.FastForward(16 * time.Minute)
count, _, _ = rl.FailureCount(ctx, "login", "x@y.com")
if count != 0 {
t.Fatalf("count after TTL = %d, want 0", count)
}
}