Files
new-api/model/auth_cache_integrity.go
Calcium-Ion 706144769e fix(auth): 校验 Redis 鉴权缓存完整性 (#8200)
* fix(auth): verify Redis authentication cache integrity

* fix(auth): repair auth cache hashes with unreadable fields

A token cache hash with a field that cannot be parsed, or with a stray
DeletedAt field, fell back to the database on every request and was
never rewritten. Repairs now read the stored signature on its own,
drop DeletedAt, and replace quota counters that are not integers in
both the token and user caches. Valid counters are still kept.
2026-11-04 22:58:20 +08:00

23 lines
657 B
Go

package model
import (
"crypto/hmac"
"time"
"github.com/QuantumNous/new-api/common"
)
// authCacheMAC binds cache metadata to its purpose and Redis key. Only
// database snapshots or server-created session states may be signed.
func authCacheMAC(key string, metadata any) (string, error) {
payload, err := common.Marshal(metadata)
if err != nil {
return "", err
}
return common.GenerateHMACWithKey([]byte("auth-cache-v1:"+common.CryptoSecret), key+"\x00"+string(payload)), nil
}
func validAuthCacheMAC(expected, actual string, expiresAt int64) bool {
return expiresAt > time.Now().UnixMilli() && hmac.Equal([]byte(expected), []byte(actual))
}