Skip to content

fix(openai): protect rotated oauth credentials from enrichment timeout and race conditions - #8671

Merged
Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
xuemk:fix/openai-oauth-token-rotation-persistence
Nov 20, 2026
Merged

Wei-Shaw merged 1 commit into
Wei-Shaw:mainfrom
xuemk:fix/openai-oauth-token-rotation-persistence

Conversation

@xuemk

@xuemk xuemk commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR addresses critical edge-case failures during OpenAI OAuth token rotation where rotated credentials (access_token,
refresh_token, and expires_at) could be lost or overwritten due to downstream enrichment timeouts or concurrent settings updates.

Problem

  1. Enrichment Context Cancellation: After OpenAI upstream successfully returns a new rotated
    refresh_token, subsequent account metadata enrichment (e.g. ChatGPT privacy/account checks) runs under the same attempt context. If enrichment times out or parent context cancels, the entire operation failed without saving the rotated credentials to PostgreSQL. Because OpenAI OAuth refresh tokens are single-use / rotated upon refresh, the old token is invalidated and the account becomes permanently unauthenticated (invalid_grant).
  2. Lock Expiration During Rotation: If background execution experiences network delay or slow database queries, the redis distributed lock could expire before the rotated credentials are saved, risking concurrent runs consuming invalidated tokens.
  3. Concurrent Account Settings Updates: While token rotation is executing in the background, user updates to non-credential account fields (proxy settings, model filters, etc.) could cause standard unconditional overwrites or CAS rejections, causing rotated tokens to be dropped.

Solution

  1. Uninterrupted Persistence: Wrapped credential persistence and token cache invalidation in context.WithoutCancel with a dedicated bounded timeout (10 seconds) once tokens are received from upstream, ensuring successful rotations are saved even if metadata enrichment times out or client cancels.
  2. CAS (Compare-And-Swap) Optimistic Concurrency:
    • Implemented UpdateOpenAIOAuthCredentialsIfUnchanged in accountRepository (mirroring Grok's pattern with parent_account_id IS NULL check).
    • Added 3x retry CAS merge in RefreshIfNeeded to preserve concurrent user-modified non-credential account settings (proxy/concurrency limits) while applying the rotated credentials.
  3. Lock Budgeting & Cycle Containment:
    • Enforce a minimum lock lease budget (20 seconds) before performing OpenAI token rotation to prevent lock expiration mid-flight.
    • If persistence fails after tokens have been rotated upstream, the provider is marked for cycle containment rather than retrying upstream with the already-consumed old token.

Verification

  • Added comprehensive unit tests in internal/service and internal/repository:
    • TestRefreshIfNeeded_OpenAIEnrichmentTimeoutKeepsRotatedCredentials
    • TestRefreshIfNeeded_OpenAILockLeaseReservesPersistenceBudget
    • TestRefreshIfNeeded_OpenAIShortLockLeaseDoesNotConsumeRefreshToken
    • TestRefreshIfNeeded_OpenAILateSuccessPersistsWithBoundedContext
    • TestRefreshIfNeeded_OpenAICASKeepsConcurrentReauthorization
    • TestRefreshIfNeeded_OpenAIPersistenceFailureContainsProvider
    • TestRefreshIfNeeded_OpenAICanceledWithoutSuccessfulCredentialsDoesNotPersist
    • TestTokenRefreshService_OpenAIRotationSurvivesAttemptDeadline
    • TestTokenRefreshService_OpenAIPersistenceFailureDoesNotRetryUpstream
    • TestTokenRefreshService_OpenAIParentCancellationStillPersists
    • TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_*
  • All tests passing: PASS ok github.com/Wei-Shaw/sub2api/internal/service, PASS ok github.com/Wei-Shaw/sub2api/internal/repository.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA. ✅
Posted by the CLA Assistant Lite bot.

@xuemk

xuemk commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

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

github-actions Bot added a commit that referenced this pull request Nov 11, 2026
riofutab added a commit to riofutab/sub2api that referenced this pull request Nov 13, 2026
riofutab added a commit to riofutab/sub2api that referenced this pull request Nov 13, 2026
riofutab added a commit to riofutab/sub2api that referenced this pull request Nov 13, 2026
- Claude 链路:令牌轮换后 401 同账号重试,per-turn beta 保留轮次输出配置,Stainless 版本头与抬升后的 UA 对齐(Wei-Shaw#8737 Wei-Shaw#8742 Wei-Shaw#8731 Wei-Shaw#8726 Wei-Shaw#8724 Wei-Shaw#8698)。
- Codex/OpenAI 链路:Desktop 独立上下文原样转发并删除 fork 的 bootstrap 扫描器,分叉会话沿用父会话缓存键,刷新后的令牌在补充信息超时时仍保存(Wei-Shaw#8680 Wei-Shaw#8664 Wei-Shaw#8671 Wei-Shaw#8735 Wei-Shaw#8682 Wei-Shaw#8703)。
- 构建:Go 升到 1.27.4 修复 GO-2026-6859(Wei-Shaw#8670);前端 Gemini 用量条刷新不再跳动(Wei-Shaw#8740)。
- fork 带的 Wei-Shaw#8034 测试改为断言轮换后的凭据被保存,并为测试桩补齐 CAS 方法。
- 后端全量 unit、golangci-lint、前端 lint/typecheck/账号组件测试通过;repository 集成测试未跑。
@xuemk
xuemk force-pushed the fix/openai-oauth-token-rotation-persistence branch from 00e6d89 to fb52c6e Compare November 16, 2026 16:01
@Wei-Shaw
Wei-Shaw merged commit c38a534 into Wei-Shaw:main Nov 20, 2026
7 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 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.

2 participants