Skip to content

fix: use global OAuth refresh lock to prevent cross-agent race (#26322) - #51476

Closed
HeroSizy wants to merge 11 commits into
openclaw:mainfrom
HeroSizy:fix/oauth-lock-racing-condition-squashed
Closed

HeroSizy wants to merge 11 commits into
openclaw:mainfrom
HeroSizy:fix/oauth-lock-racing-condition-squashed

Conversation

@HeroSizy

@HeroSizy HeroSizy commented Mar 21, 2026 •

Copy link
Copy Markdown

Summary

  • Problem: shared OAuth profiles could race refresh, and follow-up review uncovered new corruption and null-return paths once refresh stopped holding the per-store auth lock for the whole network round-trip.
  • Why it matters: agents could overwrite newer auth-mode changes, leak OAuth tokens across agent stores, contend on ambiguous lock paths, or fail inherited-profile refreshes even when valid main-store credentials existed.
  • What changed: kept the global per-profile refresh lock, but made post-refresh writes compare-and-set against the exact persisted OAuth snapshot; tightened cross-agent identity checks; switched auth-store reads under the global refresh lock to read-only; replaced variable-length UTF-8 hex lock ids with bounded SHA-256 lock ids; fixed inherited main-store profile refresh and merged-store re-resolution paths; returned freshly refreshed credentials for the in-flight request when CAS persistence cannot complete and no newer auth state is visible; added focused regressions for each race.
  • What did NOT change (scope boundary): plugin OAuth refresh interfaces, failover/cooldown behavior, non-OAuth auth-store mutation semantics outside these refresh races, or the overall main-agent/shared-profile model.

Change Type (select all)

  • Bug fix
  • Security hardening

Scope (select all touched areas)

  • Auth / tokens

Linked Issue/PR

Root Cause / Regression History (if applicable)

  • Root cause: the global refresh lock fixed the thundering-herd network race, but the original follow-up write paths still assumed the same local OAuth entry remained authoritative after refresh. That was wrong for delete/re-auth races, inherited main-store profiles, and providers without stable identity metadata. The first lock-path encoder also allowed ambiguous or unsafe filenames.
  • Missing detection / guardrail: there was no compare-and-set write against the persisted OAuth snapshot, no strict positive-identity requirement for cross-agent token sharing, no focused inherited-profile retry coverage, and no lock-path tests for distinct ids, dot-segment safety, and bounded filename length.
  • Prior context (git blame, prior PR, issue, or refactor if known): this PR started as a fix for the shared-profile refresh_token_reused race described in OAuth token refresh race condition causes spurious failovers (refresh_token_reused) #26322. Review then surfaced the post-refresh corruption paths introduced by shortening the lock scope.
  • Why this regressed now: refresh is now serialized by a global per-profile lock instead of the per-store auth lock, so stale post-refresh writes had to become conditional instead of relying on old lock ordering.
  • If unknown, what was ruled out: N/A

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts, src/agents/auth-profiles/oauth.fallback-to-main-agent.test.ts, src/agents/auth-profiles.paths.test.ts
  • Scenario the test should lock in: delete/type-change during refresh, provider-only identity mismatch, inherited main-store profile refresh/write-back, merged-store re-resolution after a null refresh result, current-request success when auth-store CAS persistence times out after refresh, and distinct, dot-safe, bounded-length lock path encoding.
  • Why this is the smallest reliable guardrail: these tests exercise the real auth-store merge, refresh, and persistence behavior across main/sub-agent stores without needing live multi-process OAuth.
  • Existing test that already covers this (if any): src/agents/auth-profiles/oauth.test.ts still covers the baseline OAuth resolution behavior.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • OAuth refresh is serialized per shared profile, avoiding refresh_token_reused stampedes.
  • In-flight refreshes no longer recreate deleted profiles or overwrite a newer token / api_key re-auth.
  • Cross-agent OAuth adoption/write-back now requires positive identity evidence (accountId or matching email) or exact credential equivalence, preserving per-agent account isolation.
  • A request that successfully refreshes OAuth can still proceed even if the local CAS write-back times out, as long as no newer auth mode is visible in the merged runtime store.
  • Refresh lock filenames are now namespace-safe, bounded in length, and hash-based.
  • Sub-agents that inherit OAuth profiles from main now refresh and recover correctly without forcing a local clone of that profile.

Diagram (if applicable)

Before:
[sub-agent refresh] -> [global/shared race or stale local write] -> [401 / overwrite / null return]

After:
[sub-agent refresh] -> [global per-profile lock] -> [CAS write to owning store + merged re-resolution] -> [usable credentials without clobbering newer auth state]

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? Yes
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • If any Yes, explain risk + mitigation: token persistence rules are stricter now. Cross-agent sharing only happens with positive identity evidence or exact credential equivalence; persisted writes are compare-and-set against the expected OAuth snapshot; reads under the global refresh lock are read-only; and refresh lock ids now use deterministic SHA-256 filenames that stay dot-safe and bounded in length.

Repro + Verification

Environment

  • OS: macOS 26.3.1 arm64
  • Runtime/container: Bun test wrapper in the repo workspace
  • Model/provider: auth-profile OAuth flows (openai-codex, anthropic)
  • Integration/channel (if any): N/A
  • Relevant config (redacted): main + sub-agent auth-profile stores, including shared and inherited OAuth profile cases

Steps

  1. Configure shared or inherited OAuth profiles across main and sub-agent auth stores.
  2. Trigger refresh while concurrently deleting/re-authing the profile or updating the main-store credential.
  3. Observe the stored credential and resolved auth result.

Expected

  • Refresh serializes once per profile.
  • Newer auth-mode changes win over stale refresh output.
  • Different-account agents do not exchange tokens on provider-only matches.
  • Inherited main-store profiles refresh and re-resolve successfully.

Actual (before fix)

  • Refresh could clobber a newer token / api_key entry or recreate a deleted profile.
  • Provider-only identity matches could copy one agent's OAuth tokens into another agent's store.
  • Ambiguous lock ids could collide or form unsafe path segments, and long encoded ids could fail with ENAMETOOLONG.
  • Inherited-profile refreshes could return null even after valid main-store updates.
  • A successful refresh could still fail the current request if CAS persistence of the new OAuth entry timed out or errored before the refreshed credential became visible in the auth store.

Evidence

  • Failing test/log before + passing after

Focused regressions now cover:

  • refresh_token_reused recovery against a fresher main-store credential
  • no stale overwrite after delete or token re-auth during refresh
  • no provider-only cross-agent write-back/adoption
  • inherited main-store profile refresh and null-retry re-resolution
  • current-request success when refreshed OAuth CAS persistence times out
  • distinct, bounded, and dot-safe refresh lock paths

Human Verification (required)

  • Verified scenarios: bun run test -- src/agents/auth-profiles.paths.test.ts src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts src/agents/auth-profiles/oauth.fallback-to-main-agent.test.ts src/agents/auth-profiles/oauth.test.ts (4 files, 40 tests passing), plus oxlint and oxfmt --check on the touched files.
  • Edge cases checked: delete during refresh, token re-auth during refresh, provider-only account mismatch, inherited-profile refresh/write-back, merged-store retry after null, auth-store CAS lock timeout after refresh, and lock-path collision/dot-segment safety.
  • What you did not verify: live multi-process refresh across separate OS processes; repo-wide pnpm test, pnpm check, and pnpm build were not rerun as part of this final update.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: shared-profile refresh still serializes peers behind a single profile lock.
    • Mitigation: the lock is per-profile rather than global, stale-lock handling remains in place, and the main benefit is preventing the refresh-token herd.
  • Risk: cross-agent credential sharing could still be dangerous if identity inference were too loose.
    • Mitigation: the current branch requires positive identity evidence or exact credential equivalence, and all persisted writes are compare-and-set guarded against the owning store snapshot.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Mar 21, 2026
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch 2 times, most recently from dab4b5f to 0a2f567 Compare March 21, 2026 11:49
@HeroSizy
HeroSizy marked this pull request as ready for review March 21, 2026 12:03
@HeroSizy
HeroSizy requested a review from a team as a code owner March 21, 2026 12:03
@greptile-apps

greptile-apps Bot commented Mar 21, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real production race condition: when 18+ agents share one OAuth profile, all of them could race to refresh the single-use refresh token simultaneously, causing refresh_token_reused 401 errors and expensive failovers. The fix serialises refresh across all agents by replacing the per-agent-dir file lock with a global per-profile lock at ~/.openclaw/locks/oauth-refresh/<profileId>, and adds a write-back so that only one agent performs the network round-trip while others adopt the result.

Key observations:

  • The global lock implementation is correct. withFileLock internally calls fs.mkdir({ recursive: true }), so the new locks/oauth-refresh/ directory is created automatically without extra setup code.
  • The re-read inside the lock (loadAuthProfileStoreForAgent bypassing the runtime snapshot cache) correctly prevents a double-refresh when multiple agents race to the lock boundary.
  • The isSameOAuthIdentity guard (provider + email when both present) is a net improvement over the existing adoptNewerMainOAuthCredential which only checked provider — cross-account overwrite protection is sound.
  • The refresh_token_reused catch block (lines 284–307 of oauth.ts) is the primary new recovery path for edge cases (stale locks, cross-machine refreshes). However, the test named "recovers from refresh_token_reused by adopting fresher main agent credentials" does not actually exercise this block — adoptNewerMainOAuthCredential adopts the fresh main-store credentials before performOAuthRefresh is even called, so the mock throw is never reached. That code path currently has no test coverage.
  • resolveOAuthRefreshLockPath replaces : with _, so profile IDs provider:name and provider_name would share a lock file — low practical risk but technically a collision.

Confidence Score: 4/5

  • Safe to merge with one targeted follow-up: the refresh_token_reused catch-block recovery path needs a test that actually exercises it.
  • The core locking mechanism is correct and well-structured. The write-back and identity-guard logic are sound. Two of the three new tests exercise their intended paths correctly. The one test that claims to cover refresh_token_reused recovery silently short-circuits through a pre-existing code path, leaving the new catch block uncovered — a meaningful gap for an explicitly advertised recovery mechanism, but not a blocker since the overall behavior (result correctness) is validated and the edge case only fires outside the lock boundary.
  • src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts — the first new test needs to be reworked to actually trigger the refresh_token_reused catch path.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
Line: 165-212

Comment:
**Test does not exercise the `refresh_token_reused` catch path**

This test never actually triggers the `refresh_token_reused` mock. Here is why:

1. `ensureAuthProfileStore(subAgentDir)` merges main + sub-agent stores; the sub-agent's expired creds override main in the merge result.
2. `resolveApiKeyForProfile` then calls `adoptNewerMainOAuthCredential`, which reads the main store directly and finds the fresh credentials. `oauthCred` becomes fresh.
3. Because `Date.now() < oauthCred.expires` is `true`, the function returns immediately — `refreshOAuthTokenWithLock` (and therefore `performOAuthRefresh`) is never called.

The mock is set up but silently ignored, and the result comes entirely from the pre-existing `adoptNewerMainOAuthCredential` code path that predates this PR. The new `refresh_token_reused` catch block (lines 284–307 of `oauth.ts`) has no test coverage.

To actually test the recovery path the test name describes, the main store would need to have **expired** creds at the point `adoptNewerMainOAuthCredential` runs but **fresh** creds by the time `performOAuthRefresh` throws (simulating a race outside the lock). One way to force this is to initialize the main store with expired creds before calling `resolveApiKeyForProfile`, then have the mock mutate the main store to contain fresh creds before throwing — or by mocking `loadAuthProfileStoreForAgent` to return different values at different call sites.

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/paths.ts
Line: 37-39

Comment:
**Lock-path collision between different profile IDs**

The sanitiser replaces every character outside `[a-zA-Z0-9_.-]` with `_`, so the colon separator is also replaced. This means `openai-codex:default` and the (unusual but valid) profile ID `openai-codex_default` both map to the same lock file `openai-codex_default`.

Two semantically distinct profiles would therefore share a lock and serialise against each other unnecessarily. In practice this is very unlikely (profile IDs rarely use underscores as separators), but a disambiguating separator — such as preserving the colon, or inserting a hash segment — would eliminate the ambiguity entirely:

```suggestion
  const safeId = profileId.replace(/[^a-zA-Z0-9_.-]/g, (c) => `%${c.charCodeAt(0).toString(16).padStart(2, "0")}`);
  return path.join(resolveStateDir(), "locks", "oauth-refresh", safeId);
```

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/constants.ts
Line: 23-32

Comment:
**`OAUTH_REFRESH_LOCK_OPTIONS` is identical to `AUTH_STORE_LOCK_OPTIONS`**

Both objects have the same `retries`, `factor`, `minTimeout`, `maxTimeout`, `randomize`, and `stale` values. Keeping them separate is fine if you anticipate tuning them independently (e.g., the global refresh lock may eventually need a longer `maxTimeout` or more retries than the per-store lock), but right now it introduces silent duplication. At minimum, a short comment explaining why they are separate would clarify intent for future maintainers.

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

Last reviewed commit: "fix: use global OAut..."

@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 0a2f567 to 29b0d6b Compare March 21, 2026 12:08
Comment thread src/agents/auth-profiles/paths.ts Resolved
Comment thread src/agents/auth-profiles/constants.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: 0a2f5674c2

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
Comment thread src/agents/auth-profiles/paths.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: 29b0d6b421

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/paths.ts Resolved
Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 29b0d6b to f8d6cc6 Compare March 22, 2026 07:33

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

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch 3 times, most recently from fbe9baf to 62689b9 Compare March 22, 2026 07:50

@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: 62689b958d

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
Comment thread src/agents/auth-profiles/constants.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch 2 times, most recently from 7c82fc5 to 3d0fc67 Compare March 22, 2026 08:03

@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: 3d0fc67651

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 3d0fc67 to 22495c9 Compare March 22, 2026 08:32

@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: 22495c9a64

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 22495c9 to a1f3564 Compare March 22, 2026 08:40

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

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from a1f3564 to 394f747 Compare March 22, 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: 394f747dc4

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 394f747 to a11018b Compare March 22, 2026 09:09

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

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from a11018b to 7f7ee3e Compare March 22, 2026 11:11
@openclaw-barnacle openclaw-barnacle Bot removed the gateway Gateway runtime label Mar 30, 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: 0c41c9782e

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@openclaw-barnacle openclaw-barnacle Bot added channel: tlon Channel integration: tlon app: web-ui App: web-ui gateway Gateway runtime labels Mar 30, 2026
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 4a3253d to c154ef0 Compare March 30, 2026 16:21
@openclaw-barnacle openclaw-barnacle Bot removed channel: tlon Channel integration: tlon app: web-ui App: web-ui gateway Gateway runtime labels Mar 30, 2026
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from c154ef0 to 44f4041 Compare March 30, 2026 16:38

@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: 44f4041fe4

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

expectedCurrent: cred,
newCred: mainCred,
});
if (adopted.current && Date.now() < adopted.current.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 Return fresh main OAuth creds even when local CAS write fails

This branch has already verified that mainCred is a fresh, share-safe OAuth credential, but it only returns success when writeCredentialToAgentStore succeeds. If the sub-agent auth store lock times out (lock_failed), the code falls through to performOAuthRefresh(cred) with stale tokens; for providers that rotate/single-use refresh tokens, that can raise refresh_token_reused and fail the request even though a valid main-store credential was already available. In that lock-contention scenario, the current request should still use the proven fresh main credential (while keeping write-back best-effort).

Useful? React with 👍 / 👎.

HeroSizy and others added 11 commits March 31, 2026 08:25
…law#26322)

Replace the per-agentDir file lock in refreshOAuthTokenWithLock with a global
per-profile lock at ~/.openclaw/locks/oauth-refresh/<profileId>. This serializes
token refresh across all agents sharing the same OAuth profile, preventing
refresh_token_reused 401 errors that cascade to expensive model fallback.

Changes:
- Global lock keyed by profileId (resolveOAuthRefreshLockPath)
- Fresh disk reads via loadAuthProfileStoreForAgent (bypasses runtime cache)
- Recovery on refresh_token_reused: re-read main store, adopt fresher creds
- Write-back refreshed creds to main store so peer agents benefit
- Identity guard (isSameOAuthIdentity) prevents cross-account overwrites
- All store writes go through updateAuthProfileStoreWithLock (file-lock safe)

Tests: 3 new tests covering recovery, no-recovery, and write-back scenarios.
Docs: Updated oauth.md, multi-agent.md, multi-agent-sandbox-tools.md.
- Add accountId to isSameOAuthIdentity for stronger identity matching
- Switch lock path sanitization to percent-encoding to prevent collisions
- Fix refresh_token_reused test to actually exercise the catch path
- Use isSameOAuthIdentity in adoptNewerMainOAuthCredential and error fallback
- Use loadAuthProfileStoreForAgent in updateAuthProfileStoreWithLock for fresh disk reads
- Add comment explaining separate OAUTH_REFRESH_LOCK_OPTIONS
…verwrites

- Replace loadProviderRuntime() (removed during rebase) with direct static import
- Scope access/refresh comparison in write condition to equal-expiry case only,
  preventing a stale refresh from clobbering newer re-auth credentials
@HeroSizy
HeroSizy force-pushed the fix/oauth-lock-racing-condition-squashed branch from 44f4041 to 6e37369 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: 6e37369565

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

maxTimeout: 10_000,
randomize: true,
},
stale: 30_000,

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 Raise OAuth refresh lock stale window for network refreshes

OAUTH_REFRESH_LOCK_OPTIONS keeps stale at 30 seconds even though this lock now wraps the full OAuth network refresh path. In withFileLock, a lock is considered stale once its createdAt age exceeds staleMs even if the owning PID is still alive (src/plugin-sdk/file-lock.ts), so a slow refresh (>30s) lets another process delete the live lock and run a second refresh concurrently. That reintroduces the same refresh_token_reused race this global lock is intended to prevent.

Useful? React with 👍 / 👎.

Comment on lines +374 to +378
const currentCred = writeResult.current;
if (
currentCred &&
canShareOAuthCredentialAcrossAgents(params.cred, currentCred) &&
Number.isFinite(currentCred.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 Return main credential when local adopt CAS cannot lock

adoptNewerMainOAuthCredential already has a fresher mainCred, but it only adopts when writeResult.current is populated. If the local auth store lock times out (updateAuthProfileStoreWithLock returns null and writeResult.status stays lock_failed), this branch falls through and returns null, so resolveApiKeyForProfile keeps using the older local OAuth credential. Under store-lock contention, that can cause avoidable auth failures or unnecessary refresh attempts even though a valid main-agent credential was already available for the current request.

Useful? React with 👍 / 👎.

@TinyTb

TinyTb commented Apr 13, 2026

Copy link
Copy Markdown
Contributor

Adding a data point to raise reviewer-attention priority: hitting #26322 on 2026.4.11 (commit 769908e) with 499 refresh_token_reused failures in a 24h window across multiple local agents sharing a single openclaw gateway. Commit 9d7459f is already applied on this build and is not sufficient for the adversarial case where OpenAI's theft-detection burns the entire descendant chain (more detail in my comment on #26322). This PR's global-per-profile-lock approach looks like exactly the pre-race prevention the symptom requires.

visionik added a commit that referenced this pull request Apr 17, 2026
Before: each agent held its own per-agentDir file lock during refresh, so N
agents sharing a single OAuth profile would all refresh in parallel when the
token expired. Because OpenAI rotates the refresh token on every successful
call, the losers of that race get HTTP 401 refresh_token_reused and cascade
to model fallback even though auth is actually valid. With 18 codex agents
this caused a token-expiry storm every ~12h.

After:
- refreshOAuthTokenWithLock now takes a cross-agent file lock at
  $STATE_DIR/locks/oauth-refresh/sha256-<hex64>. All agents sharing a
  profileId serialize on this single coordination point.
- An in-process Promise queue keyed on profileId chains same-PID callers
  so the re-entrant file lock cannot let two concurrent refreshes slip
  through within the same process.
- Inside the lock, an explicit main-store recheck adopts a freshly
  mirrored credential from the main agent instead of issuing a duplicate
  HTTP refresh. This collapses N serialized refreshes into 1 refresh +
  (N-1) adoptions.
- After a successful refresh from a secondary agent, the new credential
  is mirrored best-effort back into the main-agent store so peers adopt
  rather than race. Main-agent refreshes are unchanged.

Adapted from HeroSizy's approach in #51476; that PR's head was 7,755
commits behind origin/main and the surrounding auth-profiles files had
been split/refactored, so this is a port against the current shape of
oauth.ts/store.ts/path-resolve.ts, not a rebase.

Tests:
- oauth.concurrent-20-agents.test.ts: 20 distinct agentDirs sharing one
  profileId/accountId fire resolveApiKeyForProfile concurrently; exactly
  one refresh call is observed and all 20 receive the same fresh token.
- oauth.mirror-refresh.test.ts: sub-agent refresh mirrors into the main
  store; main-agent self-refresh is unchanged.
- oauth-lock-path.test.ts: unit + fuzz coverage for
  resolveOAuthRefreshLockPath (path-safety invariants, hashing, length
  bound, no separators/.. in basename, 2,700+ random adversarial inputs).

Co-authored-by: HeroSizy <[email protected]>
@HeroSizy

Copy link
Copy Markdown
Author

The PR has been ported and merged in #67876, will close this PR.

@HeroSizy HeroSizy closed this Apr 17, 2026
@visionik

Copy link
Copy Markdown
Contributor

Many thanks for your work on this @HeroSizy glad we could get it updated @ merged!

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation size: XL

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