Skip to content

fix(auth): prevent concurrent OAuth turns from failing after refresh - #185880

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-red-main-oauth-authority-chain-20260919
Oct 27, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-red-main-oauth-authority-chain-20260919

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes concurrent OAuth turns failing after a successful shared-account refresh with MCP_AUTHORIZATION_UNAVAILABLE.

User Impact

The refreshing agent and its waiting peer can both use the verified same-account rotation, including after restart. Account mismatches and logout still refuse credentials.

Why This Change Was Made

#184791 correctly added live authorization capture to OAuth turns, exposing a latent race in first-use enrollment. Concurrent captures inspect the same canonical store; one enrollment can invalidate the other's read or strict enrollment comparison even though both requested the same account.

The authorization owner now uses the existing keyed queue for the complete read/enroll/capture sequence, keyed by both canonical database paths. Each caller keeps its own closure, live owner checks, readers, and disposable handle. The native writer's strict comparison, revocation/rebinding checks, pending-write fence, and unknown-settlement refusal remain intact. Ignoring authorization-lifetime differences would lose identical-byte reconnect protection, so the fix coordinates enrollment instead.

Captures sharing a database serialize initialization; disjoint stores remain independent. Production growth is 13 lines (the larger diff is indentation), needed to retain the existing security contract. This is a correctness repair with no performance claim.

Evidence

  • Current-main reproduction at 69ad14ea81bc47ad658c9fc3a4b669f90eeab348: the actual built-Gateway file fails the same-account peer with MCP_AUTHORIZATION_UNAVAILABLE; mismatch and logout pass (1 failed, 2 passed).

  • Adjacent revision comparison with the unchanged Gateway test: c00af62f03e6ab9929234a998693f53341a4e126 passes the same-account/restart case; the immediately following fix: renew OAuth credentials during long custom transport attempts #184791 commit c152c5976b218bf62f7c7666c4703d1a39ecfa80 fails its peer-success assertion. Both revisions were rebuilt independently in this lane.

  • The new native-owner regression fails before the fix: two concurrent first-use captures produce one fulfilled and one rejected result. It also checks independent disposal and replacement invalidation.

  • Focused validation: 54 tests passed across the authorization owner, native writer observation, request-auth controller, and prompt-prefix stability files. The command took 652.70 seconds including worker preparation on a loaded Mac; the new concurrent-capture case took 2.447 seconds. Core typecheck, changed-file lint, formatting, and git diff --check passed.

  • Built-Gateway candidate proof on pushed head 2939f3c824e9b19897f3f70fbf2e5493fdfe269f: all 3 original cases passed (same-account peer/restart, account-mismatch refusal, and logout revocation before stale refresh settlement). The prebuilt Gateway test command took 157.74 seconds; test cases took 43.002, 16.515, and 25.085 seconds respectively. No authority assertion was weakened.

  • Independent subagent review (autoreview route unavailable): scoped-clean at P1/P2. The configured autoreview route failed its configuration preflight; no operator configuration was changed. The subsequent exact test-line ceiling refresh was independently reviewed and verified against the script's counting method.

  • First PR CI run 40503408340: all selected tests, typechecks, lint, source contracts, and guards passed except the test-line ceiling. It reported 6,281,655 lines versus 6,280,000, with only +17 from this PR. After the required main rebase, the measured total is 6,282,728 versus the updated 6,282,239 ceiling (472 inherited excess +17 here). The ceiling now equals that exact total, with zero headroom; the failed ratchet passes locally. This preserves the native concurrency regression and Gateway diagnostics without weakening any assertion. Authorization sources, queue, state sources, affected tests, package manifest, and lockfile are unchanged from the tested head. Final exact-head CI is recorded below.

Related: #185732, whose failed OAuth CI job and maintainer attribution identified this inherited red. No Team load or Testbox lease was used; all runtime proof uses isolated synthetic local Gateways.

CodeQL triage

Alert #1171 reports js/insufficient-password-hash on the unchanged SHA-256 authorization-ID calculation moved inside the queued block. Source inspection and the independent reviewer confirm a false positive: the complete hash input is a namespace, profile ID, canonical database paths, and owner-issued incarnation UUIDs, never credential bytes. authorization-observation.ts obtains incarnations through readAuthProfileAuthorizationLifetime; authorization-lifetime.ts creates/rotates them with randomUUID() and overrides incoming lifetime metadata. auth-controller.ts separately extracts the API key and profile ID; only the latter reaches capture. Live caller/owner and incarnation/status checks enforce authority independently of the digest.

GitHub requires delegated dismissal approval. False-positive dismissal request #74 was submitted and is pending; no scan rule or security check was disabled.

Final CI attribution

Final head bb71315b1a58ec8356a8173a22fe82b13ccf7d70 completed CI run 40506151388. The ratchet, all typechecks/lint, security-fast, and all other selected test jobs passed. The only non-aggregate failure is checks-node-changed-3: the two final HTTP adoption cases in src/cron/isolated-agent.auth-continuity.integration.test.ts report successful synthetic responses but observe no loopback requests at line 580.

The identical single-file command, node scripts/run-vitest.mjs src/cron/isolated-agent.auth-continuity.integration.test.ts --maxWorkers=1, reproduces exactly 2 failed, 7 passed on both the final PR head (175.74 seconds) and unchanged CI main parent 83274dfe3218ea394900afc3fb7cb91416a3a80c (230.48 seconds). CI checkout 821ce829a70774c0349b9f27487fe3b7acefe71d has those exact main/PR parents. The fixture and transport-host sources are unchanged by this PR. Its fetch spy can be copied into a replacement host during lazy transport initialization, while mock restoration restores the prior object; later HTTP cases then receive the retained synthetic response. This is a separate fixture-isolation failure, not an authorization rejection.

Landing uses the maintainer-authorized inherited-CI exception with the failed run retained as failed. No CI rerun was requested. Exact-head security-sensitive and dependency review both passed. CodeQL's separately reviewed false-positive dismissal remains pending as described above; no security rule was disabled.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Oct 27, 2026
@steipete
steipete marked this pull request as ready for review October 27, 2026 12:23
@clawsweeper

clawsweeper Bot commented Oct 27, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T12:46:36.268684Z bb71315 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: bb71315b1a58ec8356a8173a22fe82b13ccf7d70
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/authorization.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

Comment on lines +283 to +288
JSON.stringify([
"mcp-auth-profile-v1",
profileId,
selectedPath,
...lineage.map((target) => [target.databasePath, target.incarnation]),
]),
Serialize authorization capture across overlapping canonical stores so first-use
lifetime enrollment cannot invalidate another capture of the same shared account.
Keep each caller's own authority and the native writer's strict stale comparison,
revocation checks, and uncertain-settlement refusal.

Preserve same-account peer inheritance, restart behavior, and fail-closed mismatch
and logout behavior. Regress the concurrent capture and independent disposal.

Related: #185732, #184791
Preserve the concurrent OAuth authority regression and its diagnostic assertion. The synchronized base already exceeds the ceiling by 472 lines; this change adds 17. Set the ceiling to the exact measured total with no extra headroom. Independently reviewed; the failed ratchet now passes.
@steipete
steipete force-pushed the steipete/perf-micro-red-main-oauth-authority-chain-20260919 branch from 2939f3c to bb71315 Compare October 27, 2026 12:44
@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. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed 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. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR serializes authorization capture across overlapping credential stores while preserving each caller’s independent authority.

Example: Two agents concurrently capture the unchanged authority-proof:default OAuth account for the first time.

  • Before: One capture can fail with MCP_AUTHORIZATION_UNAVAILABLE after the other enrolls authorization metadata.
  • After: Both captures succeed, while disposal and credential replacement still invalidate the appropriate handles.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with reported production-entry-point authority coverage and no actionable patch findings; unresolved CI and alert disposition remain landing gates.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR records built-Gateway results exercising the changed capture owner through real agent turns and loopback provider HTTP: same-account owner and peer succeed across restart, a mismatched peer sends no model request, and logout prevents stale settlement and later model I/O; the tested production and affected-test blobs match this head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Concurrent OAuth turns can fail after successful same-account refresh because first-use authorization captures invalidate one another.
Reason: The maintainer-authored direction restores documented account continuity through the existing owner without adding configuration, public APIs, or credential storage.

Regression provenance

Possible regression — probable (reviewed change; known regression link). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this maintainer PR repairs a current authorization-enrollment race with a focused change; no introduced correctness defect was found.

Priority: P1
Reviewed head: bb71315b1a58ec8356a8173a22fe82b13ccf7d70

Before merge

  • Await maintainer action - An authorized reviewer must resolve the pending delegated false-positive dismissal for CodeQL alert 1171.

Findings

None.

Agent review details

How this fits together

The authorization owner reads canonical local and shared credential stores and returns token-free handles that guard subsequent credential resolution and provider requests.

flowchart TD
  A[Concurrent agent turns] --> B[Canonical store keyed queue]
  B --> C[Read and enroll authorization]
  C --> D[Independent authority handles]
  E[Credential writer publications] --> D
  D --> F[Guarded provider requests]
Loading

Technical review

Best possible solution:

Retain the owner-level serialization and strict credential comparisons, then land once the existing CI and alert-disposition gates are satisfied.

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

The unqueued main implementation and strict whole-row enrollment comparison explain the failure, corroborated by the PR’s before/after Gateway results and the independent report at #185919; this review ran no target code.

Is this the best way to solve the issue?

Serializing the complete initialization sequence in the existing authorization owner is the smallest complete fix: it prevents enrollment collisions without weakening reconnect detection or sharing caller authority.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Authorization capture and enrollment keeps the original intent (d25a316: Bind automation inference to a durable account lifetime while rejecting replacement, revocation, and identity changes.)
  • Writer-published authorization facts keeps the original intent (b106f5a: Reuse canonical owner facts while retaining pending-write and uncertain-settlement refusal.)
  • Gateway OAuth authority assertions keeps the original intent (b824b72: Prove same-account refresh continuity, cross-account refusal, and logout invalidation before provider effects.)
  • Test-line ceiling changes intended behavior with a stated reason (ad9b7ae: Maintain a measured test-line ceiling; this PR documents and exactly accounts for inherited excess and its focused regression.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Focused introduced change: The pinned introduced diff wraps the existing read/enroll/capture sequence in enqueueKeyedTask using both canonical database paths; authority checks, enrollment comparison, hashing inputs, and disposal semantics remain intact. (src/agents/auth-profiles/authorization.ts:212, bb71315b1a58)
  • Current owned failure: Enrollment strictly compares the complete observed row, so another successful first-use enrollment can invalidate an otherwise unchanged account. The same failure is independently documented in [Bug]: concurrent first-use authorizations reject unchanged accounts #185919; fetched main retains the unqueued capture implementation. (src/agents/auth-profiles/authorization-enrollment.ts:30, a4a8f632da0a)
  • Gateway and authority evidence: The PR records successful built-Gateway same-account/restart, account-mismatch, and logout-before-settlement scenarios. Their source asserts account-A HTTP requests on success and no forbidden peer or post-logout model requests. GitHub blob identities confirm the reported tested revision’s authorization implementation and affected tests match this head. (test/oauth-refresh-authority-chain.e2e.test.ts:525, bb71315b1a58)
  • Preserved security contract: Queued tasks recheck caller and owner authority before reading and enrollment; returned handles retain incarnation, pending-write, replacement, and revocation checks. The flagged SHA-256 input contains profile IDs, paths, and owner-issued UUIDs rather than passwords or bearer credentials. (src/agents/auth-profiles/authorization.ts:281, bb71315b1a58)
  • Exact measured baseline: An independent read-only recount using the ratchet’s tracked-file patterns yields 6,282,728 newline characters, exactly the proposed ceiling; the script expressly permits a justified ceiling adjustment. (config/test-lines-baseline.txt:1, bb71315b1a58)
  • Outstanding merge gates: Current-head CI reports a cron auth-continuity HTTP assertion failure at line 580, whose cause is not established, and the CodeQL hash alert. The PR reports a pending delegated false-positive dismissal. Detailed job logs redirect to a blocked storage host, so the cron failure is neither attributed to this patch nor declared inherited. (src/cron/isolated-agent.auth-continuity.integration.test.ts:580, bb71315b1a58)

PR surface

Source +13, Tests +17, Docs +5, Other 0. Total +35 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 98 85 +13
Tests 2 19 2 +17
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 5 123 88 +35

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +13 net lines; tests +17 net lines. The production growth coordinates existing owner operations; the test growth covers concurrent enrollment and improves existing Gateway failure diagnostics.

Labels

Label changes:

  • add P1: A demonstrated current-main race causes concurrent OAuth agent turns to fail before inference despite an unchanged authorized account.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.

Label justifications:

  • P1: A demonstrated current-main race causes concurrent OAuth agent turns to fail before inference despite an unchanged authorized account.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • 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.

Reviewed October 27, 2026, 9:00 AM ET / 13:00 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Inherited-CI landing evidence for head bb71315b1a58ec8356a8173a22fe82b13ccf7d70:

Run 40506151388 failed only the cron OAuth continuity test job (plus its downstream CI gate). The refreshable-control and access-only HTTP adoption cases both fail at line 580 with no observed HTTP request, despite successful synthetic model output.

The exact single-file command node scripts/run-vitest.mjs src/cron/isolated-agent.auth-continuity.integration.test.ts --maxWorkers=1 reproduces the same 2 failed, 7 passed on the PR head (175.74 s) and unchanged CI main parent 83274dfe3218ea394900afc3fb7cb91416a3a80c (230.48 s). The CI merge checkout is 821ce829a70774c0349b9f27487fe3b7acefe71d, with that main parent and this PR head. Source inspection identifies a fetch spy copied into a replacement transport host, surviving restoration of the previous host object; the relevant fixture/host sources are unchanged by this PR.

All other selected CI jobs passed, including the repaired test-line ratchet, and the original OAuth refresh Gateway file passes all three cases. Independent review is clean; exact-head security-sensitive/dependency review passed. Landing under the requested inherited-failure exception, without rerunning CI or claiming the failed run green. CodeQL alert #1171 was independently verified as a false positive on the unchanged UUID-based identifier hash; delegated dismissal request #74 remains pending.

@steipete
steipete merged commit 7bce7a6 into main Oct 27, 2026
138 of 142 checks passed
@steipete
steipete deleted the steipete/perf-micro-red-main-oauth-authority-chain-20260919 branch October 27, 2026 13:06
steipete added a commit that referenced this pull request Oct 27, 2026
Initialize the complete agent transport host before provider interception so lazy runtime setup cannot retain a copied spy past teardown. Preserve all credential continuity, revocation, restart, and real HTTP assertions. Repairs the inherited cron integration failure recorded in #185880; no production behavior changes.
steipete added a commit that referenced this pull request Oct 27, 2026
* test(cron): isolate auth continuity transport spies

Initialize the complete agent transport host before provider interception so lazy runtime setup cannot retain a copied spy past teardown. Preserve all credential continuity, revocation, restart, and real HTTP assertions. Repairs the inherited cron integration failure recorded in #185880; no production behavior changes.

* test(cron): keep transport setup explanation inline
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…penclaw#185880)

* fix(auth): prevent concurrent OAuth turns from failing after refresh

Serialize authorization capture across overlapping canonical stores so first-use
lifetime enrollment cannot invalidate another capture of the same shared account.
Keep each caller's own authority and the native writer's strict stale comparison,
revocation checks, and uncertain-settlement refusal.

Preserve same-account peer inheritance, restart behavior, and fail-closed mismatch
and logout behavior. Regress the concurrent capture and independent disposal.

Related: openclaw#185732, openclaw#184791

* chore(test): refresh measured test-line ceiling

Preserve the concurrent OAuth authority regression and its diagnostic assertion. The synchronized base already exceeds the ceiling by 472 lines; this change adds 17. Set the ceiling to the exact measured total with no extra headroom. Independently reviewed; the failed ratchet now passes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
* test(cron): isolate auth continuity transport spies

Initialize the complete agent transport host before provider interception so lazy runtime setup cannot retain a copied spy past teardown. Preserve all credential continuity, revocation, restart, and real HTTP assertions. Repairs the inherited cron integration failure recorded in openclaw#185880; no production behavior changes.

* test(cron): keep transport setup explanation inline
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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: M status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants