Skip to content

fix(auth): invalidate stale runtime auth snapshots when auth files change - #68866

Closed
alithnar-bot wants to merge 1 commit into
openclaw:mainfrom
alithnar-bot:fix/codex-auth-snapshot-invalidation
Closed

alithnar-bot wants to merge 1 commit into
openclaw:mainfrom
alithnar-bot:fix/codex-auth-snapshot-invalidation

Conversation

@alithnar-bot

Copy link
Copy Markdown

Summary

  • invalidate runtime auth profile snapshots when auth-profiles.json changes on disk
  • invalidate runtime auth profile snapshots when auth-state.json changes on disk
  • add regression coverage for both auth-store and auth-state mtime invalidation

Problem

A long-lived gateway process can keep serving a stale in-memory runtime auth snapshot even after a fresh OAuth login rotates credentials on disk.

In the Codex OAuth path, that leaves the running process reusing an already-rotated refresh token until the gateway restarts, which can surface as repeated refresh failures like:

  • 401
  • refresh_token_reused
  • Your refresh token has already been used to generate a new access token. Please try signing in again.

Root cause

src/agents/auth-profiles/runtime-snapshots.ts cached runtime auth stores by agent path, but it did not verify whether the underlying auth-profiles.json or auth-state.json files had changed since the snapshot was created.

That meant external disk updates, including browser re-login flows and other auth-store writes, could leave a stale runtime snapshot active indefinitely inside the current gateway process.

Fix

This PR fingerprints runtime snapshots with the current mtimes of:

  • auth-profiles.json
  • auth-state.json

When either file changes, the snapshot is evicted before reuse, so the next auth-store load comes from fresh persisted state instead of stale in-memory credentials.

Tests

  • npx --yes [email protected] exec vitest run src/agents/auth-profiles.store-cache.test.ts src/agents/auth-profiles.store.save.test.ts
  • npx --yes [email protected] exec vitest run src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts

@alithnar-bot
alithnar-bot requested a review from a team as a code owner April 19, 2026 07:34
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Apr 19, 2026
@greptile-apps

greptile-apps Bot commented Apr 19, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a long-lived gateway process serving stale in-memory auth snapshots after a browser OAuth re-login rotates credentials on disk. It fingerprints each RuntimeAuthProfileStoreSnapshot with the current mtimes of both auth-profiles.json and auth-state.json, evicting the cached entry on any mtime mismatch before the next read.

The logic correctly handles missing files (both sides returning null stays valid), filesystem errors (caught and coerced to null), and the cache key correctly ties to the auth-store path to uniquely identify each agent dir. Two new regression tests cover both file paths, using fs.utimesSync to force a deterministic mtime bump.

Confidence Score: 5/5

Safe to merge — the fix is minimal, well-targeted, and covered by new regression tests.

No P0 or P1 findings. The sole comment is a P2 naming suggestion for a private helper. The mtime-invalidation logic is correct, error handling is sound, and the tests exercise both invalidation paths with a reliable mtime bump strategy.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/runtime-snapshots.ts
Line: 21-27

Comment:
**Misleading helper name**

`readAuthStoreMtimeMs` is used for both `auth-profiles.json` (auth store) and `auth-state.json` (auth state) paths, but the name implies it's specific to the auth store. A more generic name like `readFileMtimeMs` or `readMtimeMs` would prevent confusion for future readers.

```suggestion
function readFileMtimeMs(pathname: string): number | null {
  try {
    return fs.statSync(pathname).mtimeMs;
  } catch {
    return null;
  }
}
```

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 on lines +21 to +27
function readAuthStoreMtimeMs(pathname: string): number | null {
try {
return fs.statSync(pathname).mtimeMs;
} catch {
return null;
}
}

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 Misleading helper name

readAuthStoreMtimeMs is used for both auth-profiles.json (auth store) and auth-state.json (auth state) paths, but the name implies it's specific to the auth store. A more generic name like readFileMtimeMs or readMtimeMs would prevent confusion for future readers.

Suggested change
function readAuthStoreMtimeMs(pathname: string): number | null {
try {
return fs.statSync(pathname).mtimeMs;
} catch {
return null;
}
}
function readFileMtimeMs(pathname: string): number | null {
try {
return fs.statSync(pathname).mtimeMs;
} catch {
return null;
}
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/auth-profiles/runtime-snapshots.ts
Line: 21-27

Comment:
**Misleading helper name**

`readAuthStoreMtimeMs` is used for both `auth-profiles.json` (auth store) and `auth-state.json` (auth state) paths, but the name implies it's specific to the auth store. A more generic name like `readFileMtimeMs` or `readMtimeMs` would prevent confusion for future readers.

```suggestion
function readFileMtimeMs(pathname: string): number | null {
  try {
    return fs.statSync(pathname).mtimeMs;
  } catch {
    return null;
  }
}
```

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@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: 2f8dbabe26

ℹ️ 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 64 to +65
export function hasRuntimeAuthProfileStoreSnapshot(agentDir?: string): boolean {
return runtimeAuthStoreSnapshots.has(resolveRuntimeStoreKey(agentDir));
return Boolean(getFreshRuntimeAuthProfileStoreSnapshot(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.

P1 Badge Preserve runtime snapshots when persisting updated stores

hasRuntimeAuthProfileStoreSnapshot now calls the freshness check, so it returns false (and evicts the entry) as soon as auth-profiles.json/auth-state.json mtimes change. In saveAuthProfileStore (src/agents/auth-profiles/store.ts), the files are written before this check, so a previously-present runtime snapshot is treated as stale and skipped instead of being refreshed via setRuntimeAuthProfileStoreSnapshot. That means runtime-only in-memory auth data (for example external OAuth overlays or pre-resolved secret refs) can disappear after a normal save path and stay missing until a full runtime snapshot rebuild.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Apr 21, 2026
@alithnar-bot
alithnar-bot force-pushed the fix/codex-auth-snapshot-invalidation branch from 0cc450f to 591cd59 Compare April 21, 2026 18:29
@openclaw-barnacle openclaw-barnacle Bot removed the app: web-ui App: web-ui label Apr 21, 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: 591cd59b20

ℹ️ 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 +50 to +52
if (snapshot.authMtimeMs !== authMtimeMs || snapshot.stateMtimeMs !== stateMtimeMs) {
runtimeAuthStoreSnapshots.delete(key);
return undefined;

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 Reload subagent store when runtime snapshot goes stale

When getFreshRuntimeAuthProfileStoreSnapshot evicts and returns undefined on mtime drift, subagent calls now look like “no requested snapshot.” In that case resolveRuntimeAuthProfileStore (src/agents/auth-profiles/store.ts) falls back to the main-agent runtime snapshot and returns early, so ensureAuthProfileStore(subagentDir) can skip reloading the changed subagent auth-profiles.json/auth-state.json from disk. This leaves subagent auth updates unapplied (and can incorrectly use main-agent credentials) whenever a main snapshot is present.

Useful? React with 👍 / 👎.

@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

@clawsweeper

clawsweeper Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex automated review.

Current main, shipped in v2026.4.24, already fixes the stale Codex OAuth credential failure through safer disk reloads in locked auth writes and OAuth refresh recovery. The unmerged PR's runtime-snapshot mtime approach is now stale and had review comments flagging credential/snapshot regressions, so it should not be merged as the fix.

Best possible solution:

Close this PR and keep the shipped v2026.4.24 implementation. If maintainers still want broader runtime auth snapshot mtime invalidation later, it should be designed as a new change with tests for subagent fallback, save-path refresh, auth-state changes, and runtime-only secret overlays.

What I checked:

  • Locked auth writes reload disk state: updateAuthProfileStoreWithLock explicitly reloads from disk inside the file lock before mutating/saving, preventing live gateway usage/cooldown writes from overwriting fresher CLI or login credentials with stale in-memory auth state. (src/agents/auth-profiles/store.ts:127, cbcfdf62c729)
  • OAuth refresh uses persisted store: The refresh path loads loadAuthProfileStoreForSecretsRuntime under the refresh/auth locks, so refresh decisions use fresh persisted auth rather than the active runtime snapshot. (src/agents/auth-profiles/oauth-manager.ts:324, cbcfdf62c729)
  • refresh_token_reused recovery implemented: On refresh failure, current code reloads the store, adopts a usable refreshed credential, and retries once when refresh_token_reused only rotated the stored refresh token. (src/agents/auth-profiles/oauth-manager.ts:520, cbcfdf62c729)
  • Regression coverage exists: Tests cover adopting fresher stored OpenAI Codex credentials after refresh_token_reused and retrying after the stored refresh token changes. (src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts:417, cbcfdf62c729)
  • Runtime snapshot save path protected: Current tests assert that saveAuthProfileStore refreshes an existing runtime snapshot when OAuth tokens rotate, covering the save-path regression called out in PR review. (src/agents/auth-profiles.store.save.test.ts:75, f0b327cf686e)
  • Release evidence: The v2026.4.24 changelog records the shipped OpenAI Codex OAuth fix: reload fresh on-disk credentials in the locked refresh path and retry after refresh_token_reused, preventing relogin/restart recovery from staying stuck on stale cached auth state. (CHANGELOG.md:1121, cbcfdf62c729)

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

Codex Review notes: model gpt-5.5, reasoning high; reviewed against f0b327cf686e; fix evidence: release v2026.4.24, commit cbcfdf62c729.

@clawsweeper clawsweeper Bot closed this Apr 27, 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.

1 participant