Skip to content

fix(auth): consume refresh tokens atomically during rotation - #8637

Merged
Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
lishuangqiang:fix/atomic-refresh-token-rotation
Nov 10, 2026
Merged

Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
lishuangqiang:fix/atomic-refresh-token-rotation

Conversation

@lishuangqiang

@lishuangqiang lishuangqiang commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

问题

RefreshTokenPair 现在用 GetRefreshToken + DeleteRefreshToken 两步完成轮转,Redis 操作不是原子的。两个并发请求可以都读到旧 token、都通过校验,然后各签发一套新 token(同一 family),同一个 refresh token 就被兑换了两次。

修复

  • RefreshTokenCache 新增 ConsumeRefreshToken;
  • Redis 实现用 Lua 脚本原子地 GET + DEL;
  • RefreshTokenPair 必须成功消费旧 token 才继续签发新 token;
  • 消费失败时:token 已被消费 → ErrRefreshTokenInvalid;Redis 错误 → ErrServiceUnavailable(fail closed,不再在旧 token 未失效时发新 token)。

测试

  • repository/refresh_token_cache_test.go:16 个 goroutine 并发消费同一个 token,只成功 1 次;
  • service/auth_service_refresh_race_test.go:用屏障让 8 个请求都先读到旧 token,再同时进入消费阶段;旧实现 8 个全部成功(测试失败),新实现 1 个成功 + 7 个 invalid。

本地验证:

  • go test -tags=unit ./internal/service/ 通过
  • handler 测试包编译通过
  • 两个新测试加 -race 通过

Closes #8638

RefreshTokenPair read the token and deleted it in two Redis calls. Two
concurrent requests with the same refresh token both passed the read and
validation, so both could mint a new token pair, keeping a stolen token
alive across rotations.

Add an atomic ConsumeRefreshToken (Lua GET+DEL) and require rotation to
win that consume. Losers get ErrRefreshTokenInvalid; Redis errors now
fail closed instead of issuing a new pair without invalidating the old
token.
@lishuangqiang

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@Wei-Shaw
Wei-Shaw merged commit efdc399 into Wei-Shaw:main Nov 10, 2026
9 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 10, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Refresh Token 轮转不是原子消费,并发刷新可以把同一个 token 兑换两次

2 participants