Skip to content

Commit a86e526

Browse files
lsr911claude
andcommitted
fix(infra): fail closed in readResponseBodySnippet non-streaming fallback
Per ClawSweeper review: the previous fix still awaited response.text() before applying maxBytes, so a large non-streaming response body was still fully materialized in memory first. Replace the whole-body fallback with a fail-closed return of "" — when no body reader is available, return empty rather than risk OOM. Co-Authored-By: Claude <[email protected]>
1 parent 3d2f218 commit a86e526

2 files changed

Lines changed: 59 additions & 74 deletions

File tree

‎src/infra/http-error-body.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@ export async function readResponseBodySnippet(
55
try {
66
const body = response.body;
77
if (!body || typeof body.getReader !== "function") {
8-
const text = await response.text();
9-
const encoded = new TextEncoder().encode(text);
10-
const bounded =
11-
encoded.length > limits.maxBytes ? encoded.subarray(0, limits.maxBytes) : encoded;
12-
// subarray may cut mid-codepoint; strip trailing U+FFFD artifacts
13-
return new TextDecoder().decode(bounded).replace(/�+$/, "").slice(0, limits.maxChars);
8+
// Fail closed when no reader is available: calling response.text()
9+
// would buffer the full body before maxBytes can be applied, so
10+
// return an empty snippet rather than risk OOM on large bodies.
11+
return "";
1412
}
1513

1614
const reader = body.getReader();

‎test/_proof_response_body_snippet_bound.mts‎

Lines changed: 55 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
/**
2-
* Real behavior proof: readResponseBodySnippet maxBytes enforcement.
2+
* Real behavior proof: readResponseBodySnippet fail-closed fallback.
33
*
4-
* Calls the actual readResponseBodySnippet with a mock Response whose body
5-
* is null (simulating non-streaming / mocked transports), exercising the
6-
* fixed fallback path that now encodes → bounds → decodes instead of
7-
* buffering the entire response.text() without a byte limit.
4+
* When the response body has no reader (non-streaming/mocked responses),
5+
* the function now returns "" instead of calling response.text() which
6+
* would buffer the full body before maxBytes can be applied.
87
*
98
* Usage: node --import tsx test/_proof_response_body_snippet_bound.mts
109
*/
@@ -22,69 +21,65 @@ function check(label: string, ok: boolean, detail = "") {
2221
}
2322
}
2423

25-
/** Mock Response-like object with no body reader (hits the fallback). */
24+
/** Mock Response with null body — hits the fail-closed fallback. */
2625
function nonStreamingMock(bodyText: string): Response {
2726
return {
2827
body: null,
2928
text: async () => bodyText,
3029
} as unknown as Response;
3130
}
3231

33-
/** Real ReadableStream-backed Response (hits the streaming path). */
32+
/** ReadableStream-backed Response — hits the bounded streaming path. */
3433
function streamingResponse(bodyText: string): Response {
3534
const encoded = new TextEncoder().encode(bodyText);
36-
const stream = new ReadableStream({
37-
start(controller) {
38-
controller.enqueue(encoded);
39-
controller.close();
40-
},
41-
});
42-
return new Response(stream, {
43-
status: 400,
44-
headers: { "content-type": "text/plain" },
45-
});
35+
return new Response(
36+
new ReadableStream({
37+
start(controller) {
38+
controller.enqueue(encoded);
39+
controller.close();
40+
},
41+
}),
42+
{ status: 400, headers: { "content-type": "text/plain" } },
43+
);
4644
}
4745

4846
async function proof() {
49-
const { readResponseBodySnippet } =
50-
await import("../src/infra/http-error-body.js");
47+
const { readResponseBodySnippet } = await import(
48+
"../src/infra/http-error-body.js"
49+
);
5150

52-
// ── Non-streaming: body exceeds maxBytes ──
51+
// ── Non-streaming: fails closed, returns "" ──
5352
const largeBody = "x".repeat(10_000);
54-
const limits = { maxBytes: 200, maxChars: 500 };
5553
const nonStreamingRes = nonStreamingMock(largeBody);
56-
const snippet = await readResponseBodySnippet(nonStreamingRes, limits);
57-
58-
check(
59-
"non-streaming: snippet ≤ maxChars",
60-
snippet.length <= limits.maxChars,
61-
`len=${snippet.length} max=${limits.maxChars}`,
62-
);
63-
const byteLen = new TextEncoder().encode(snippet).length;
54+
const snippet = await readResponseBodySnippet(nonStreamingRes, {
55+
maxBytes: 200,
56+
maxChars: 500,
57+
});
6458
check(
65-
"non-streaming: byte length ≤ maxBytes",
66-
byteLen <= limits.maxBytes,
67-
`bytes=${byteLen} max=${limits.maxBytes}`,
59+
"non-streaming fail-closed: returns empty string",
60+
snippet === "",
61+
`len=${snippet.length}`,
6862
);
6963

70-
// ── Non-streaming: small body passes through ──
71-
const smallBody = "hello";
72-
const smallRes = nonStreamingMock(smallBody);
64+
// ── Non-streaming: even small bodies fail closed ──
65+
const smallRes = nonStreamingMock("hello");
7366
const smallSnippet = await readResponseBodySnippet(smallRes, {
7467
maxBytes: 10_000,
7568
maxChars: 10_000,
7669
});
7770
check(
78-
"non-streaming small: passes through",
79-
smallSnippet === smallBody,
71+
"non-streaming small: also returns empty (fail-closed)",
72+
smallSnippet === "",
8073
`got="${smallSnippet}"`,
8174
);
8275

8376
// ── Streaming: body exceeds maxBytes ──
8477
const largeStreamingBody = "y".repeat(10_000);
85-
const streamingRes = streamingResponse(largeStreamingBody);
86-
const streamSnippet = await readResponseBodySnippet(streamingRes, limits);
87-
78+
const limits = { maxBytes: 200, maxChars: 500 };
79+
const streamSnippet = await readResponseBodySnippet(
80+
streamingResponse(largeStreamingBody),
81+
limits,
82+
);
8883
check(
8984
"streaming: snippet ≤ maxChars",
9085
streamSnippet.length <= limits.maxChars,
@@ -97,50 +92,42 @@ async function proof() {
9792
`bytes=${streamByteLen} max=${limits.maxBytes}`,
9893
);
9994

100-
// ── Streaming: small body ──
101-
const smallStreamRes = streamingResponse("world");
102-
const smallStreamSnippet = await readResponseBodySnippet(smallStreamRes, {
103-
maxBytes: 10_000,
104-
maxChars: 10_000,
105-
});
95+
// ── Streaming: small body passes through ──
96+
const smallStreamSnippet = await readResponseBodySnippet(
97+
streamingResponse("world"),
98+
{ maxBytes: 10_000, maxChars: 10_000 },
99+
);
106100
check(
107101
"streaming small: passes through",
108102
smallStreamSnippet === "world",
109103
`got="${smallStreamSnippet}"`,
110104
);
111105

112-
// ── Multibyte CJK not corrupted by byte-boundary truncation ──
113-
const cjkBody = "啊".repeat(500); // 3 bytes each in UTF-8
114-
const cjkLimits = { maxBytes: 15, maxChars: 100 };
115-
const cjkNonStreamingRes = nonStreamingMock(cjkBody);
116-
const cjkSnippet = await readResponseBodySnippet(
117-
cjkNonStreamingRes,
118-
cjkLimits,
106+
// ── Streaming: multibyte CJK not corrupted ──
107+
const cjkStreamSnippet = await readResponseBodySnippet(
108+
streamingResponse("啊".repeat(500)),
109+
{ maxBytes: 15, maxChars: 100 },
119110
);
120-
const cjkByteLen = new TextEncoder().encode(cjkSnippet).length;
111+
const cjkByteLen = new TextEncoder().encode(cjkStreamSnippet).length;
121112
check(
122-
"multibyte non-streaming: bytes ≤ maxBytes",
123-
cjkByteLen <= cjkLimits.maxBytes,
124-
`bytes=${cjkByteLen} max=${cjkLimits.maxBytes}`,
113+
"streaming multibyte: bytes ≤ maxBytes",
114+
cjkByteLen <= 15,
115+
`bytes=${cjkByteLen} max=15`,
125116
);
126117
check(
127-
"multibyte non-streaming: chars ≤ maxChars",
128-
cjkSnippet.length <= cjkLimits.maxChars,
129-
`chars=${cjkSnippet.length} max=${cjkLimits.maxChars}`,
118+
"streaming multibyte: chars ≤ maxChars",
119+
cjkStreamSnippet.length <= 100,
120+
`chars=${cjkStreamSnippet.length} max=100`,
130121
);
131-
// subarray may split a multibyte character; the decoder replaces that
132-
// trailing fragment with U+FFFD (�). Verify we strip it.
133122
check(
134-
"multibyte non-streaming: no replacement character",
135-
!cjkSnippet.includes("�"),
136-
`snippet="${cjkSnippet}"`,
123+
"streaming multibyte: no replacement char",
124+
!cjkStreamSnippet.includes("�"),
125+
`snippet="${cjkStreamSnippet}"`,
137126
);
138127
}
139128

140129
async function main() {
141-
console.log(
142-
`node --import tsx test/_proof_response_body_snippet_bound.mts\n`,
143-
);
130+
console.log(`node --import tsx test/_proof_response_body_snippet_bound.mts\n`);
144131
await proof();
145132
console.log(`\n[proof] ${pass} PASS, ${fail} FAIL`);
146133
if (fail > 0) process.exit(1);

0 commit comments

Comments
 (0)