Files
pangolin/server/internal/auth/password.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

112 lines
3.9 KiB
Go

package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
// argon2id parameters. Tuned for a control-plane login path: ~64 MiB memory,
// single pass, 4 lanes. Kept as constants so the encoded hash is self-describing
// and parameters can evolve without breaking existing hashes (params are parsed
// back out of the stored string at verify time).
const (
argonMemory uint32 = 64 * 1024 // KiB → 64 MiB
argonTime uint32 = 1
argonThreads uint8 = 4
argonKeyLen uint32 = 32
argonSaltLen = 16
)
// errInvalidHash is returned when a stored PHC string cannot be parsed.
var errInvalidHash = errors.New("auth: invalid argon2id hash format")
// HashPassword derives an argon2id hash and returns it in the standard PHC
// string format: $argon2id$v=19$m=...,t=...,p=...$<salt>$<hash>.
func HashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("auth: read salt: %w", err)
}
return encodeArgon(password, salt, argonTime, argonMemory, argonThreads, argonKeyLen), nil
}
// encodeArgon computes the hash and formats the PHC string.
func encodeArgon(password string, salt []byte, t, m uint32, p uint8, keyLen uint32) string {
key := argon2.IDKey([]byte(password), salt, t, m, p, keyLen)
return fmt.Sprintf(
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, m, t, p,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key),
)
}
// VerifyPassword reports whether password matches the encoded argon2id hash.
// The comparison is constant-time. A malformed encoded hash returns false with
// an error so callers can distinguish "wrong password" from "corrupt record".
func VerifyPassword(encoded, password string) (bool, error) {
t, m, p, salt, key, err := decodeArgon(encoded)
if err != nil {
return false, err
}
other := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(key)))
if subtle.ConstantTimeCompare(key, other) == 1 {
return true, nil
}
return false, nil
}
// decodeArgon parses a PHC argon2id string back into its parameters.
func decodeArgon(encoded string) (t, m uint32, p uint8, salt, key []byte, err error) {
parts := strings.Split(encoded, "$")
// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, key]
if len(parts) != 6 || parts[1] != "argon2id" {
return 0, 0, 0, nil, nil, errInvalidHash
}
var version int
if _, err = fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return 0, 0, 0, nil, nil, errInvalidHash
}
if version != argon2.Version {
return 0, 0, 0, nil, nil, errInvalidHash
}
if _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil {
return 0, 0, 0, nil, nil, errInvalidHash
}
if salt, err = base64.RawStdEncoding.DecodeString(parts[4]); err != nil {
return 0, 0, 0, nil, nil, errInvalidHash
}
if key, err = base64.RawStdEncoding.DecodeString(parts[5]); err != nil {
return 0, 0, 0, nil, nil, errInvalidHash
}
return t, m, p, salt, key, nil
}
// dummyHash is a pre-computed argon2id hash used to spend roughly the same CPU
// time when a login targets a non-existent account, keeping the login response
// time constant regardless of whether the email exists. Computed lazily once.
var dummyHash = mustDummyHash()
func mustDummyHash() string {
h, err := HashPassword("pangolin-constant-time-placeholder")
if err != nil {
// Fall back to a static PHC string; verification will simply fail.
return "$argon2id$v=19$m=65536,t=1,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
}
return h
}
// ConstantTimeReject performs a throwaway argon2id verification against a dummy
// hash. Login handlers call this when the account does not exist so the timing
// profile matches the "account exists, wrong password" branch.
func ConstantTimeReject(password string) {
_, _ = VerifyPassword(dummyHash, password)
}