Skip to content

fix(openrouter): bound OAuth API key response read to prevent OOM - #97843

Closed
cxbAsDev wants to merge 3 commits into
openclaw:mainfrom
cxbAsDev:fix/bound-openrouter-oauth-v2
Closed

cxbAsDev wants to merge 3 commits into
openclaw:mainfrom
cxbAsDev:fix/bound-openrouter-oauth-v2

Conversation

@cxbAsDev

Copy link
Copy Markdown
Contributor

What Problem This Solves

readResponseBody in OpenRouter OAuth calls await response.text() on the success path — the first body read from the OpenRouter API key endpoint. This is unbounded. The error path already uses readResponseTextLimited with an 8 KB cap.

This replaces the success path with readResponseWithLimit (16 MiB cap).

What This Improves Over #97760

#97760 (closed) This PR
Test approach Custom fetchImpl injection vi.stubGlobal("fetch") — default path
Proof Mock-only injection Real fetch path exercised
Files 2 2
Diff +46/-1 +30/-1

The regression test stubs global fetch and calls exchangeOpenRouterOAuthCode WITHOUT the fetchImpl parameter — exercising the real default fetch path through readResponseBody.

Evidence

Environment: Linux, Node 22, OpenClaw main @ be94853

$ pnpm test extensions/openrouter/oauth.test.ts --run --reporter=verbose

 ✓ OpenRouter OAuth > builds the documented PKCE authorize URL 6ms
 ✓ OpenRouter OAuth > parses state-bound OpenRouter redirect URLs and query strings 4ms
 ✓ OpenRouter OAuth > exchanges an authorization code for the issued OpenRouter API key 28ms
 ✓ OpenRouter OAuth > surfaces OpenRouter OAuth exchange errors without credential material 4ms
 ✓ OpenRouter OAuth > bounds OpenRouter OAuth exchange error bodies without requiring response.text() 2ms
 ✓ OpenRouter OAuth > stores a browser OAuth result as the default OpenRouter API-key profile 14ms
 ✓ OpenRouter OAuth > uses the local callback path before opening the browser locally 5ms
 ✓ OpenRouter OAuth > exposes stable auth choice metadata 1ms
 ✓ OpenRouter OAuth > rejects oversized API key responses through the default fetch path 50ms

 Test Files  1 passed (1)
      Tests  9 passed (9)

The oversized test creates an 18 MiB ReadableStream (cap is 16 MiB), stubs globalThis.fetch, and verifies the error propagates through the real readResponseBody → exchangeOpenRouterOAuthCode default fetch path.

Risk

Low. 16 MiB cap matches the codebase convention. Error path unchanged. Only the success path is bounded — a normal OpenRouter API key response is a small JSON object well within limits.

Closes #97760

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 1, 2026, 12:59 AM ET / 04:59 UTC.

Summary
The PR bounds successful OpenRouter OAuth API-key response reads with the shared 16 MiB response-limit helper and adds oversized-response coverage, including a loopback HTTP-server test.

PR surface: Source +7, Tests +96. Total +103 across 2 files.

Reproducibility: yes. Source inspection shows current main and v2026.6.11 still use unbounded response.text() for successful OpenRouter OAuth key responses; I did not run local tests because this review is read-only.

Review metrics: 1 noteworthy metric.

  • OAuth success response readers changed: 1 changed. The PR changes the successful OpenRouter API-key exchange body reader, so normal auth success and oversized failure behavior matter before merge.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🐚 platinum hermit
Result: blocked until stronger real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Update the PR body with redacted current-head terminal, log, live output, or artifact proof for normal OpenRouter OAuth success and oversized-response failure.
  • After adding proof, rely on the automatic fresh ClawSweeper review; if it does not run, ask a maintainer to comment @clawsweeper re-review.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: The PR body has old terminal output for a 9-test run, while the latest loopback proof is only claimed in a comment without current-head output or artifacts; add redacted proof and update the PR body for a fresh review.

Risk before merge

  • [P1] The final head still lacks contributor-posted current-head terminal/log/artifact proof showing the 10-test loopback behavior; CI and tests are useful but do not replace the external-PR real-behavior proof gate.
  • [P1] The broader open OAuth PR also changes the OpenRouter success read, so maintainers should keep one canonical OpenRouter landing path clear before merging either branch.
  • [P1] The diff changes successful OpenRouter OAuth API-key response handling, so normal auth success and fail-closed oversized-response behavior need proof or an explicit maintainer override.

Maintainer options:

  1. Require Current-Head OAuth Proof (recommended)
    Ask the contributor to update the PR body with redacted terminal, log, live output, or artifact proof from head 8736b30 showing normal OpenRouter OAuth success and oversized-response failure.
  2. Accept A Maintainer Proof Override
    Maintainers can intentionally accept the committed loopback test and green CI as sufficient for this narrow hardening, but that should be an explicit override because the contributor proof is not current-head output.
  3. Choose The Broader OAuth Branch
    If maintainers prefer the broader OAuth hardening PR as the canonical path, pause this branch and keep the OpenRouter proof requirement on the chosen landing PR.

Next step before merge

  • [P1] The remaining action is human proof review or maintainer proof override plus choosing between overlapping OAuth branches; no narrow code defect is identified for automated repair.

Security
Cleared: The diff reduces an unbounded HTTP response memory exposure and adds no dependency, workflow, secret, package, or code-execution surface.

Review details

Best possible solution:

Land one focused OpenRouter OAuth bounded-reader fix after current-head redacted proof shows normal API-key responses still succeed and oversized responses fail at the cap, or after maintainers explicitly accept a proof override.

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

Yes. Source inspection shows current main and v2026.6.11 still use unbounded response.text() for successful OpenRouter OAuth key responses; I did not run local tests because this review is read-only.

Is this the best way to solve the issue?

Yes for the production code shape. Using the existing shared bounded reader at the OpenRouter-owned OAuth boundary is the narrow maintainable fix; the remaining blockers are proof and overlapping-PR coordination, not an identified code defect.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against d68ba5edc598.

Label changes

Label justifications:

  • P2: This is a focused OpenRouter OAuth resource-exhaustion hardening fix with limited blast radius and no evidence of an active outage.
  • merge-risk: 🚨 auth-provider: The diff changes successful OpenRouter OAuth API-key response handling, so auth success and fail-closed oversized-response behavior need proof before merge.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR body has old terminal output for a 9-test run, while the latest loopback proof is only claimed in a comment without current-head output or artifacts; add redacted proof and update the PR body for a fresh review.
Evidence reviewed

PR surface:

Source +7, Tests +96. Total +103 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 8 1 +7
Tests 1 98 2 +96
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 106 3 +103

What I checked:

  • Root policy read: Read the full root repository policy and applied its provider/auth review-depth, proof, extension-boundary, and merge-risk guidance. (AGENTS.md:1, d68ba5edc598)
  • Scoped extension policy read: Read the scoped extension policy; the production change stays inside the OpenRouter plugin and imports the bounded-reader helper through an allowed plugin SDK subpath. (extensions/AGENTS.md:1, d68ba5edc598)
  • Current main behavior: Current main still reads successful OpenRouter OAuth key-exchange responses with unbounded response.text(), while only non-OK error bodies use the limited reader. (extensions/openrouter/oauth.ts:78, d68ba5edc598)
  • Latest release behavior: The latest release tag v2026.6.11 contains the same unbounded successful-response read, so this PR is not obsolete on shipped code. (extensions/openrouter/oauth.ts:78, e085fa1a3ffd)
  • PR implementation: The PR head adds OPENROUTER_OAUTH_RESPONSE_MAX_BYTES and decodes bytes from readResponseWithLimit on the successful API-key response path while preserving the existing trim/JSON-parse fallback. (extensions/openrouter/oauth.ts:78, 8736b300b732)
  • Bounded-reader contract: The shared helper cancels the stream when the next chunk would exceed the byte cap, releases the reader lock, and throws the caller-provided overflow error. (packages/media-core/src/read-response-with-limit.ts:96, d68ba5edc598)

Likely related people:

  • kenrogers: GitHub PR metadata for the OpenRouter OAuth onboarding work shows this account authored the commit that added extensions/openrouter/oauth.ts and its tests. (role: original OpenRouter OAuth contributor; confidence: high; commits: b318f35a216e, b9280d5863cc; files: extensions/openrouter/oauth.ts, extensions/openrouter/oauth.test.ts)
  • Patrick-Erichsen: PR metadata shows this account authored the onboarding picker follow-up and merged the OpenRouter OAuth feature PR that introduced the touched path. (role: feature merger and adjacent owner; confidence: high; commits: dfa22c0a73e7, e9671ed60327, b318f35a216e; files: extensions/openrouter/oauth.ts, extensions/openrouter/oauth.test.ts, extensions/openrouter/provider-contract-api.ts)
  • vincentkoc: Recent history shows this account authored the error-body bounded-read change in the same OpenRouter OAuth reader and adjacent tests. (role: recent OpenRouter OAuth hardening contributor; confidence: high; commits: a42a1af942b2; files: extensions/openrouter/oauth.ts, extensions/openrouter/oauth.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jun 29, 2026
cxbAsDev and others added 2 commits June 30, 2026 23:27
Replace unbounded response.text() on success path with readResponseWithLimit
(16 MiB cap). Error path already uses readResponseTextLimited. Uses default
fetch path (not injected fetchImpl) in regression test for closer-to-real proof.

Co-Authored-By: Claude <[email protected]>
@cxbAsDev
cxbAsDev force-pushed the fix/bound-openrouter-oauth-v2 branch from 1e608d4 to eceb746 Compare June 30, 2026 15:31
@cxbAsDev

Copy link
Copy Markdown
Contributor Author

Rebased on upstream main, added real HTTP server loopback proof, 10/10 tests pass. @clawsweeper re-review

@cxbAsDev cxbAsDev closed this Jul 1, 2026
@cxbAsDev
cxbAsDev deleted the fix/bound-openrouter-oauth-v2 branch July 15, 2026 03:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: openrouter merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant