Skip to content

fix: serialize shared OAuth profile refreshes - #54856

Closed
owen-ever wants to merge 9 commits into
openclaw:mainfrom
owen-ever:fix/oauth-refresh-profile-mutex
Closed

owen-ever wants to merge 9 commits into
openclaw:mainfrom
owen-ever:fix/oauth-refresh-profile-mutex

Conversation

@owen-ever

@owen-ever owen-ever commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • serialize refreshes per provider/profile within the gateway process so concurrent callers reuse one in-flight refresh
  • reload auth-profiles on refresh_token_reused and retry once when another refresh rotated only the refresh token
  • add focused regression coverage for concurrent refresh, reload-after-reuse, and reload+retry paths

Closes #26322.

Validation

  • corepack pnpm exec vitest run src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
  • corepack pnpm exec vitest run src/agents/auth-profiles/oauth.test.ts src/agents/auth-profiles/oauth.fallback-to-main-agent.test.ts src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
  • NODE_OPTIONS='--max-old-space-size=8192' corepack pnpm exec tsc -p /tmp/tsconfig.oauth-check.json --noEmit --pretty false | rg 'src/agents/auth-profiles/oauth.ts|src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts'

AI Disclosure

  • AI-assisted (Claude)
  • Fully tested (vitest + tsc type-check)
  • Author understands what the code does
  • Bot review conversations resolved

@owen-ever
owen-ever requested a review from a team as a code owner March 26, 2026 03:35
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Mar 26, 2026

@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: 921ebb9d60

ℹ️ 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 thread src/agents/auth-profiles/oauth.ts Resolved
@greptile-apps

greptile-apps Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a race condition where concurrent callers in the same gateway process could each independently attempt to refresh the same OAuth profile, burning the rotation token multiple times. It introduces a process-scoped in-flight map (keyed by provider:profileId) so that concurrent callers deduplicate onto one refresh and each writes the result to their own agent dir via awaitOAuthRefreshResult. On top of that it adds refresh_token_reused detection with a reload-then-retry path to gracefully handle the case where another process already rotated the token before this process got to it.\n\n- Serialization (oauthRefreshInFlight map + awaitOAuthRefreshResult): JavaScript's single-threaded execution model guarantees the check-then-set in refreshOAuthTokenWithLock is atomic; the implementation is correct.\n- refresh_token_reused recovery: first attempts a credential reload; if the stored token is still expired (only the refresh token was rotated) it falls back to a single retry via refreshOAuthTokenFromStoreWithLock — clean and bounded to one attempt.\n- Idempotent writes: syncOAuthCredentialToStore short-circuits when credentials haven't changed, protecting against the double-sync that can occur when loadFreshStoredOAuthCredential and awaitOAuthRefreshResult both fire for the originating caller.\n- Test coverage: the three new tests target each new code path. The concurrent test is slightly incomplete — it doesn't assert that workerAgentDir's store is also written — which is the secondary half of the deduplication guarantee.

Confidence Score: 4/5

Safe to merge; the core logic is correct and no data-loss or security regressions were found.

The serialization approach is sound for Node.js's single-threaded event loop, the refresh_token_reused retry is properly bounded to one attempt, and idempotent writes prevent duplicate disk operations. One minor targeted fix would strengthen the test: the concurrent test should also assert that workerAgentDir's store receives the refreshed credentials, since that is the second half of the deduplication contract that awaitOAuthRefreshResult is responsible for.

oauth.openai-codex-refresh-fallback.test.ts — the concurrent test is missing an assertion for workerAgentDir store update.

Important Files Changed

Filename Overview
src/agents/auth-profiles/oauth.ts Core OAuth refresh logic refactored to add process-scoped in-flight deduplication, refresh_token_reused recovery (reload + single retry), and a new syncOAuthCredentialToStore helper. Logic is sound; minor redundant sync for the in-flight originator when fresh credentials were already on disk.
src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts Three new regression tests added for concurrent refresh, reload-after-reuse, and reload+retry paths. The concurrent test is missing an assertion that workerAgentDir's store receives the refreshed credentials.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/oauth.ts
Line: 374-383

Comment:
**Redundant `syncOAuthCredentialToStore` call for the in-flight originator**

When `loadFreshStoredOAuthCredential` finds fresh credentials it already syncs them to `params.agentDir` (line ~215–222). The IIFE then resolves with that value, and the outer `awaitOAuthRefreshResult` call (line 417) invokes `syncOAuthCredentialToStore` on the same `agentDir` a second time. The idempotency check inside `syncOAuthCredentialToStore` prevents a duplicate disk write, but it still acquires and releases the file lock a second time for the originating caller.

Secondary / waiting callers are fine — their `agentDir` differs from the IIFE's and only the outer `awaitOAuthRefreshResult` writes to them. The redundancy is limited to the caller that actually started the refresh. Consider skipping the outer sync when `freshStored` was the source of the result (e.g. by returning an already-synced marker or by having `loadFreshStoredOAuthCredential` accept a flag indicating it should skip in-place sync when the caller will sync afterwards).

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

---

This is a comment left during a code review.
Path: src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
Line: 245-261

Comment:
**Worker agent dir credentials not verified**

The concurrent-serialization test is the core regression coverage for this PR's deduplication guarantee, but it only asserts that `agentDir` (the main agent) ends up with the refreshed credentials. Since `awaitOAuthRefreshResult` is responsible for writing the result to each waiter's own `agentDir`, a matching `readStoredProfile(workerAgentDir, profileId)` assertion would confirm that secondary callers also get their stores updated — the other half of the shared-refresh contract.

Consider adding after the existing `readStoredProfile(agentDir, profileId)` assertion:

```ts
await expect(readStoredProfile(workerAgentDir, profileId)).resolves.toMatchObject({
  access: "fresh-access-token", // pragma: allowlist secret
  refresh: "fresh-refresh-token",
});
```

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

Reviews (1): Last reviewed commit: "fix: serialize oauth profile refreshes" | Re-trigger Greptile

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@Mdx2025

This comment was marked as spam.

@Mdx2025

This comment was marked as spam.

@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: 8af734bdf7

ℹ️ 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 thread src/agents/auth-profiles/oauth.ts Resolved

@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: c3c459c128

ℹ️ 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 thread src/agents/auth-profiles/oauth.ts Resolved

@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: 79142def9e

ℹ️ 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 thread src/agents/auth-profiles/oauth.ts Resolved
Replace blacklist-style guards in syncOAuthCredentialToStore with a
single whitelist condition: only update when an existing OAuth profile
with a matching provider is present. This prevents resurrecting
deleted profiles and simplifies the guard logic.
All Date.now() < expires comparisons now guard with Number.isFinite()
first, so NaN/undefined/non-numeric expires values are treated as
stale and trigger a refresh instead of silently reusing an invalid
access token.
@owen-ever
owen-ever force-pushed the fix/oauth-refresh-profile-mutex branch from a27c505 to cd18846 Compare March 31, 2026 00:25

@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: cd1884630f

ℹ️ 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 +170 to +173
const current = store.profiles[params.profileId];
if (!current || current.type !== "oauth" || current.provider !== params.provider) {
return false;
}

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 Guard OAuth sync against concurrent OAuth credential swaps

syncOAuthCredentialToStore only checks type and provider before writing, so an in-flight refresh can still overwrite a newer OAuth login for the same profile/provider. This happens when an operator (or another process) re-authenticates the profile to a different OAuth account while the refresh promise is running: the updater still accepts the row and writes newCredentials, effectively rolling back the newer credential set. The updater should also verify the current OAuth fields still match the credential snapshot that initiated the refresh (or another monotonic version check) before replacing tokens.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This PR addresses concurrent refresh serialization for the same profile, not mid-refresh account re-authentication.

The syncOAuthCredentialToStore write guard (type + provider match) is pre-existing behavior unchanged by this PR. A monotonic version check for credential swaps during refresh is a valid hardening idea but falls outside this fix's scope — happy to track as a follow-up issue.

@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: 683d1b1060

ℹ️ 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".

previous?: Pick<OAuthCredential, "access" | "refresh" | "expires">;
requireChange?: boolean;
}): Promise<OAuthRefreshResult | null> {
const reloadedStore = loadAuthProfileStoreForSecretsRuntime(params.agentDir);

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 OAuth refresh reloads snapshot-aware

loadFreshStoredOAuthCredential now reloads credentials with loadAuthProfileStoreForSecretsRuntime, which bypasses active runtime auth-store snapshots and reads directly from disk. In an active secrets-runtime snapshot (where callers pass snapshot-backed stores from ensureAuthProfileStore), this can silently return fresher/different disk credentials than the snapshot and change which account/token is used during refresh resolution, breaking snapshot consistency for that run. The reload here should use the same snapshot-aware source as the caller (or explicitly gate disk reloads when snapshots are active).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The disk reload in loadFreshStoredOAuthCredential is intentional — it detects whether another process has already rotated the refresh token, which is the core mechanism for refresh_token_reused recovery. Using snapshot-aware stores here would return stale credentials in exactly the scenario this PR fixes.

This disk read is scoped to the refresh-retry path only and doesn't affect normal token resolution. Secrets-runtime snapshot consistency is a broader pre-existing concern outside this PR's scope.

@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: e117fb0cc9

ℹ️ 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 (
result &&
params.agentDir &&
(!result.originAgentDir || result.originAgentDir !== params.agentDir)

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 Skip post-refresh resync when origin is unknown

The new awaitOAuthRefreshResult path rewrites result.newCredentials whenever originAgentDir is falsy, and refreshOAuthTokenFromStoreWithLock's plugin-refresh return still omits originAgentDir; that means plugin refreshes for agent-scoped stores now do an extra post-lock write. If the profile is re-authenticated to a different OAuth account (same provider/profileId) between the lock-protected refresh write and this follow-up sync, this second write can roll back the newer credentials. Fresh evidence in this commit is the newly introduced awaitOAuthRefreshResult branch with the !result.originAgentDir condition.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This follows the same pattern as the earlier credential-swap concern (#7). The !originAgentDir branch ensures plugin-refresh results are propagated to the requesting agent's store — without it, agent-scoped callers would silently miss refreshed tokens.

The mid-refresh re-authentication race is a pre-existing concern outside this PR's scope, as noted in #7. The extra write is intentional and necessary for correctness in the common case.

@owen-ever

Copy link
Copy Markdown
Contributor Author

@tyler6204 @vincentkoc This PR is ready for review — all bot review conversations have been addressed, and the remaining CI failure (task-owner-access.test.ts timeout on Windows) is an infra-flaky issue unrelated to this change. Would appreciate a look when you get a chance. 🙏

@steipete

steipete commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Thanks, I landed a narrowed version of this directly on main here:

9d7459f

What shipped from the original direction:

  • locked refresh now reloads on-disk auth state instead of trusting runtime snapshots
  • on refresh_token_reused, OpenClaw adopts fresher stored creds when they already exist
  • if only the stored refresh token rotated, OpenClaw retries refresh once with the reloaded token lineage
  • focused regression coverage + changelog

What I intentionally left out:

  • process-scoped in-flight mutex / cross-store fanout
  • broader auth-store sync helper refactor
  • stale openai-codex:default vs named-profile selection/migration work

Reason for the cut: the minimal refresh-recovery fix was clear and shippable on its own, while the larger PR was mixing that with adjacent profile-selection/store-topology problems.

@vincentkoc vincentkoc added the dedupe:child Duplicate issue/PR child in dedupe cluster label Apr 25, 2026
@vincentkoc vincentkoc added the close:duplicate Closed as duplicate label Apr 25, 2026
@vincentkoc vincentkoc self-assigned this Apr 25, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Thanks for the focused refresh-race fix.

I am closing this as superseded by the merged Codex OAuth hardening in #68396 and the canonical issue closeout at #52037. The merged path includes shared OAuth refresh hardening, fresh-store reload/retry behavior, and Codex CLI bootstrap/auth-store coverage beyond this older PR.

If you think a specific assertion from this PR is still missing on current main, point me at it and I can reopen review right away.

@vincentkoc vincentkoc closed this Apr 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling close:duplicate Closed as duplicate dedupe:child Duplicate issue/PR child in dedupe cluster size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OAuth token refresh race condition causes spurious failovers (refresh_token_reused)

4 participants