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>
141 lines
3.2 KiB
Go
141 lines
3.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/alicebob/miniredis/v2"
|
|
"github.com/google/uuid"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// newMiniRedis spins up an in-memory Redis and returns a connected client.
|
|
func newMiniRedis(t *testing.T) (*redis.Client, *miniredis.Miniredis) {
|
|
t.Helper()
|
|
mr, err := miniredis.Run()
|
|
if err != nil {
|
|
t.Fatalf("miniredis: %v", err)
|
|
}
|
|
t.Cleanup(mr.Close)
|
|
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
|
t.Cleanup(func() { _ = rdb.Close() })
|
|
return rdb, mr
|
|
}
|
|
|
|
// newRSAKey generates a 2048-bit RSA key for signing test tokens.
|
|
func newRSAKey(t *testing.T) *rsa.PrivateKey {
|
|
t.Helper()
|
|
k, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
t.Fatalf("rsa key: %v", err)
|
|
}
|
|
return k
|
|
}
|
|
|
|
// newTokenManager builds a TokenManager with the given clock and a single kid.
|
|
func newTokenManager(t *testing.T, rdb *redis.Client, now func() time.Time) *TokenManager {
|
|
t.Helper()
|
|
key := newRSAKey(t)
|
|
tm, err := NewTokenManager(rdb, TokenConfig{
|
|
SignKey: key,
|
|
SignKID: "k1",
|
|
AccessTTL: 15 * time.Minute,
|
|
RefreshTTL: 30 * 24 * time.Hour,
|
|
Now: now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewTokenManager: %v", err)
|
|
}
|
|
return tm
|
|
}
|
|
|
|
// --------------------------------------------------------------------------
|
|
// fakeStore — in-memory UserStore for unit tests.
|
|
// --------------------------------------------------------------------------
|
|
|
|
type trialRecord struct {
|
|
plan string
|
|
expiresAt time.Time
|
|
source string
|
|
}
|
|
|
|
type fakeStore struct {
|
|
mu sync.Mutex
|
|
byEmail map[string]*User
|
|
trials map[int64]trialRecord
|
|
nextID int64
|
|
}
|
|
|
|
func newFakeStore() *fakeStore {
|
|
return &fakeStore{byEmail: map[string]*User{}, trials: map[int64]trialRecord{}}
|
|
}
|
|
|
|
func (f *fakeStore) CreateUserWithTrial(_ context.Context, email, pwHash string, trialDays int) (*User, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if _, ok := f.byEmail[email]; ok {
|
|
return nil, ErrEmailTaken
|
|
}
|
|
f.nextID++
|
|
u := &User{
|
|
ID: f.nextID,
|
|
UUID: uuid.NewString(),
|
|
Email: email,
|
|
PwHash: pwHash,
|
|
DpUUID: uuid.NewString(),
|
|
Status: "active",
|
|
}
|
|
f.byEmail[email] = u
|
|
f.trials[u.ID] = trialRecord{
|
|
plan: "pro",
|
|
expiresAt: time.Now().UTC().AddDate(0, 0, trialDays),
|
|
source: "trial",
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
func (f *fakeStore) GetUserByEmail(_ context.Context, email string) (*User, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
u, ok := f.byEmail[email]
|
|
if !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
cp := *u
|
|
return &cp, nil
|
|
}
|
|
|
|
// setStatus mutates a stored user's status (e.g. to "banned") for tests.
|
|
func (f *fakeStore) setStatus(email, status string) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if u, ok := f.byEmail[email]; ok {
|
|
u.Status = status
|
|
}
|
|
}
|
|
|
|
// captureMailer records the last code it was asked to send.
|
|
type captureMailer struct {
|
|
mu sync.Mutex
|
|
last map[string]string
|
|
}
|
|
|
|
func newCaptureMailer() *captureMailer { return &captureMailer{last: map[string]string{}} }
|
|
|
|
func (m *captureMailer) SendCode(_ context.Context, to, code string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.last[to] = code
|
|
return nil
|
|
}
|
|
|
|
func (m *captureMailer) codeFor(to string) string {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
return m.last[to]
|
|
}
|