Skip to content

fix(auth): invalidate stale runtime auth-profile snapshots when disk file is newer - #53367

Closed
artwalker wants to merge 6 commits into
openclaw:mainfrom
artwalker:fix/auth-profile-stale-cache-overwrite
Closed

artwalker wants to merge 6 commits into
openclaw:mainfrom
artwalker:fix/auth-profile-stale-cache-overwrite

Conversation

@artwalker

Copy link
Copy Markdown
Contributor

Summary

  • Problem: Gateway overwrites fresh OAuth tokens with stale cached state on startup, burning single-use refresh tokens and blocking all Codex requests
  • Why it matters: 100% reproducible regression that completely breaks openai-codex provider usage on v2026.3.22+
  • What changed: Added mtime-based staleness detection to resolveRuntimeAuthProfileStore() — before returning a cached snapshot, compare disk file mtime against snapshot load timestamp; invalidate on stale
  • What did NOT change: Runtime snapshot caching still works for the normal hot-path (gateway running, no external token updates); loadedAuthStoreCache mtime logic unchanged

Change Type

  • Bug fix
  • Security hardening

Scope

  • Auth / tokens

Linked Issue

User-visible / Behavior Changes

OAuth tokens written by openclaw models auth login while gateway is stopped are no longer overwritten on startup.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? Yes — stale cached OAuth tokens are invalidated when the on-disk store is newer, preventing accidental credential rollback
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Root Cause

resolveRuntimeAuthProfileStore() returns the in-memory snapshot populated by replaceRuntimeAuthProfileStoreSnapshots() on gateway startup, without checking if the on-disk file was modified since. The existing loadedAuthStoreCache has mtime-based invalidation, but runtimeAuthStoreSnapshots (a separate cache layer) does not — and it takes priority.

When openclaw models auth login writes a fresh token to auth-profiles.json while the gateway is stopped, the next gateway startup loads the old snapshot, and any subsequent write-back (usage stats, profile sync) overwrites the fresh token.

Repro + Verification

Environment

  • OS: WSL2 Ubuntu
  • Provider: openai-codex (PKCE OAuth)

Steps

  1. Stop gateway
  2. Run openclaw models auth login --provider openai-codex (fresh token written)
  3. Start gateway
  4. Check auth-profiles.json — previously: old token restored; now: fresh token preserved

Expected

Gateway uses the fresh token without overwriting it.

Actual (before fix)

Gateway writes stale January token back within 30 seconds of startup.

Evidence

  • Root cause analysis with exact file paths and line numbers
  • npm run build passes (0 PARSE_ERROR)
  • Integration test with token file modification (manual verification pending)

Human Verification (required)

  • Verified: readAuthStoreMtimeMs() correctly reads file mtime via fs.statSync
  • Verified: staleness check validates both main and agent-specific store paths
  • Verified: clearRuntimeAuthProfileStoreSnapshots() resets the timestamp
  • Verified: IIFE for requestedKey mtime is short-circuit safe (no eval when keys match)
  • Not verified: live OAuth token flow (requires Codex credentials)

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

Failure Recovery

  • Revert the single commit to restore previous behavior
  • Watch for: OAuth token overwrite errors returning after revert

Risks and Mitigations

  • Risk: Additional statSync call on every resolveRuntimeAuthProfileStore() invocation
  • Mitigation: statSync is sub-millisecond (kernel dentry cache), and this function is not called in tight loops. The performance cost is negligible compared to the security benefit.

🤖 Generated with Claude Code

@artwalker
artwalker requested a review from a team as a code owner March 24, 2026 03:46
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 24, 2026
@greptile-apps

greptile-apps Bot commented Mar 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds mtime-based staleness detection to resolveRuntimeAuthProfileStore() in src/agents/auth-profiles/store.ts to fix a 100%-reproducible regression where a gateway startup would overwrite fresh OAuth tokens (written by openclaw models auth login while the gateway was stopped) with the stale in-memory runtime snapshot.

What changed:

  • Introduces runtimeSnapshotsLoadedAtMs (module-level let) to record when replaceRuntimeAuthProfileStoreSnapshots() last populated the runtime map.
  • On every resolveRuntimeAuthProfileStore() call, compares the on-disk mtimeMs of both the main and agent-specific auth-profile files against runtimeSnapshotsLoadedAtMs. If either is newer, the runtime snapshot (and loadedAuthStoreCache) is cleared and null is returned so callers fall through to a fresh disk read.
  • clearRuntimeAuthProfileStoreSnapshots() now also resets runtimeSnapshotsLoadedAtMs to 0.

Issues found:

  • The IIFE used for the agent-specific staleness check (isRequestedStale) is functional but unusual — a plain early-evaluation assignment would be cleaner and equally efficient.
  • loadedAuthStoreCache is cleared together with runtimeAuthStoreSnapshots on staleness, even though loadedAuthStoreCache is already mtime-aware and would self-invalidate; this risks evicting a valid, freshly-populated cache entry and causing an extra disk read.
  • runtimeSnapshotsLoadedAtMs is stamped at the time the in-memory map is written, not before the underlying disk reads that produce entries. A write that lands between the load and the stamp would not be detected as stale. Recording the timestamp at the call site before the disk reads would close this window.

The primary regression scenario (login while gateway is stopped) is well-covered by this fix; the race window is narrow enough that it would not affect the described repro in practice.

Confidence Score: 4/5

  • Safe to merge with minor follow-up improvements — the fix correctly addresses the reported regression for the primary use-case.
  • The staleness detection logic is sound and directly closes the described regression (fresh OAuth tokens overwritten on startup). The three issues flagged are all P2: an IIFE style nit, an overly aggressive loadedAuthStoreCache.clear(), and a narrow timestamp-ordering race that would not affect the primary repro scenario. None of these is a blocker.
  • src/agents/auth-profiles/store.ts — specifically the timestamp capture ordering in replaceRuntimeAuthProfileStoreSnapshots and the loadedAuthStoreCache.clear() inside the staleness branch.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/store.ts
Line: 57-62

Comment:
**IIFE adds unnecessary indirection**

The IIFE used for short-circuit evaluation on the agent-specific mtime check works correctly, but it's an unusual pattern here. A plain early assignment achieves the same result with less cognitive overhead:

```suggestion
    const requestedMtime = requestedKey !== mainKey ? readAuthStoreMtimeMs(requestedKey) : null;
    const isRequestedStale = requestedMtime !== null && requestedMtime > runtimeSnapshotsLoadedAtMs;
```

This avoids the self-calling arrow function and keeps both staleness checks visually parallel.

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/store.ts
Line: 63-68

Comment:
**Aggressive `loadedAuthStoreCache` eviction may be unnecessary**

When a stale runtime snapshot is detected, the code clears `loadedAuthStoreCache` as well. However, `loadedAuthStoreCache` is already mtime-aware — `readCachedAuthProfileStore` validates the cached entry's `mtimeMs` against the current file mtime, so it would self-invalidate naturally when the caller falls through to it.

Clearing it here can evict a *valid* `loadedAuthStoreCache` entry that was already populated with the newer file's mtime (e.g., if another code path loaded the updated file just before this staleness check ran), forcing a redundant disk read.

Consider only clearing `runtimeAuthStoreSnapshots` and `runtimeSnapshotsLoadedAtMs`:

```suggestion
      runtimeAuthStoreSnapshots.clear();
      runtimeSnapshotsLoadedAtMs = 0;
      return null;
```

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/store.ts
Line: 98-101

Comment:
**Timestamp set after load creates a narrow staleness blind spot**

`runtimeSnapshotsLoadedAtMs` is stamped at the moment the in-memory map is written, but the actual disk reads that produced `entries` happen *before* `replaceRuntimeAuthProfileStoreSnapshots` is called. This means there is a window where:

1. Auth store is loaded from disk at time **T₁**  
2. `openclaw models auth login` writes a fresh token at time **T₂** (T₁ < T₂)  
3. `replaceRuntimeAuthProfileStoreSnapshots` runs at **T₃** (T₃ > T₂) and sets `runtimeSnapshotsLoadedAtMs = T₃`  
4. Staleness check sees `disk_mtime (T₂) < runtimeSnapshotsLoadedAtMs (T₃)` → **stale write not detected**

The staleness check was designed to catch exactly this scenario, but the ordering means it misses any write that lands between the disk load and the map population.

A robust fix would capture the timestamp *before* the disk reads and thread it into this function:

```ts
// At call site, before loading entries from disk:
const snapshotTimestamp = Date.now();
// ... load entries ...
replaceRuntimeAuthProfileStoreSnapshots(entries, snapshotTimestamp);
```

```ts
export function replaceRuntimeAuthProfileStoreSnapshots(
  entries: Array<{ agentDir?: string; store: AuthProfileStore }>,
  loadedAtMs = Date.now(),
): void {
  runtimeAuthStoreSnapshots.clear();
  runtimeSnapshotsLoadedAtMs = loadedAtMs;
  ...
}
```

This is admittedly a narrow race window and would rarely trigger in the described repro scenario (gateway stopped → login → start), but it is exploitable in a running gateway if the startup sequence is slow.

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

Reviews (1): Last reviewed commit: "fix(auth): invalidate stale runtime auth..." | Re-trigger Greptile

Comment thread src/agents/auth-profiles/store.ts Resolved
Comment thread src/agents/auth-profiles/store.ts Resolved
Comment thread src/agents/auth-profiles/store.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: c9ded4af82

ℹ️ 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/store.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: f80fd244fb

ℹ️ 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/store.ts Resolved
@mediocreasian

Copy link
Copy Markdown

Can someone review this Pull Request? Seems like a fix for users who are facing the bug #53317

@artwalker

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main.

@artwalker
artwalker force-pushed the fix/auth-profile-stale-cache-overwrite branch from f80fd24 to fce4c60 Compare March 31, 2026 09:21

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

ℹ️ 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/store.ts Resolved
@prtags

prtags Bot commented Apr 23, 2026

Copy link
Copy Markdown

Related work from PRtags group apt-oryx-nhva

Title: auth: stale runtime snapshots overwrite OAuth tokens

Number Title
#53317 Title unavailable
#53367* fix(auth): invalidate stale runtime auth-profile snapshots when disk file is newer
#53754 fix/53317-gateway-overwrites-oauth-token
#68866 fix(auth): invalidate stale runtime auth snapshots when auth files change

* This PR

@artwalker
artwalker force-pushed the fix/auth-profile-stale-cache-overwrite branch from fdc78a7 to 9d3c701 Compare April 24, 2026 01:44

@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: 9d3c701f67

ℹ️ 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/secrets/runtime.ts Resolved
@artwalker
artwalker force-pushed the fix/auth-profile-stale-cache-overwrite branch from 9d3c701 to 71086a3 Compare April 24, 2026 03:38
@artwalker
artwalker force-pushed the fix/auth-profile-stale-cache-overwrite branch from 44173b4 to 25a370f Compare April 24, 2026 03:45

@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: 25a370f596

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

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

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

@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Current main already fixes the stale OAuth overwrite bug through auth-store reload and recovery logic, and the shipped v2026.4.23 release contains that implementation plus regression coverage. This PR's runtime-snapshot invalidation approach is no longer needed to address the reported behavior.

What I checked:

  • Release reloads auth store before refresh: In v2026.4.23, the locked OAuth refresh path reloads auth-profiles.json from disk and returns an already-usable persisted OAuth credential without spending a refresh token. (src/agents/auth-profiles/oauth-manager.ts:347, a9797214338b)
  • Release recovers from refresh_token_reused: In v2026.4.23, the failure path reloads the auth store from disk after refresh_token_reused and adopts fresher stored OAuth credentials instead of continuing with stale in-memory state. (src/agents/auth-profiles/oauth-manager.ts:542, a9797214338b)
  • Release prevents stale snapshot write-back under lock: Locked auth-store writers now reload from disk instead of reusing runtime snapshots, explicitly to avoid overwriting fresher CLI/config-auth writes with stale in-memory auth state. (src/agents/auth-profiles/store.ts:136, a9797214338b)
  • Regression test covers stale snapshot overwrite: The shipped test suite includes a regression asserting markAuthProfileFailure does not overwrite fresher on-disk credentials with a stale runtime snapshot. (src/agents/auth-profiles.markauthprofilefailure.test.ts:76, a9797214338b)
  • Regression test covers refreshed credential adoption: The shipped test suite also asserts that refresh_token_reused falls back to fresher stored openai-codex credentials and returns the reloaded access token. (src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts:446, a9797214338b)
  • Linked issue already closed as implemented: Maintainer steipete closed linked issue #53317 on 2026-04-25 after Codex review, citing the same auth reload/recovery paths and regression tests as sufficient current-main proof. (8f64cd3e4d83)

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

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

@steipete steipete 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 size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Gateway overwrites fresh OAuth token with stale cached state on startup (v2026.3.22, openai-codex)

3 participants