Skip to content

fix(auth): keep OAuth sign-ins through safe refresh failures - #178646

Merged
fuller-stack-dev merged 21 commits into
openclaw:mainfrom
Stronggenetics:fix/oauth-refresh-transient-timeout
Oct 22, 2026
Merged

fuller-stack-dev merged 21 commits into
openclaw:mainfrom
Stronggenetics:fix/oauth-refresh-transient-timeout

Conversation

@Stronggenetics

@Stronggenetics Stronggenetics commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Related: #89278 (OAuth timeout symptoms, not a claim to fix its older Codex timeout path).

Builds on @Stronggenetics's original transient-refresh fix; maintainer corrections replace status-only retry admission with provider-owned evidence.

What Problem This Solves

A temporary OAuth refresh failure could permanently fence an OpenClaw-owned sign-in and force re-login, and concurrent callers could each repeat the same failing refresh. On main, an xAI token-endpoint 429/5xx was terminal.

User Impact

Fewer forced re-logins for xAI, Google and Microsoft integrations and for failures before dispatch; no replay of possibly consumed rotating grants elsewhere. No config or database schema change; stored OAuth credential JSON records gain optional refresh-claim fields.

Why This Change Was Made

Refresh routes report a typed, credential-free outcome (src/shared/oauth-refresh-outcome.ts, additive exports in openclaw/plugin-sdk/provider-oauth-runtime). The credential owner restores the exact claimed credential for a later retry only with positive evidence:

  • the request was never dispatched (all owners);
  • the provider documents the grant as reusable — Google (Meet, Vertex authorized_user ADC) and Microsoft (Teams delegated): transport loss, an unreadable or HTML response, and 429/5xx keep the sign-in;
  • xAI (product decision on this PR): a 429/5xx keeps the sign-in unless the OAuth error is final (invalid_grant, invalid_client, invalid_request, access_denied, …); a verified Cloudflare cf-mitigated: challenge is retried up to 3 times.

Other owners (OpenAI, Anthropic, GitHub, X, MCP, Chutes, MiniMax, Radius, Twitch) rotate grants or don't document reuse, so a lost response or post-dispatch 429/5xx stays fenced and asks for reconnect; definitive rejections stay terminal everywhere. Twitch documents that one refresh token can back many access tokens, but not reuse after a lost rotation, so a Twitch 429/5xx or lost response still requires reauthorizing the bot. Queued callers share one settled failure instead of replaying it. Rotated results are persisted before use (X, GitHub, Twitch), and Vertex never rewrites gcloud's ADC file.

owner-accepted-provider-retry is an SDK evidence kind for an explicit provider-owner decision; the classifier cannot verify it, and docs say so.

Excluded: Gemini CLI and other tool-owned CLI homes, setup tokens, static API keys.

Evidence

Exact candidate tree f354ff361c812e14e3289b5a6959aa5509e23727 (correction integrated with main d175030f056), verified in isolated, secretless AWS Crabbox guests with synthetic credentials only:

  • Regression tests for each correction (several first shown failing on the prior head): transient xAI 429/5xx (structured and HTML), Google Meet and Microsoft Teams HTML/unreadable 5xx, queued-caller sharing, merged personal-owner disconnect, authority capture before claim persistence.

  • Focused suites (102 files, 1,737 tests; one inherited main failure in doctor-lint.state-isolation from fix: updates tolerate missing legacy OAuth directories #180174's advisory OAuth-dir change, untouched by this PR) across the auth-profile manager/queue/classifier, GitHub personal OAuth lifecycle/publication, SDK AuthStorage boundary (139 cases), Vertex, Meet, Teams, Twitch, xAI, X, MiniMax and auth-controller consumers, plus every MCP OAuth consumer (Gateway mcp.authLogin forced effects, CLI login, doctor lint state isolation); import-cycle, extension-boundary and line-cap guards; core and extension types and test types, lint, format, docs, assertion-safety and test-mock-export ratchets, git diff --check, and pnpm build.

  • Main conflicts resolved semantically: Meet keeps its refresh helpers shared with the plugin owner; X keeps the OAuth owner without main's retired client-wide signal; MCP redirect and refresh-queue tests keep the uncertain-outcome assertions on main's fixtures; test path lists and the assertion baseline take both sides; GitHub personal OAuth keeps main's pending-write tracker with the typed refresh outcomes, and the worker test list drops the enterprise MCP tests main reverted.

  • Hosted CI fixes on the previous head: interactive MCP sign-in now starts authorization after a failed refresh (the possibly consumed grant stays fenced until the new code exchange replaces it); a caller abort while waiting for the MCP OAuth lease keeps its informational lease outcome; Codex refresh tests cover the full credential context and the flow-owner fail-closed path; X type cycle, Vertex test helper import and PR wrapper inventory.

  • Latest correction: Control UI MCP sign-in no longer reports success while an earlier lost forced refresh leaves a fenced claim beside locally fresh tokens; it starts a new authorization, and the code exchange clears the claim (Gateway mcp.authLogin regression shown failing on the prior head). A sign-in's own failed refresh still reports as before. Added a direct test for cancelling a caller while another holds the MCP OAuth lease. The Meet grant lineage hash keeps its deterministic SHA-256 (persisted, must survive restarts; not password storage) and its ineffective inline CodeQL comment is removed. Integrating main picks up fix: terminal lifecycle tests fail during module loading #180156, which fixes the inherited agent-lifecycle-terminal test failure from main.

Not covered: live provider refresh against real accounts. Exact-head CI runs on this PR.

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Oct 20, 2026
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR preserves saved OAuth credentials after narrowly identified transient xAI refresh failures so later requests can retry.

Example: The xAI token endpoint returns HTTP 503 while refreshing xai:default.

  • Before: The saved credential becomes terminal, requiring sign-in again.
  • After: The exact credential is restored after settlement, allowing a later request to refresh successfully.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused real-transport evidence and repaired regressions support the implementation; readiness remains capped by the unresolved replay-policy decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied head-pinned trace exercises the native manager and registered xAI transport/parser against fault-injected real HTTP with isolated SQLite, showing delayed-settlement and 503 recovery, terminal invalid-200/401 handling, no duplicate in-flight requests, and disconnect/reassignment rejection before publication or subsequent provider I/O.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Preference · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A temporary xAI refresh failure retires the saved login and makes subsequent requests require sign-in again.
Reason: The recovery has demonstrated user value, but it deliberately changes an established safety policy rather than restoring previously promised retry behavior.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open for an auth-owner decision on the proposed replay policy; both prior findings are addressed, and no remaining discrete code defect was identified.

Priority: P2
Reviewed head: 32625d2d4c318b51aa882d0ade5fde918c4d7993
Owner decision: Required. See Decision needed.

Decision needed

  • Question: May completed xAI transport failures and token-endpoint 429/5xx responses restore a potentially consumed refresh token for a later attempt?
  • Recommendation: Accept the narrow exception: Allow provider-admitted restoration with the implemented authority checks, terminal rejection handling, and unchanged in-flight ownership.
  • Why: Existing fencing deliberately prohibits post-I/O replay, and this PR explains but does not establish owner acceptance of its narrower exception.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Agent review details

How this fits together

The auth-profile manager claims persisted credentials, invokes the provider refresh hook, and settles owner and peer stores before returning access credentials or a typed failure to agent callers.

flowchart TD
  A[Agent auth candidate] --> B[OAuth manager]
  B --> C[SQLite credential claim]
  B --> D[xAI refresh transport]
  D --> E[Failure admission]
  E --> F[Authority and exact claim checks]
  F --> C
  B --> G[Access credential or typed failure]
Loading

Technical review

Best possible solution:

Retain provider-owned admission and exact-claim restoration only if the auth owner accepts the documented token-replay tradeoff.

Do we have a high-confidence way to reproduce the issue?

Current-main source terminally fences completed refresh failures, and the supplied real-HTTP comparison demonstrates that behavior for HTTP 503; this review executed no target code.

Is this the best way to solve the issue?

The implementation uses the existing provider, claim, store, and health owners and preserves invalid-success rejection; whether uncertain refresh-token replay is desirable remains an explicit owner choice.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against bd2dbfdeb493.

Provenance checked

  • Post-I/O refresh retirement changes intended behavior with a stated reason (b824b72: Durable fencing prevents failed or delayed owners and copied credentials from replaying potentially consumed refresh tokens.)
  • Historical peer settlement changes intended behavior with a stated reason (43c68c3: Peer transitions use their admitted database writer and exact captured identity; post-provider failures deliberately remained terminal.)
  • Candidate health recording keeps the original intent (0a8313e: The candidate owner records typed refresh failures while preserving read-only and local failure policies.)
  • Personal credential publication keeps the original intent (f48c19d: Worker-owned exact comparison and final authority checks prevent delayed settlement from replacing a newer personal credential.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Raw commit b824b72 adds docs/auth-credential-semantics.md:62 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b824b72ce284; files: docs/auth-credential-semantics.md)

PR surface

Source +200, Tests +370, Docs +14. Total +584 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 280 80 +200
Tests 6 382 12 +370
Docs 1 16 2 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 678 94 +584

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +280/-80 lines; tests +382/-12 lines Growth implements provider admission, exact restoration, and current-authority checks using existing owners; tests cover distinct rejection, persistence, and caller-policy boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The change improves recovery from limited xAI refresh failures; the supplied evidence does not establish an urgent deployed regression.
  • merge-risk: 🚨 auth-provider: Restoring failed refresh generations changes whether later requests reuse saved credentials or require sign-in.
  • merge-risk: 🚨 security-boundary: The proposed exception changes the intentional retirement boundary for refresh tokens that may already have been consumed.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-20T18:57:34.401Z sha a8305467003d56abc84ab5fe45f51ce397c6dbe7 :: needs real behavior proof before merge. :: [P2] Keep successful-response validation failures terminal | [P2] Honor caller health-write policy during transient rollback

Reviewed October 20, 2026, 6:26 PM ET / 22:26 UTC (Revision 2).

@Stronggenetics
Stronggenetics force-pushed the fix/oauth-refresh-transient-timeout branch from a830546 to 32625d2 Compare October 20, 2026 22:20
@Stronggenetics

Copy link
Copy Markdown
Contributor Author

Updated for the round-1 review (head 32625d2d4c). The PR description now answers each item:

  • Post-200 parse/validation failures (including the xAI missing access_token case) stay terminal. Only provider-admitted transport, timeout, 429 and 5xx outcomes can restore the credential.
  • Credential restoration is now separate from health recording, so read-only and local-policy runs no longer persist a shared cooldown.
  • Personal-account disconnect and reassignment during a pending refresh are rejected before publication, with no further provider I/O.
  • Main-created SQLite rows load unchanged.
  • A real xAI HTTP transport proof runs main against the branch.

The narrow replay policy is stated for the maintainer decision.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 20, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

1 similar comment
@fuller-stack-dev

Copy link
Copy Markdown
Member

/allow-security-sensitive-change

@fuller-stack-dev
fuller-stack-dev enabled auto-merge (squash) October 22, 2026 04:34
@fuller-stack-dev
fuller-stack-dev merged commit 6a4ac84 into openclaw:main Oct 22, 2026
160 of 169 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…w#178646)

* fix(auth): temporary OAuth refresh failures force repeated sign-in

* fix(auth): transient refresh recovery bypasses validation and caller policy

* fix(auth): fence transient refresh recovery by current owner

* test(auth): prove scoped refresh failure sharing

* fix(auth): share evidence-based OAuth refresh recovery

* fix(auth): close OAuth refresh-recovery review gaps

- Vertex ADC: drop the external durable claim; recover via the shared outcome.
- Microsoft Teams: reusable delegated claims keep the original grant; terminal
  rejection erases recovery material; publication failure retries safely.
- Google Meet, Twitch, MCP: preserve completed exchanges and reconcile exact
  committed claims instead of stranding or replaying rotating grants.
- xAI: bounded retries only for a verified Cloudflare challenge; transport and
  pre-header failures stay uncertain.
- GitHub: classify personal preparation failures as before-dispatch; fold the
  refresh-boundary suite into the lifecycle helper root; scheduling test waits
  for the dispatched refresh after the pre-dispatch claim write.
- Anthropic: safe local refresh diagnostics.
- Document operator reconnect after a rotating-grant crash.

* fix(xai): keep sign-in after plain 429/5xx refresh responses

xAI token responses with HTTP 429 or 5xx and no OAuth error field now report an owner-accepted provider retry, so the stored sign-in is restored and refreshed later. Structured OAuth errors, lost or unreadable responses, and invalid success bodies stay fenced.

* fix(xai): keep sign-in after transient OAuth errors on 429/5xx

xAI 429/5xx token responses with transient or unrecognized OAuth error codes now keep the stored sign-in for a later refresh. Final OAuth errors stay terminal at any status.

* fix(auth): keep Google and Microsoft grants through unreadable refresh responses

Meet and Teams classify an HTML or unreadable 5xx/429 refresh body by status with documented reusable-grant evidence, and an unreadable success body like a lost response. The xAI SDK boundary test now expects a kept sign-in after an HTML 503. Fold the three new auth-storage OAuth test roots into one to keep the agents-sessions type shard at 720. Docs describe per-owner recovery, Twitch reauthorization and the provider-owner decision behind owner-accepted-provider-retry.

* docs(auth): scope final OAuth reasons and Vertex recovery wording

* refactor(x): drop retired client-wide OAuth signal

Main removed the unused client-wide signal from createXApiClient; the token
exchange keeps its own 30 second deadline and callers still cancel observation.

* fix(auth): align OAuth refresh correction with current main

Use main's positional Twitch token resolver, keep Teams claim parsing within its assertion budget, reuse main's OAuth manager test helper, and give the caller-policy test typed reusable-grant evidence instead of the retired retryable boolean.

* fix(auth): keep MCP sign-in and lease aborts working with refresh fences

- start interactive MCP authorization after a failed refresh while the
  dispatched claim stays fenced; align forced-effects expectations
- forward caller aborts to MCP OAuth lease waiting only; detach after admission
- cover Codex flow-owner refresh context and fail-closed facade branch
- break the X api/oauth type cycle, keep the Vertex test on public helpers,
  add the shared outcome module to the PR wrapper inventory, and annotate the
  Meet grant fingerprint for CodeQL

* chore(google-meet): drop ineffective CodeQL suppression comment

* fix(mcp): start a new sign-in when a refresh claim fences fresh tokens

* fix(mcp): let Gateway sign-in prepare authorization past a fenced refresh claim

* fix(mcp): keep reporting this sign-in's own failed refresh

---------

Co-authored-by: Stronggenetics <[email protected]>
Co-authored-by: Jason (Json) <[email protected]>
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: msteams Channel integration: msteams channel: twitch Channel integration: twitch channel: x clawtributor-review Clawtributor pull request awaiting prioritized maintainer review docs Improvements or additions to documentation extensions: chutes extensions: google extensions: minimax extensions: openai extensions: radius extensions: xai gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. plugin: google-meet proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants