原 jwtSecret() 每次调用都重新读取环境变量,为空时当场生成随机密钥,导致签发与验签各拿一把不同密钥——自己签发的 token 自己验不过,所有鉴权接口 100% 返回 401。这是 P0-1 的根因。 改为 Configure(Options) 启动期一次性注入:删除随机生成分支与硬编码 fallback-unsafe-key-change-me(后者在 rand.Read 失败时会让全网使用公开密钥,可伪造任意用户的 token,危害高于 401),新增 ≥32 字节长度校验与 ErrSecretNotConfigured 哨兵错误。 密钥按原始字节使用、不做任何派生变换,保证已配置密钥的部署升级后既有 token 继续有效。ParseToken 在解析前先取密钥,使畸形 token 也能稳定返回哨兵错误。新增 7 个回归用例。
159 lines
4.3 KiB
Go
159 lines
4.3 KiB
Go
// internal/auth/jwt.go
|
||
package auth
|
||
|
||
import (
|
||
"crypto/rand"
|
||
"crypto/sha256"
|
||
"encoding/hex"
|
||
"errors"
|
||
"fmt"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/golang-jwt/jwt/v5"
|
||
)
|
||
|
||
// MinSecretBytes 是 HS256 签名密钥要求的最小字节长度(256 bit)。
|
||
// 注意:这是"下限护栏",用于拦截空值/占位符/短口令这类部署事故,
|
||
// 不能替代真正的随机熵——请用 `openssl rand -hex 32` 生成。
|
||
const MinSecretBytes = 32
|
||
|
||
var (
|
||
// ErrSecretNotConfigured 表示 main 未调用 Configure。调用方应将其
|
||
// 视为服务端配置错误(HTTP 500),而非客户端凭证错误(HTTP 401)。
|
||
ErrSecretNotConfigured = errors.New("auth: JWT secret is not configured (call auth.Configure at startup)")
|
||
ErrSecretEmpty = errors.New("auth: JWT secret is empty")
|
||
ErrAccessTTLInvalid = errors.New("auth: AccessTokenTTL must be > 0")
|
||
|
||
secretMu sync.RWMutex
|
||
secretKey []byte
|
||
accessTTL time.Duration
|
||
)
|
||
|
||
// Options 是令牌签发策略,由 main 从 config 装载后一次性注入。
|
||
// 用结构体而非多个位置参数,是为了后续新增 refresh TTL / issuer / 轮换密钥时
|
||
// 不再改动函数签名。
|
||
type Options struct {
|
||
Secret string
|
||
AccessTokenTTL time.Duration
|
||
}
|
||
|
||
// Configure 设置 JWT 签名密钥与访问令牌有效期。必须在签发/校验任何 token
|
||
// 之前调用一次,通常由 main 在加载配置后立即调用。
|
||
//
|
||
// 密钥按原始字节使用,不做任何派生或编码变换(保证升级不失效既有 token)。
|
||
func Configure(opts Options) error {
|
||
if opts.Secret == "" {
|
||
return ErrSecretEmpty
|
||
}
|
||
if len(opts.Secret) < MinSecretBytes {
|
||
return fmt.Errorf("auth: JWT secret too short: %d bytes, need >= %d", len(opts.Secret), MinSecretBytes)
|
||
}
|
||
if opts.AccessTokenTTL <= 0 {
|
||
return ErrAccessTTLInvalid
|
||
}
|
||
|
||
secretMu.Lock()
|
||
secretKey = []byte(opts.Secret)
|
||
accessTTL = opts.AccessTokenTTL
|
||
secretMu.Unlock()
|
||
return nil
|
||
}
|
||
|
||
// currentAccessTTL 返回已配置的访问令牌有效期。
|
||
func currentAccessTTL() time.Duration {
|
||
secretMu.RLock()
|
||
defer secretMu.RUnlock()
|
||
return accessTTL
|
||
}
|
||
|
||
// Fingerprint 返回密钥的不可逆指纹(sha256 前 8 个 hex 字符)。
|
||
// 仅用于跨实例/跨进程核对"API 与 Worker 是否使用同一密钥",不泄露密钥本身。
|
||
func Fingerprint() string {
|
||
secretMu.RLock()
|
||
defer secretMu.RUnlock()
|
||
if len(secretKey) == 0 {
|
||
return "unconfigured"
|
||
}
|
||
sum := sha256.Sum256(secretKey)
|
||
return hex.EncodeToString(sum[:])[:8]
|
||
}
|
||
|
||
// secret 返回已配置的密钥;未配置时返回 ErrSecretNotConfigured。
|
||
func secret() ([]byte, error) {
|
||
secretMu.RLock()
|
||
defer secretMu.RUnlock()
|
||
if len(secretKey) == 0 {
|
||
return nil, ErrSecretNotConfigured
|
||
}
|
||
return secretKey, nil
|
||
}
|
||
|
||
type Claims struct {
|
||
AccountID uint `json:"account_id"`
|
||
Username string `json:"username"`
|
||
jwt.RegisteredClaims
|
||
}
|
||
|
||
func GenerateToken(accountID uint, username string) (string, error) {
|
||
key, err := secret()
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
|
||
now := time.Now()
|
||
claims := Claims{
|
||
AccountID: accountID,
|
||
Username: username,
|
||
RegisteredClaims: jwt.RegisteredClaims{
|
||
ExpiresAt: jwt.NewNumericDate(now.Add(currentAccessTTL())),
|
||
IssuedAt: jwt.NewNumericDate(now),
|
||
NotBefore: jwt.NewNumericDate(now),
|
||
},
|
||
}
|
||
|
||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
|
||
return token.SignedString(key)
|
||
}
|
||
|
||
func GenerateRefreshToken(accountID uint) (string, error) {
|
||
b := make([]byte, 32)
|
||
if _, err := rand.Read(b); err != nil {
|
||
return "", err
|
||
}
|
||
return hex.EncodeToString(b), nil
|
||
}
|
||
|
||
func ParseToken(tokenString string) (*Claims, error) {
|
||
// 先取密钥:这样即使 token 本身畸形(keyfunc 不会被调用),
|
||
// "密钥未配置"也能稳定地以 ErrSecretNotConfigured 返回。
|
||
key, err := secret()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
token, err := jwt.ParseWithClaims(
|
||
tokenString,
|
||
&Claims{},
|
||
func(token *jwt.Token) (interface{}, error) {
|
||
if token.Method == nil || token.Method.Alg() != jwt.SigningMethodHS256.Alg() {
|
||
return nil, errors.New("unexpected signing method")
|
||
}
|
||
return key, nil
|
||
},
|
||
// 双保险:拒绝 HS256 之外的一切算法(含 alg=none 类攻击)。
|
||
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
|
||
)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
claims, ok := token.Claims.(*Claims)
|
||
if !ok || !token.Valid {
|
||
return nil, jwt.ErrTokenInvalidClaims
|
||
}
|
||
|
||
return claims, nil
|
||
}
|