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>
107 lines
3.4 KiB
Go
107 lines
3.4 KiB
Go
// Package config holds application configuration loaded from environment variables.
|
|
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Config holds all application-level configuration.
|
|
type Config struct {
|
|
// DSN is the MySQL connection string.
|
|
// Format: user:password@tcp(host:port)/dbname?parseTime=true&loc=UTC&time_zone=%%27UTC%%27
|
|
DSN string
|
|
|
|
// RedisAddr is the Redis server address (host:port).
|
|
RedisAddr string
|
|
RedisPassword string
|
|
RedisDB int
|
|
|
|
// WebhookSecret is the HMAC-SHA256 shared secret for the card-store webhook.
|
|
// Must be set; no default.
|
|
WebhookSecret string
|
|
|
|
// RedeemFailMax is the number of consecutive redeem failures before a 1-hour lock.
|
|
// Default: 5
|
|
RedeemFailMax int
|
|
|
|
// RedeemLockDuration is how long the lock lasts after hitting RedeemFailMax.
|
|
// Default: 1 hour
|
|
RedeemLockDuration time.Duration
|
|
|
|
// WebhookTimestampTolerance is the ±window for webhook timestamp validation.
|
|
// Default: 5 minutes
|
|
WebhookTimestampTolerance time.Duration
|
|
|
|
// WebhookNonceTTL is how long a webhook nonce is kept in Redis to prevent replay.
|
|
// Should be > 2 * WebhookTimestampTolerance. Default: 15 minutes.
|
|
WebhookNonceTTL time.Duration
|
|
|
|
// ── Auth / JWT (RS256) ────────────────────────────────────────────────
|
|
// JWTPrivateKeyPath is the PEM file holding the active RS256 signing key.
|
|
JWTPrivateKeyPath string
|
|
// JWTKeyID is the `kid` written into the JWT header (identifies the signing key).
|
|
JWTKeyID string
|
|
// JWTPublicKeys maps kid -> PEM public-key file path. It must include the
|
|
// active key's kid and may carry previous keys still accepted during
|
|
// rotation. Parsed from JWT_PUBLIC_KEYS="kid1:/path1,kid2:/path2".
|
|
JWTPublicKeys map[string]string
|
|
}
|
|
|
|
// FromEnv reads configuration from environment variables.
|
|
// Returns an error if required variables are missing.
|
|
func FromEnv() (*Config, error) {
|
|
c := &Config{
|
|
DSN: os.Getenv("DB_DSN"),
|
|
RedisAddr: getEnvDefault("REDIS_ADDR", "127.0.0.1:6379"),
|
|
RedisPassword: os.Getenv("REDIS_PASSWORD"),
|
|
RedisDB: 0,
|
|
WebhookSecret: os.Getenv("WEBHOOK_SECRET"),
|
|
RedeemFailMax: 5,
|
|
RedeemLockDuration: time.Hour,
|
|
WebhookTimestampTolerance: 5 * time.Minute,
|
|
WebhookNonceTTL: 15 * time.Minute,
|
|
JWTPrivateKeyPath: os.Getenv("JWT_PRIVATE_KEY_PATH"),
|
|
JWTKeyID: os.Getenv("JWT_KEY_ID"),
|
|
JWTPublicKeys: parseKeyMap(os.Getenv("JWT_PUBLIC_KEYS")),
|
|
}
|
|
|
|
if c.DSN == "" {
|
|
return nil, fmt.Errorf("config: DB_DSN is required")
|
|
}
|
|
if c.WebhookSecret == "" {
|
|
return nil, fmt.Errorf("config: WEBHOOK_SECRET is required")
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
func getEnvDefault(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
// parseKeyMap parses a "kid1:/path1,kid2:/path2" string into a map. Empty input
|
|
// yields a nil map. Malformed entries (missing ':') are skipped.
|
|
func parseKeyMap(raw string) map[string]string {
|
|
if raw == "" {
|
|
return nil
|
|
}
|
|
m := map[string]string{}
|
|
for _, pair := range strings.Split(raw, ",") {
|
|
pair = strings.TrimSpace(pair)
|
|
if pair == "" {
|
|
continue
|
|
}
|
|
i := strings.IndexByte(pair, ':')
|
|
if i <= 0 || i == len(pair)-1 {
|
|
continue
|
|
}
|
|
m[strings.TrimSpace(pair[:i])] = strings.TrimSpace(pair[i+1:])
|
|
}
|
|
return m
|
|
}
|