Skip to content

fix(infra): bound response body read in readResponseBodySnippet non-streaming fallback - #101270

Closed
Pandah97 wants to merge 4 commits into
openclaw:mainfrom
Pandah97:fix/issue-101269-bound-error-body-read
Closed

Pandah97 wants to merge 4 commits into
openclaw:mainfrom
Pandah97:fix/issue-101269-bound-error-body-read

Conversation

@Pandah97

@Pandah97 Pandah97 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Problem: readResponseBodySnippet() non-streaming fallback (!body.getReader) calls response.text() without any size bound, buffering the entire response before the maxBytes check runs.

Solution: Replace response.text() with readResponsePrefix(response, maxBytes) which caps the read at maxBytes bytes regardless of path. The non-streaming fallback in readResponsePrefix itself is hardened with a fail-closed guard: when the response has no ReadableStream reader, it returns empty immediately — never calling arrayBuffer() or text() which would materialize the full body.

What changed: readResponsePrefix exported from http-body.ts (was private). Non-streaming fallback in http-error-body.ts uses it instead of response.text(). The no-reader branch of readResponsePrefix now fails closed (returns empty + truncated) instead of falling back to whole-body arrayBuffer(). Regression tests assert that arrayBuffer() is never invoked for no-reader or null-body responses.

What did NOT change: Streaming path behavior (already bounded). Return type/API surface of readResponseBodySnippet. Any caller behavior — all callers pass the same limits.

Fixes #101269

Root Cause

readResponseBodySnippet() at src/infra/http-error-body.ts:8-9 calls response.text() when no streaming reader is available (!body.getReader). Unlike the streaming path which reads chunk-by-chunk up to maxBytes, response.text() buffers the entire HTTP response body before any size check. The initial fix routed this through readResponsePrefix(), but that helper's own no-reader fallback called response.arrayBuffer() — the same unbounded-read pattern.

What Problem This Solves

readResponseBodySnippet() is called from Gateway error-handling paths to produce a diagnostic snippet of error response bodies. When response.body is a ReadableStream (always true in Node.js undici fetch), the streaming path correctly bounds reads. But for synthetic Response objects or edge-case HTTP responses without a readable stream, the fallback path could materialize a multi-megabyte body before truncation. This fix ensures that responses without a streaming reader are handled without any whole-body allocation, matching the fail-closed pattern already used by adjacent web helpers.

Real behavior proof

Behavior addressed: No-reader Response objects (synthetic or edge-case) now return empty without calling arrayBuffer() or text().

Real environment tested: Linux x64 (kernel 4.19.112), Node.js v24.13.1, OpenClaw commit a78538d (PR base)

Exact steps or command run after this patch:

npx tsx -e "
import { readResponseBodySnippet } from './src/infra/http-error-body.ts';

async function main() {
  // Test 1: No-reader Response — must NOT call arrayBuffer()
  let ab = false;
  const r1 = await readResponseBodySnippet({
    body: {} as ReadableStream,
    arrayBuffer: async () => { ab = true; return new ArrayBuffer(100000); },
  } as unknown as Response, { maxBytes: 50, maxChars: 100 });
  console.log('Test 1 (no-reader, arrayBuffer called?):', ab, 'result:', JSON.stringify(r1));

  // Test 2: null body
  let ab2 = false;
  const r2 = await readResponseBodySnippet({
    body: null,
    arrayBuffer: async () => { ab2 = true; return new ArrayBuffer(0); },
  } as unknown as Response, { maxBytes: 1024, maxChars: 100 });
  console.log('Test 2 (null body, arrayBuffer called?):', ab2, 'result:', JSON.stringify(r2));

  // Test 3: Large streaming response bounded by maxBytes
  const large = new Uint8Array(1024 * 100).fill(65);
  const r3 = await readResponseBodySnippet(new Response(new Blob([large]).stream()), { maxBytes: 100, maxChars: 200 });
  console.log('Test 3 (100KB stream, maxBytes=100):', r3.length, 'chars');

  // Test 4: Streaming with maxBytes strict
  const r4 = await readResponseBodySnippet(new Response(new Blob([new Uint8Array(500).fill(97)]).stream()), { maxBytes: 30, maxChars: 500 });
  console.log('Test 4 (maxBytes=30, 500 bytes):', new TextEncoder().encode(r4).length, 'bytes');

  // Test 5: Empty streaming response
  const r5 = await readResponseBodySnippet(new Response(new Blob([new Uint8Array(0)]).stream()), { maxBytes: 1024, maxChars: 50 });
  console.log('Test 5 (empty stream):', JSON.stringify(r5));
}
main();
"

After-fix evidence:

Test 1 (no-reader, arrayBuffer called?): false result: ""
Test 2 (null body, arrayBuffer called?): false result: ""
Test 3 (100KB stream, maxBytes=100): 100 chars
Test 4 (maxBytes=30, 500 bytes): 30 bytes
Test 5 (empty stream): ""

Observed result after the fix: All 5 real-world test cases confirm fail-closed behavior — no-reader and null-body Response objects never trigger arrayBuffer(). The streaming path correctly caps reads at maxBytes. All 11 unit tests pass with 2 regression tests asserting arrayBuffer() is not called for no-reader or null-body responses.

 ✓ readResponseBodySnippet > returns full text when under both limits
 ✓ readResponseBodySnippet > truncates by maxChars when under maxBytes
 ✓ readResponseBodySnippet > truncates by maxBytes before maxChars
 ✓ readResponseBodySnippet > enforces maxBytes before maxChars
 ✓ readResponseBodySnippet > does not split multi-byte UTF-8 characters at the byte boundary
 ✓ readResponseBodySnippet > stream path enforces maxBytes
 ✓ readResponseBodySnippet > stream path enforces maxChars
 ✓ readResponseBodySnippet > returns empty string when maxBytes is 0
 ✓ readResponseBodySnippet > returns empty string for empty response body
 ✓ readResponseBodySnippet > fails closed when body has no getReader (avoids arrayBuffer)
 ✓ readResponseBodySnippet > returns empty immediately when body is null
 Test Files  1 passed (1)
      Tests  11 passed (11)

What was not tested: Full end-to-end Gateway error handling — only the readResponseBodySnippet() function was verified via direct import call. The no-reader path is inherently a synthetic/edge-case scenario in Node.js undici fetch, where all HTTP responses provide a ReadableStream body.

Changes

File Change
src/infra/http-body.ts:189 Export readResponsePrefix (was private function)
src/infra/http-body.ts:199-208 Fail closed in no-reader branch: return empty immediately instead of calling arrayBuffer()
src/infra/http-error-body.ts:1,10 Import readResponsePrefix, replace unbounded response.text() with bounded readResponsePrefix
src/infra/http-error-body.test.ts Replace synthetic mock with streaming Response; add regression tests for fail-closed no-reader and null-body paths

Risk checklist

  • merge-risk: Low — streaming path unchanged (covers all production HTTP responses); fail-closed only affects synthetic/edge-case no-reader paths
  • Risk mitigation: No-reader path can never materialize a large response body — it returns empty immediately, matching the fail-closed pattern used by adjacent web helpers
  • User-visible behavior change? No — same limits, same truncation behavior for all production paths
  • Config/env/migration change? No
  • Security/auth/network change? No

Linked context

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 7, 2026, 8:46 AM ET / 12:46 UTC.

Summary
The branch exports readResponsePrefix, routes readResponseBodySnippet through it for no-reader responses, changes the shared no-reader helper path to fail closed, and updates focused tests.

PR surface: Source -5, Tests +31. Total +26 across 3 files.

Reproducibility: yes. Source inspection gives a high-confidence current-main path: pass a no-reader Response-like object with a large text() result to readResponseBodySnippet, and current main buffers the full text before applying maxBytes.

Review metrics: 1 noteworthy metric.

  • SDK Reader Behavior: 1 exported reader behavior changed. The shared helper backs plugin-sdk/response-limit-runtime, so maintainers should notice the public edge-case behavior before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #101269
Summary: This PR is a candidate fix for the canonical no-reader HTTP error snippet memory-bound issue; one sibling PR remains open with overlapping work, one sibling is closed unmerged, and merged related PRs are partial or adjacent precedent.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • [P2] A maintainer should either accept the SDK no-reader compatibility tradeoff or ask for focused public-helper tests before merge.

Risk before merge

  • [P2] readResponseWithLimit is exported through plugin-sdk/response-limit-runtime; non-standard Response-like plugin callers that previously relied on no-reader arrayBuffer() fallback will now get the overflow path instead of body bytes.

Maintainer options:

  1. Add SDK-Visible Fallback Coverage (recommended)
    Add direct tests through readResponseWithLimit or the plugin SDK subpath proving the no-reader fail-closed behavior, then re-review the exact head.
  2. Land With Compatibility Acceptance
    A maintainer can accept that capped calls must fail closed when no bounded stream exists, even though some Response-like plugin mocks may stop returning bytes.

Next step before merge

  • [P2] The remaining action is a maintainer compatibility call for an SDK-exported helper edge case, not an autonomous repair task.

Maintainer decision needed

  • Question: Should this PR land with fail-closed behavior for SDK-exported readResponseWithLimit when a non-standard Response-like object has no readable stream, or should focused SDK-facing coverage be added first?
  • Rationale: The fail-closed direction matches adjacent bounded-read policy, but the helper backs a public plugin SDK subpath and can change edge-case plugin behavior.
  • Likely owner: steipete — This account is the clearest owner for the bounded-response compatibility call based on current blame and the adjacent fail-closed fallback merge.
  • Options:
    • Require SDK Coverage First (recommended): Add focused tests for the SDK-exported reader's no-reader fail-closed behavior before landing the compatibility-sensitive helper change.
    • Accept The Edge-Case Change: Land the current patch based on the bounded-read safety rationale and adjacent fail-closed precedent, accepting the Response-like compatibility tradeoff.

Security
Cleared: No dependency, workflow, credential, permission, or supply-chain regression was found; the patch reduces an availability risk by avoiding whole-body fallback reads.

Review details

Best possible solution:

Land one canonical fail-closed bounded-reader fix, with the SDK-visible no-reader behavior either explicitly accepted by a maintainer or covered by focused public-helper tests before merge.

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

Yes. Source inspection gives a high-confidence current-main path: pass a no-reader Response-like object with a large text() result to readResponseBodySnippet, and current main buffers the full text before applying maxBytes.

Is this the best way to solve the issue?

Mostly yes. The fail-closed helper shape is the narrow maintainable way to make the byte cap honest, but the SDK-exported edge behavior should be accepted or covered before merge.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: This is a focused infra availability bug-fix PR with limited surface area and no evidence of an active outage.
  • merge-risk: 🚨 compatibility: The changed no-reader fallback affects a helper exported through the plugin SDK, which can change behavior for existing Response-like plugin callers.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes copied terminal output from after-fix direct runtime calls showing no-reader and null-body cases avoid arrayBuffer() and streaming cases obey the byte cap.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes copied terminal output from after-fix direct runtime calls showing no-reader and null-body cases avoid arrayBuffer() and streaming cases obey the byte cap.
Evidence reviewed

PR surface:

Source -5, Tests +31. Total +26 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 13 18 -5
Tests 1 53 22 +31
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 66 40 +26

What I checked:

  • Current main still has the reported unbounded fallback: On current main, the no-reader branch calls response.text() before applying limits.maxBytes, so a no-reader Response-like object can still materialize the whole body first. (src/infra/http-error-body.ts:8, 60f0749b7fb3)
  • PR head fails closed before whole-body reads: At PR head, readResponsePrefix returns an empty non-truncated result for null body and an empty truncated result for non-null bodies without getReader, avoiding arrayBuffer() and text(). (src/infra/http-body.ts:199, 7604a19acd7c)
  • PR head routes the error snippet fallback through the shared helper: The changed no-reader branch calls readResponsePrefix(response, limits.maxBytes) and returns empty when the helper fail-closes. (src/infra/http-error-body.ts:10, 7604a19acd7c)
  • Regression tests cover the repaired edge paths: The updated tests assert no-reader responses do not call arrayBuffer() and null bodies return immediately without invoking arrayBuffer(). (src/infra/http-error-body.test.ts:97, 7604a19acd7c)
  • SDK compatibility surface: readResponseWithLimit is exported through plugin-sdk/response-limit-runtime, so the helper behavior change can affect plugin callers that pass non-standard Response-like objects without a readable stream. (src/plugin-sdk/response-limit-runtime.ts:4, 60f0749b7fb3)
  • Adjacent fail-closed precedent: Current main already has a similar policy in MCP and web helpers: body-less foreign responses and capped no-stream fallbacks avoid text()/arrayBuffer() because whole-body fallbacks cannot honor byte caps. (src/agents/mcp-http-fetch.ts:64, 60f0749b7fb3)

Likely related people:

  • steipete: Blame on the current helper snapshot points to Peter Steinberger, and he merged the adjacent fail-closed web fallback PR that sets the closest policy precedent. (role: recent area contributor and merger; confidence: high; commits: 395fbb8eb631, 3cbcba10cf30, db25e9ec5218; files: src/infra/http-body.ts, src/infra/http-error-body.ts, src/agents/tools/web-shared.ts)
  • Pick-cat: Authored the merged PR that added byte-limit output handling and tests in the same readResponseBodySnippet fallback area, leaving the pre-truncation whole-body allocation as the remaining issue. (role: recent adjacent contributor; confidence: medium; commits: 7c9c2ef0c369, 18a781748394; files: src/infra/http-error-body.ts, src/infra/http-error-body.test.ts)
  • zenglingbiao: Authored the adjacent web-shared bounded response fallback work that moved capped no-stream response reads to a fail-closed shape. (role: adjacent precedent contributor; confidence: medium; commits: db25e9ec5218, b787e74298f4; files: src/agents/tools/web-shared.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.
Review history (3 earlier review cycles)
  • reviewed 2026-07-07T02:30:41.269Z sha 50f4f9db9aaa2e58e5dad87be120074959322823 :: needs real behavior proof before merge. :: [P1] Avoid whole-body fallback reads under maxBytes
  • reviewed 2026-07-07T03:29:42.013Z sha bf5bec6b5ab2f29f691497179058e75cb60bc45a :: needs real behavior proof before merge. :: [P1] Avoid whole-body fallback reads without Content-Length
  • reviewed 2026-07-07T04:16:18.855Z sha f928ff3277748b3eefd0ae9e962528c1290aea85 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. labels Jul 7, 2026
@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed clawsweeper P1 findings. Changes:

  • P1: Added Content-Length guard and null-body early return in readResponsePrefix no-reader fallback — no longer calls arrayBuffer() when Content-Length exceeds maxBytes or body is null
  • P1: Added L2 real behavior proof to PR body (direct function calls with real Response objects)
  • P2 lint: Fixed eslint(curly) causing check-lint CI failure
  • Added 2 regression tests asserting arrayBuffer() is not called in the Content-Length gate and null-body paths

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Fixed check-lint CI: replaced parseInt/isNaN with Number.parseInt/Number.isNaN per oxlint unicorn/prefer-number-properties rule.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The previous re-review request was acknowledged ~15 min ago. CI is all green (71 ✅, check-lint passed). PR body has been updated with L2 terminal proof including Content-Length guard demonstration.

@Pandah97

Pandah97 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed round 2 findings: no-reader fallback now fails closed — returns empty immediately instead of calling arrayBuffer(). Removed the Content-Length guard approach in favor of a simpler fail-closed pattern.

Changes in this round:

  • No-reader readResponsePrefix path returns empty + truncated (never calls whole-body methods)
  • Updated tests to use streaming Response in bounded-read tests
  • Regression test proving arrayBuffer() is never invoked for no-reader responses

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed 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. labels Jul 7, 2026
Pandah97 added 2 commits July 7, 2026 20:18
…treaming fallback

The non-streaming fallback in readResponseBodySnippet called response.text()
without any size limit, buffering the entire response before the maxBytes
check. Switch to readResponsePrefix which caps the read at maxBytes bytes.

The streaming path was already bounded — only the !body.getReader fallback
was vulnerable.

Fixes openclaw#101269
…nt-Length guard

- Add null-body early return in readResponsePrefix to avoid arrayBuffer() call
- Add Content-Length check before arrayBuffer() in non-streaming path
- Export readResponsePrefix from http-body.ts (was private)
- Replace response.text() with readResponsePrefix in readResponseBodySnippet
- Add 2 regression tests for Content-Length gate and null-body short-circuit

Ref. openclaw#101270
Pandah97 added 2 commits July 7, 2026 20:18
… arrayBuffer

Replace the Content-Length guard approach with a simpler fail-closed
strategy: when the response has no ReadableStream reader, return empty
immediately instead of falling back to arrayBuffer()/text(). The
streaming path (which handles all production HTTP responses in Node.js
undici fetch) is unchanged.

- Remove arrayBuffer() fallback from readResponsePrefix no-reader branch
- Rewrite body-less path tests to use streaming Response with Blob
- Add regression test asserting no-reader path never calls arrayBuffer()

Ref. openclaw#101270
@barnacle-openclaw

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@barnacle-openclaw barnacle-openclaw Bot added the stale Marked as stale due to inactivity label Jul 22, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[infra] readResponseBodySnippet non-streaming fallback reads entire response without size bound

1 participant