a5e25b444f
实现 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>
162 lines
4.9 KiB
Go
162 lines
4.9 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// RateLimiter implements per-scope sliding-window rate limiting and failure
|
|
// counters on top of Redis. It stores nothing but short-lived counters — no
|
|
// connection or behaviour logs — per the no-log baseline (doc/06 §4).
|
|
//
|
|
// Sliding-window keys are ZSETs named `rl:{scope}:{key}` whose members are
|
|
// timestamped attempts; failure counters are plain integer keys.
|
|
type RateLimiter struct {
|
|
rdb *redis.Client
|
|
now func() time.Time
|
|
}
|
|
|
|
// NewRateLimiter builds a RateLimiter. now may be nil (defaults to time.Now).
|
|
func NewRateLimiter(rdb *redis.Client, now func() time.Time) *RateLimiter {
|
|
if now == nil {
|
|
now = time.Now
|
|
}
|
|
return &RateLimiter{rdb: rdb, now: now}
|
|
}
|
|
|
|
// slidingWindow is a single atomic Lua script:
|
|
// - drops members older than the window,
|
|
// - if the live count already reached the limit, returns {0, oldestScore},
|
|
// - otherwise records the attempt and returns {1, 0}.
|
|
//
|
|
// All times are unix-milliseconds.
|
|
var slidingWindow = redis.NewScript(`
|
|
local key = KEYS[1]
|
|
local now = tonumber(ARGV[1])
|
|
local window = tonumber(ARGV[2])
|
|
local limit = tonumber(ARGV[3])
|
|
local member = ARGV[4]
|
|
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
|
|
local count = redis.call('ZCARD', key)
|
|
if count >= limit then
|
|
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
|
|
return {0, oldest[2]}
|
|
end
|
|
redis.call('ZADD', key, now, member)
|
|
redis.call('PEXPIRE', key, window)
|
|
return {1, 0}
|
|
`)
|
|
|
|
// rlKey builds the canonical `rl:{scope}:{key}` Redis key.
|
|
func rlKey(scope, key string) string {
|
|
return fmt.Sprintf("rl:%s:%s", scope, key)
|
|
}
|
|
|
|
// Allow records an attempt in the sliding window for (scope, key). It returns
|
|
// allowed=false together with the Retry-After duration when the limit within
|
|
// window has been reached. limit is the maximum number of attempts permitted
|
|
// inside window.
|
|
func (rl *RateLimiter) Allow(ctx context.Context, scope, key string, limit int, window time.Duration) (allowed bool, retryAfter time.Duration, err error) {
|
|
nowMs := rl.now().UnixMilli()
|
|
winMs := window.Milliseconds()
|
|
|
|
member, err := uniqueMember(nowMs)
|
|
if err != nil {
|
|
return false, 0, err
|
|
}
|
|
|
|
res, err := slidingWindow.Run(ctx, rl.rdb, []string{rlKey(scope, key)},
|
|
nowMs, winMs, limit, member).Result()
|
|
if err != nil {
|
|
return false, 0, fmt.Errorf("auth: ratelimit run: %w", err)
|
|
}
|
|
|
|
vals, ok := res.([]interface{})
|
|
if !ok || len(vals) != 2 {
|
|
return false, 0, fmt.Errorf("auth: ratelimit unexpected result %v", res)
|
|
}
|
|
ok1, _ := vals[0].(int64)
|
|
if ok1 == 1 {
|
|
return true, 0, nil
|
|
}
|
|
|
|
// Denied: compute how long until the oldest attempt leaves the window.
|
|
oldest := toInt64(vals[1])
|
|
ra := time.Duration(oldest+winMs-nowMs) * time.Millisecond
|
|
if ra < time.Second {
|
|
ra = time.Second
|
|
}
|
|
return false, ra, nil
|
|
}
|
|
|
|
// failKey builds the failure-counter key, e.g. `rl:login:{email}`.
|
|
func failKey(scope, key string) string {
|
|
return rlKey(scope, key)
|
|
}
|
|
|
|
// RecordFailure increments the failure counter for (scope, key), (re)setting
|
|
// its TTL to window on every increment so the lock slides forward while abuse
|
|
// continues. It returns the new count.
|
|
func (rl *RateLimiter) RecordFailure(ctx context.Context, scope, key string, window time.Duration) (int64, error) {
|
|
k := failKey(scope, key)
|
|
pipe := rl.rdb.Pipeline()
|
|
incr := pipe.Incr(ctx, k)
|
|
pipe.Expire(ctx, k, window)
|
|
if _, err := pipe.Exec(ctx); err != nil {
|
|
return 0, fmt.Errorf("auth: record failure: %w", err)
|
|
}
|
|
return incr.Val(), nil
|
|
}
|
|
|
|
// FailureCount returns the current failure count and the remaining TTL (lock
|
|
// window) for (scope, key). count is 0 when no counter exists.
|
|
func (rl *RateLimiter) FailureCount(ctx context.Context, scope, key string) (count int64, ttl time.Duration, err error) {
|
|
k := failKey(scope, key)
|
|
pipe := rl.rdb.Pipeline()
|
|
get := pipe.Get(ctx, k)
|
|
pttl := pipe.PTTL(ctx, k)
|
|
if _, err := pipe.Exec(ctx); err != nil && err != redis.Nil {
|
|
return 0, 0, fmt.Errorf("auth: failure count: %w", err)
|
|
}
|
|
n, _ := get.Int64()
|
|
d := pttl.Val()
|
|
if d < 0 {
|
|
d = 0
|
|
}
|
|
return n, d, nil
|
|
}
|
|
|
|
// ClearFailures removes the failure counter after a successful authentication.
|
|
func (rl *RateLimiter) ClearFailures(ctx context.Context, scope, key string) error {
|
|
return rl.rdb.Del(ctx, failKey(scope, key)).Err()
|
|
}
|
|
|
|
// uniqueMember returns a ZSET member that is unique even for attempts that share
|
|
// the same millisecond timestamp (timestamp prefix keeps ordering stable).
|
|
func uniqueMember(nowMs int64) (string, error) {
|
|
var b [8]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
return "", fmt.Errorf("auth: ratelimit member: %w", err)
|
|
}
|
|
return fmt.Sprintf("%d-%s", nowMs, hex.EncodeToString(b[:])), nil
|
|
}
|
|
|
|
// toInt64 coerces a Redis Lua return value (which may be int64 or string) to int64.
|
|
func toInt64(v interface{}) int64 {
|
|
switch t := v.(type) {
|
|
case int64:
|
|
return t
|
|
case string:
|
|
var n int64
|
|
_, _ = fmt.Sscanf(t, "%d", &n)
|
|
return n
|
|
default:
|
|
return 0
|
|
}
|
|
}
|