Skip to content

fix(auth): proactively refresh OAuth token before expiry to prevent concurrent-agent race condition - #60673

Closed
wiliyam wants to merge 4 commits into
openclaw:mainfrom
wiliyam:fix/proactive-oauth-token-refresh-before-expiry
Closed

wiliyam wants to merge 4 commits into
openclaw:mainfrom
wiliyam:fix/proactive-oauth-token-refresh-before-expiry

Conversation

@wiliyam

@wiliyam wiliyam commented Apr 4, 2026

Copy link
Copy Markdown

Summary

Fixes the OAuth token refresh race condition that occurs when multiple agents run in parallel.

Root Cause

EXTERNAL_CLI_NEAR_EXPIRY_MS (10 min) was defined in constants.ts but never used in the actual refresh logic in oauth.ts. Both expiry check sites used:

if (Date.now() < cred.expires) {
  return cachedToken; // valid
}
// else: refresh

This means tokens are only considered stale at the exact moment they expire. When multiple agents (e.g. 3–5 parallel claude --print jobs building different services in a monorepo) all run past the 3-hour mark simultaneously, they all reach cred.expires at the same instant.

Even though withFileLock serialises the refresh attempts, the first agent successfully uses the single-use refreshToken, making it invalid. Every subsequent agent then fails with invalid_grant, wipes credentials.json, and crashes — killing all running sessions and hours of work.

Fix

Wire up the already-defined EXTERNAL_CLI_NEAR_EXPIRY_MS constant into both expiry checks in oauth.ts:

// Before
if (Date.now() < cred.expires) { ... }

// After — treat token as stale 10 min before it actually expires
if (Date.now() < cred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) { ... }

Now tokens are refreshed proactively while still valid. The file lock ensures exactly one agent performs the refresh, saves the new token, and releases. All waiting agents then re-read the freshly refreshed credentials instead of racing on the same dying refresh token.

Affected files

  • src/agents/auth-profiles/oauth.ts — 2 expiry checks + import

Real-world reproduction

Running 3+ parallel Claude Code agents across a monorepo (UTP platform with 5 services) consistently triggered this bug after ~3 hours. Every agent died simultaneously with token errors requiring manual re-login.

@wiliyam
wiliyam requested a review from a team as a code owner April 4, 2026 04:05
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Apr 4, 2026
@greptile-apps

greptile-apps Bot commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR wires up the already-defined EXTERNAL_CLI_NEAR_EXPIRY_MS constant (10 minutes) into the OAuth token expiry checks in oauth.ts so that tokens are refreshed proactively before expiry, preventing a concurrent-agent race condition on single-use refresh tokens.

The core fix is sound — refreshOAuthTokenWithLock re-reads the credential store after acquiring the file lock, so the first agent to refresh saves a new token and subsequent agents see the fresh credential and skip their own refresh. However, one expiry check was left behind:

  • resolveApiKeyForProfile (line 439): ✅ updated with buffer
  • refreshOAuthTokenWithLock (line 183): ✅ updated with buffer (double-check after acquiring the lock)
  • tryResolveOAuthProfile (line 285): ❌ still uses the bare Date.now() < cred.expires check — this function is invoked in the error-fallback path when a legacy/alternative profile ID is tried, and leaves the same race window open for that code path

Confidence Score: 3/5

Safe to merge for the primary race condition, but the fix is incomplete — the fallback profile path in tryResolveOAuthProfile retains the old near-expiry race window.

The two most critical expiry checks (the hot path in resolveApiKeyForProfile and the post-lock double-check in refreshOAuthTokenWithLock) are correctly fixed, which will eliminate the race condition in the vast majority of cases. The missed check in tryResolveOAuthProfile (line 285) only affects the error-recovery fallback path (legacy profile ID), so it has a much lower blast radius. The overall change is directionally correct but incomplete; a one-line fix to tryResolveOAuthProfile would make it fully consistent.

src/agents/auth-profiles/oauth.ts — specifically the expiry check inside tryResolveOAuthProfile at line 285

Comments Outside Diff (1)

  1. src/agents/auth-profiles/oauth.ts, line 285 (link)

    P1 Incomplete fix: tryResolveOAuthProfile still uses the old expiry check

    The two expiry checks in resolveApiKeyForProfile (line 439) and refreshOAuthTokenWithLock (line 183) were correctly updated to use the EXTERNAL_CLI_NEAR_EXPIRY_MS buffer, but this third expiry check in tryResolveOAuthProfile was missed. It still returns a cached (potentially nearly-expired) token if Date.now() < cred.expires.

    tryResolveOAuthProfile is called in the error-fallback path when the primary refresh fails and a legacy/fallback profile ID is tried (line ~480). If that fallback credential also sits within the 10-minute near-expiry window, this function will return it without acquiring the lock and refreshing — leaving the same race condition intact for the fallback path.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/auth-profiles/oauth.ts
    Line: 285
    
    Comment:
    **Incomplete fix: `tryResolveOAuthProfile` still uses the old expiry check**
    
    The two expiry checks in `resolveApiKeyForProfile` (line 439) and `refreshOAuthTokenWithLock` (line 183) were correctly updated to use the `EXTERNAL_CLI_NEAR_EXPIRY_MS` buffer, but this third expiry check in `tryResolveOAuthProfile` was missed. It still returns a cached (potentially nearly-expired) token if `Date.now() < cred.expires`.
    
    `tryResolveOAuthProfile` is called in the error-fallback path when the primary refresh fails and a legacy/fallback profile ID is tried (line ~480). If that fallback credential also sits within the 10-minute near-expiry window, this function will return it without acquiring the lock and refreshing — leaving the same race condition intact for the fallback path.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/oauth.ts
Line: 285

Comment:
**Incomplete fix: `tryResolveOAuthProfile` still uses the old expiry check**

The two expiry checks in `resolveApiKeyForProfile` (line 439) and `refreshOAuthTokenWithLock` (line 183) were correctly updated to use the `EXTERNAL_CLI_NEAR_EXPIRY_MS` buffer, but this third expiry check in `tryResolveOAuthProfile` was missed. It still returns a cached (potentially nearly-expired) token if `Date.now() < cred.expires`.

`tryResolveOAuthProfile` is called in the error-fallback path when the primary refresh fails and a legacy/fallback profile ID is tried (line ~480). If that fallback credential also sits within the 10-minute near-expiry window, this function will return it without acquiring the lock and refreshing — leaving the same race condition intact for the fallback path.

```suggestion
  if (Date.now() < cred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) {
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(auth): proactively refresh OAuth tok..." | Re-trigger Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c980ed6c28

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// Use EXTERNAL_CLI_NEAR_EXPIRY_MS buffer: refresh proactively before expiry to avoid
// race condition where multiple concurrent agents all attempt to refresh the same
// single-use refresh token at the exact moment it expires.
if (Date.now() < oauthCred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep valid OAuth token when proactive refresh is unsupported

This new near-expiry gate sends every OAuth profile with <10m remaining into refreshOAuthTokenWithLock, and if refresh returns null the caller immediately returns null (resolveApiKeyForProfile), even though the access token is still valid until oauthCred.expires. That regresses providers/auth paths without a working refresher (for example plugin providers that register OAuth but no refreshOAuth, such as extensions/google/gemini-cli-provider.ts), causing avoidable auth failures during the final 10 minutes of token lifetime.

Useful? React with 👍 / 👎.

wiliyam added 2 commits April 4, 2026 08:48
…oncurrent-agent race

EXTERNAL_CLI_NEAR_EXPIRY_MS (10 min) was defined in constants but never used
in the refresh logic. Both refresh check sites used `Date.now() < cred.expires`
which only returns the cached token if it is not yet expired.

When multiple agents run in parallel (e.g. parallel Claude Code builds across
a monorepo), they all reach token expiry at the same instant and simultaneously
enter refreshOAuthTokenWithLock. Even though the lock serialises the refreshes,
the first agent to succeed invalidates the single-use refresh token. Every
subsequent agent then fails with invalid_grant, wiping credentials.json and
killing all running sessions.

Fix: apply the EXTERNAL_CLI_NEAR_EXPIRY_MS (10 min) buffer to both expiry
checks so tokens are treated as stale before they actually expire. The lock
ensures exactly one agent performs the refresh while others wait and then
re-read the already-refreshed credentials — rather than all rushing to
refresh the same dying token at the same moment.

The constant was added specifically for this use-case but was never wired
into the oauth.ts expiry checks.
…k path

Greptile review caught a missed expiry check in tryResolveOAuthProfile
(the error-fallback path). Apply the same EXTERNAL_CLI_NEAR_EXPIRY_MS
buffer for consistency — all three expiry check sites now proactively
refresh before the token actually expires.
@wiliyam
wiliyam force-pushed the fix/proactive-oauth-token-refresh-before-expiry branch from 6be280e to 3b4c9e4 Compare April 4, 2026 08:48

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b4c9e4857

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (Date.now() < cred.expires) {
// Apply EXTERNAL_CLI_NEAR_EXPIRY_MS buffer here too for consistency with the other
// expiry checks — ensures fallback profile path also proactively refreshes.
if (Date.now() < cred.expires - EXTERNAL_CLI_NEAR_EXPIRY_MS) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep fallback OAuth profile usable near expiry

The new near-expiry check in tryResolveOAuthProfile forces a refresh attempt for the last 10 minutes of token lifetime, so fallback profiles now fail when they use OAuth providers that cannot refresh (refreshOAuth missing and no core getOAuthApiKey provider). In that case refreshOAuthTokenWithLock returns null, tryResolveOAuthProfile drops the fallback, and the caller rethrows the original error even though the fallback access token is still valid; this turns a recoverable primary-profile refresh failure into an auth outage during the near-expiry window.

Useful? React with 👍 / 👎.

@wiliyam

wiliyam commented Apr 4, 2026

Copy link
Copy Markdown
Author

The CI failures are pre-existing and unrelated to this PR's changes:

  • extensions/zai/index.test.ts: error TS7006 — implicit any types on parameters _provider and modelId (lines 80, 125, 152). This file is unchanged by this PR and the same errors appear when checking out main directly.

This PR only modifies src/agents/auth-profiles/oauth.ts. Happy to rebase again if main gets fixed, but these failures are not caused by our changes.

wiliyam and others added 2 commits April 21, 2026 07:07
…handle null refresh gracefully

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…sh returns null

Mirrors the same null-refresh guard already in resolveApiKeyForProfile.
If refreshOAuthTokenWithLock returns null (e.g. provider has no
refreshOAuth implementation) but the access token is still valid until
cred.expires, return the existing credentials instead of dropping the
fallback profile. Prevents auth outages in the near-expiry window for
providers without refresh support (e.g. gemini-cli-provider).

Addresses chatgpt-codex-connector P2 review comment on PR openclaw#60673.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 783df3d0f7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines 299 to +303
if (!refreshed) {
// If refresh returned null (e.g. provider has no refreshOAuth implementation)
// but the token hasn't actually expired yet, fall back to the existing token
// rather than dropping the fallback profile entirely.
if (Date.now() < cred.expires) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Catch refresh exceptions for fallback OAuth profiles

This block only recovers when refreshOAuthTokenWithLock returns null, but the new near-expiry path now calls refresh for still-valid fallback tokens and that helper can throw (for example when cred.managedBy is set but readManagedExternalCliCredential is unavailable). In that case tryResolveOAuthProfile throws instead of using the still-valid fallback token, so resolveApiKeyForProfile discards the fallback and rethrows the original error during the last 10 minutes before expiry.

Useful? React with 👍 / 👎.

@wiliyam

wiliyam commented Apr 21, 2026

Copy link
Copy Markdown
Author

Pushed 783df3d0 to address both bot review comments:

  1. Line 285 (tryResolveOAuthProfile) — the EXTERNAL_CLI_NEAR_EXPIRY_MS buffer was already applied in an earlier commit (3b4c9e48).

  2. Null refresh fallback in tryResolveOAuthProfile — added the same guard already present in resolveApiKeyForProfile: when refreshOAuthTokenWithLock returns null (provider has no refreshOAuth implementation, e.g. gemini-cli-provider) but the token is still valid until cred.expires, we fall back to the existing token rather than returning null and breaking auth.

Both the primary hot-path (resolveApiKeyForProfile) and the error-fallback path (tryResolveOAuthProfile) now have consistent near-expiry + null-refresh handling.

@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Current main already covers this PR’s goal with a broader OAuth refresh flow: near-expiry OAuth credentials are treated as stale before hard expiry, refreshes are serialized through a shared per-profile lock, and the concurrent-agent race now has direct regression coverage. The open PR is therefore redundant against shipped code on main.

What I checked:

So I’m closing this as already implemented rather than keeping a duplicate issue open.

Review notes: reviewed against 6bc0dc8fb671; fix evidence: release v2026.4.23, commit a9797214338b.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants