Skip to content

fix: sync runtimeAuthStoreSnapshots on save to prevent stale OAuth tokens (#55389) - #55465

Closed
factnest365-ops wants to merge 11 commits into
openclaw:mainfrom
factnest365-ops:fix/oauth-refresh-stale-snapshot
Closed

factnest365-ops wants to merge 11 commits into
openclaw:mainfrom
factnest365-ops:fix/oauth-refresh-stale-snapshot

Conversation

@factnest365-ops

Copy link
Copy Markdown
Contributor

Summary

Fixes OAuth token refresh failure that occurs after the second refresh attempt (~16 hours after gateway startup).

Root Cause

saveAuthProfileStore() writes refreshed OAuth tokens to disk and the file cache, but never updates runtimeAuthStoreSnapshots. Since ensureAuthProfileStore() checks the runtime snapshot first (and returns a clone if it exists), all subsequent API calls read stale tokens containing the consumed (rotated) refresh token.

Token rotation lifecycle (broken):

  1. Gateway starts → loads auth store into runtimeAuthStoreSnapshots (refresh token = R1)
  2. Access token expires → refresh fires
  3. Refresh succeeds → provider returns new tokens with rotated refresh token R2
  4. saveAuthProfileStore writes R2 to disk and file cache ✅
  5. Runtime snapshot still holds R1 (consumed/invalidated by provider) ❌
  6. Next API call → ensureAuthProfileStore → returns snapshot clone with R1
  7. Refresh attempt with R1 → invalid_grant ❌

Fix

After writing to disk and cache, update runtimeAuthStoreSnapshots if a snapshot entry exists for the agent directory. Uses cloneAuthProfileStore(store) (the full unsanitized store) rather than cloneAuthProfileStore(payload) (the sanitized disk version) to preserve credentials needed for API calls.

const runtimeKey = resolveRuntimeStoreKey(agentDir);
if (runtimeAuthStoreSnapshots.has(runtimeKey)) {
  runtimeAuthStoreSnapshots.set(runtimeKey, cloneAuthProfileStore(store));
}

Impact

All OAuth-authenticated providers (Anthropic, OpenAI Codex, etc.) stop working ~16 hours after gateway startup. This fix ensures the in-memory snapshot stays in sync with disk after every token refresh.

Fixes #55389

@factnest365-ops
factnest365-ops requested a review from a team as a code owner March 27, 2026 01:49
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Mar 27, 2026
@greptile-apps

greptile-apps Bot commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a well-described OAuth token staleness bug where saveAuthProfileStore() was writing refreshed tokens to disk and the file cache but leaving runtimeAuthStoreSnapshots unchanged. Because ensureAuthProfileStore() short-circuits on an existing runtime snapshot, every subsequent API call after the first token rotation received the original (now invalidated) refresh token, causing invalid_grant failures roughly 16 hours after gateway startup.\n\nThe fix is minimal and correct:\n- Adds a guarded update to runtimeAuthStoreSnapshots after the file and cache writes, using cloneAuthProfileStore(store) (the unsanitized in-memory version) rather than cloneAuthProfileStore(payload) (the disk-sanitized version). This correctly preserves raw key/token values for keyRef/tokenRef credentials that are stripped from the on-disk payload.\n- The conditional runtimeAuthStoreSnapshots.has(runtimeKey) guard is appropriate — it avoids injecting new snapshot entries for stores that were never registered, maintaining the existing initialization contract from replaceRuntimeAuthProfileStoreSnapshots.\n- The change integrates cleanly with updateAuthProfileStoreWithLock, which already calls saveAuthProfileStore after reloading from disk, so the lock-safe writer path will also keep the snapshot fresh after the fix.

Confidence Score: 5/5

Safe to merge — the fix is minimal, targeted, and directly addresses the documented root cause with no regressions.

Single-file change with a clean, guarded update that only affects stores already registered in the runtime snapshot map. The choice of store over payload is correct and future-proof. No new code paths are introduced, and the guard prevents unintended snapshot creation.

No files require special attention.

Important Files Changed

Filename Overview
src/agents/auth-profiles/store.ts Adds runtime snapshot sync in saveAuthProfileStore() to prevent stale OAuth tokens after token rotation; uses the unsanitized store rather than the disk payload, which is the correct choice to preserve in-memory credentials.

Reviews (1): Last reviewed commit: "fix: sync runtimeAuthStoreSnapshots on s..." | 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: 48cd3c6059

ℹ️ 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 +592 to +593
if (runtimeAuthStoreSnapshots.has(runtimeKey)) {
runtimeAuthStoreSnapshots.set(runtimeKey, cloneAuthProfileStore(store));

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 resolved secrets when syncing runtime auth snapshots

saveAuthProfileStore now overwrites runtimeAuthStoreSnapshots with the passed store, but lock-based writers call it with a store reloaded from disk (updateAuthProfileStoreWithLock), and disk persistence intentionally strips plaintext key/token when keyRef/tokenRef is present. In an active secrets runtime snapshot, a normal usage/cooldown write can therefore replace resolved in-memory credentials with unresolved refs, so later ensureAuthProfileStore() calls no longer return the frozen resolved value and must re-resolve (or fail if file/exec/env refs are unavailable), which is a runtime regression introduced by this sync path.

Useful? React with 👍 / 👎.

Comment on lines +592 to +593
if (runtimeAuthStoreSnapshots.has(runtimeKey)) {
runtimeAuthStoreSnapshots.set(runtimeKey, cloneAuthProfileStore(store));

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 Sync active snapshot state when mutating runtime auth map

This update only mutates runtimeAuthStoreSnapshots, but getActiveSecretsRuntimeSnapshot() still returns stale activeSnapshot.authStores; on gateway hot-reload failure, src/gateway/server.impl.ts restores previousSnapshot via activateSecretsRuntimeSnapshot(previousSnapshot), which repopulates the runtime auth map from those stale auth stores and can roll back freshly refreshed OAuth tokens in memory. That rollback path is now inconsistent specifically because this commit introduced one-sided snapshot mutation.

Useful? React with 👍 / 👎.

Bhavya Swami and others added 11 commits March 27, 2026 15:30
- Add owner-only tools section to tools/index.md (gateway, cron, nodes)
- Fix /help/faq#where-does-openclaw-store-its-data -> #where-things-live-on-disk
- Fix exec-approvals channel links (headings no longer exist)
- Fix docker sandbox anchor (heading renamed)

Ref: openclaw#50828
Fix Vercel/Venice order in docs/providers/index.md
Vercel should come before Venice alphabetically

Ref: openclaw#50826
…kens

saveAuthProfileStore() writes refreshed tokens to disk and file cache
but never updates runtimeAuthStoreSnapshots. Since ensureAuthProfileStore()
checks the runtime snapshot first, subsequent API calls read stale tokens
containing the consumed (rotated) refresh token.

After the first OAuth refresh succeeds (which rotates the refresh token
server-side), the second refresh always fails with invalid_grant because
the runtime snapshot still holds the consumed refresh token.

The fix clones the full store (not the sanitized disk payload) into
runtimeAuthStoreSnapshots when a snapshot entry exists, keeping the
in-memory cache in sync with disk after every save.

Fixes openclaw#55389
@factnest365-ops
factnest365-ops force-pushed the fix/oauth-refresh-stale-snapshot branch from 48cd3c6 to 9551663 Compare March 30, 2026 12:40
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: bluebubbles Channel integration: bluebubbles channel: googlechat Channel integration: googlechat channel: msteams Channel integration: msteams channel: zalouser Channel integration: zalouser gateway Gateway runtime commands Command implementations docker Docker and sandbox tooling size: XL and removed size: XS labels 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: 955166325f

ℹ️ 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 +54 to +57
...resolveManifestProviderSetupFlowContributions({
...params,
scope: "text-inference",
}).map((contribution) => contribution.option.value),

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 Avoid loading provider plugins when building auth-choice help

formatAuthChoiceChoicesForCli now calls resolveManifestProviderSetupFlowContributions, which in turn resolves provider docs via runtime provider loading (resolvePluginProviders) before returning simple choice ids. This path is used to build static CLI help text at startup (for onboard --auth-choice), so every CLI run now does plugin loading work and can surface plugin-load side effects/errors even when onboarding is not being used. Please keep this helper on a manifest-only path (or skip docs resolution here) so help generation stays lightweight and side-effect free.

Useful? React with 👍 / 👎.

@steipete

Copy link
Copy Markdown
Contributor

Closing this as implemented after Codex review.

Close. Current main already implements the runtime auth snapshot sync this PR proposes, and the shipped v2026.4.22 release contains the same logic plus regression coverage.

What I checked:

  • Current main updates runtime auth snapshots on save: saveAuthProfileStore() clones the in-memory store, writes the cache, and refreshes the runtime snapshot when one already exists, which is the core fix described in the PR. (src/agents/auth-profiles/store.ts:375, d3d9b5738f83)
  • Read path still prefers runtime snapshot: ensureAuthProfileStoreWithoutExternalProfiles() returns the runtime snapshot first, so keeping that snapshot fresh is sufficient to prevent stale rotated refresh tokens from being reused. (src/agents/auth-profiles/store.ts:298, d3d9b5738f83)
  • Regression test covers rotated OAuth tokens: There is a focused test asserting that after saveAuthProfileStore() writes rotated OAuth credentials, ensureAuthProfileStore() returns the updated access and refresh tokens from the runtime snapshot. (src/agents/auth-profiles.store.save.test.ts:75, d3d9b5738f83)
  • Fix is present in shipped release: The released v2026.4.22 tag contains the same saveAuthProfileStore() runtime-snapshot update logic, so this is not just on unreleased main. (src/agents/auth-profiles/store.ts:375, 00bd2cf7a376)

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

Review notes: reviewed against d3d9b5738f83; fix evidence: release v2026.4.22, commit 00bd2cf7a376.

@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 channel: bluebubbles Channel integration: bluebubbles channel: googlechat Channel integration: googlechat channel: msteams Channel integration: msteams channel: zalouser Channel integration: zalouser commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

saveAuthProfileStore doesn't update runtimeAuthStoreSnapshots — OAuth refresh dies after first token rotation

3 participants