From ae9ee3cb50c3ba6b903ea7f1eb5a740793a22fed Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 03:28:22 +0000 Subject: [PATCH 1/3] fetch: reject already-used Request stream bodies before connecting fetch(request) where request has a ReadableStream body that was already consumed would open a TCP connection and write the full request head (POST /path HTTP/1.1 + Transfer-Encoding: chunked) before rejecting with ERR_STREAM_CANNOT_PIPE. Each retry left a half-open, unterminated chunked request at the origin. The pre-flight body check in fetch_impl consulted PendingValue::is_disturbed, which looks at body_get_cached (only populated once .body is accessed) and Locked.readable, but check_body_stream_ref had already migrated the stream out of Locked.readable into the JS stream cache slot. So the disturbed stream was never found until ResumableSink::init_exact_refs ran, after the head was on the wire. Check is_disturbed/is_locked on the actual ReadableStream returned by get_body_readable_stream (which consults the stream cache slot) before wrapping it as the request body, so the TypeError is thrown before any I/O. This matches the spec unusable check used by Request.clone() and node/undici. --- src/runtime/webcore/fetch.rs | 8 ++ test/js/web/fetch/body-mixin-errors.test.ts | 105 ++++++++++++++++++++ 2 files changed, 113 insertions(+) diff --git a/src/runtime/webcore/fetch.rs b/src/runtime/webcore/fetch.rs index ac3ac65e8112..bebeb7234f40 100644 --- a/src/runtime/webcore/fetch.rs +++ b/src/runtime/webcore/fetch.rs @@ -1237,6 +1237,14 @@ fn fetch_impl( if matches!(*body_value, BodyValue::Locked(_)) { if let Some(readable) = req.get_body_readable_stream(global_this) { + if readable.is_disturbed(global_this) || readable.is_locked(global_this) { + return Err(global_this + .err( + jsc::ErrorCode::BODY_ALREADY_USED, + format_args!("Request body already used"), + ) + .throw()); + } break 'extract_body Some(HTTPRequestBody::ReadableStream( readable_stream::Strong::init(readable, global_this), )); diff --git a/test/js/web/fetch/body-mixin-errors.test.ts b/test/js/web/fetch/body-mixin-errors.test.ts index f322a7ee32b2..88dbcb86963f 100644 --- a/test/js/web/fetch/body-mixin-errors.test.ts +++ b/test/js/web/fetch/body-mixin-errors.test.ts @@ -130,4 +130,109 @@ describe("body-mixin-errors", () => { }); }, ); + + it.concurrent( + "fetch: re-fetching a Request whose stream body was consumed rejects before any network I/O", + async () => { + let connections = 0; + const sockets: net.Socket[] = []; + const server = net.createServer(socket => { + connections++; + sockets.push(socket); + let buf = Buffer.alloc(0); + socket.on("data", d => { + buf = Buffer.concat([buf, d]); + if (buf.toString("latin1").endsWith("\r\n0\r\n\r\n")) { + socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); + } + }); + socket.on("error", () => {}); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as net.AddressInfo; + const url = `http://127.0.0.1:${port}/up`; + + try { + const makeBody = () => + new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("hello")); + c.close(); + }, + }); + const req = new Request(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); + + const first = await fetch(req); + expect(first.status).toBe(200); + expect(req.bodyUsed).toBe(true); + + const errors: unknown[] = []; + for (let i = 0; i < 3; i++) { + await fetch(req).then( + () => errors.push(null), + e => errors.push(e), + ); + } + + // Probe with a fresh body so every accept queued before this one has + // been delivered by the time the response arrives. + const probe = await fetch(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); + expect(probe.status).toBe(200); + + // First fetch + probe only. The three re-fetches must not have opened + // connections or written request heads to the origin. + expect(connections).toBe(2); + + expect(errors).toHaveLength(3); + for (const e of errors) { + expect(e).toBeInstanceOf(TypeError); + expect((e as any).code).toBe("ERR_BODY_ALREADY_USED"); + } + } finally { + for (const s of sockets) s.destroy(); + server.close(); + } + }, + ); + + it.concurrent("fetch: Request with a locked stream body rejects before any network I/O", async () => { + let connections = 0; + const sockets: net.Socket[] = []; + const server = net.createServer(socket => { + connections++; + sockets.push(socket); + socket.resume(); + socket.on("error", () => {}); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as net.AddressInfo; + const url = `http://127.0.0.1:${port}/up`; + + try { + const rs = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("hello")); + c.close(); + }, + }); + const req = new Request(url, { method: "POST", body: rs, duplex: "half" } as RequestInit); + // Lock the stream without disturbing it. + req.body!.getReader(); + expect(req.bodyUsed).toBe(false); + + let err: unknown; + await fetch(req).then( + () => expect.unreachable("fetch should reject for a locked body"), + e => (err = e), + ); + expect(err).toBeInstanceOf(TypeError); + expect((err as any).code).toBe("ERR_BODY_ALREADY_USED"); + expect(connections).toBe(0); + } finally { + for (const s of sockets) s.destroy(); + server.close(); + } + }); }); From c4d6191677b83070432d5d5edd61fe7fdd6feb54 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 03:48:22 +0000 Subject: [PATCH 2/3] test: add probe barrier to locked-body connection assertion Mirrors the sibling test so the 'no network I/O' claim can actually fail on a regressed build (the server's connection callback can lag the fetch rejection otherwise). --- test/js/web/fetch/body-mixin-errors.test.ts | 33 +++++++++++++++------ 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/test/js/web/fetch/body-mixin-errors.test.ts b/test/js/web/fetch/body-mixin-errors.test.ts index 88dbcb86963f..6f799356bce0 100644 --- a/test/js/web/fetch/body-mixin-errors.test.ts +++ b/test/js/web/fetch/body-mixin-errors.test.ts @@ -202,7 +202,13 @@ describe("body-mixin-errors", () => { const server = net.createServer(socket => { connections++; sockets.push(socket); - socket.resume(); + let buf = Buffer.alloc(0); + socket.on("data", d => { + buf = Buffer.concat([buf, d]); + if (buf.toString("latin1").endsWith("\r\n0\r\n\r\n")) { + socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); + } + }); socket.on("error", () => {}); }); server.listen(0, "127.0.0.1"); @@ -211,13 +217,14 @@ describe("body-mixin-errors", () => { const url = `http://127.0.0.1:${port}/up`; try { - const rs = new ReadableStream({ - start(c) { - c.enqueue(new TextEncoder().encode("hello")); - c.close(); - }, - }); - const req = new Request(url, { method: "POST", body: rs, duplex: "half" } as RequestInit); + const makeBody = () => + new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("hello")); + c.close(); + }, + }); + const req = new Request(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); // Lock the stream without disturbing it. req.body!.getReader(); expect(req.bodyUsed).toBe(false); @@ -227,9 +234,17 @@ describe("body-mixin-errors", () => { () => expect.unreachable("fetch should reject for a locked body"), e => (err = e), ); + + // Probe with a fresh body so every accept queued before this one has + // been delivered by the time the response arrives. + const probe = await fetch(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); + expect(probe.status).toBe(200); + + // Probe only. The rejected fetch must not have opened a connection. + expect(connections).toBe(1); + expect(err).toBeInstanceOf(TypeError); expect((err as any).code).toBe("ERR_BODY_ALREADY_USED"); - expect(connections).toBe(0); } finally { for (const s of sockets) s.destroy(); server.close(); From 5739a2efa37a32b0ca5c68741c8bcd70c04cd04c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 31 Jul 2026 04:06:38 +0000 Subject: [PATCH 3/3] test: extract withConnectionCountingServer helper Deduplicates the server/probe scaffolding shared by the two stream-body pre-flight tests, matching the withTruncatedBodyServer pattern already used in this file. --- test/js/web/fetch/body-mixin-errors.test.ts | 132 +++++++++----------- 1 file changed, 58 insertions(+), 74 deletions(-) diff --git a/test/js/web/fetch/body-mixin-errors.test.ts b/test/js/web/fetch/body-mixin-errors.test.ts index 6f799356bce0..ac5d747effc9 100644 --- a/test/js/web/fetch/body-mixin-errors.test.ts +++ b/test/js/web/fetch/body-mixin-errors.test.ts @@ -131,36 +131,62 @@ describe("body-mixin-errors", () => { }, ); + // Counts inbound TCP connections on a server that answers a chunked POST + // once it sees the 0\r\n\r\n terminator. `expectConnections(n)` first sends + // a probe request so every accept queued before it has been delivered by the + // time the response arrives, then asserts the total (including the probe). + async function withConnectionCountingServer( + fn: (ctx: { + url: string; + makeBody: () => ReadableStream; + expectConnections: (n: number) => Promise; + }) => Promise, + ): Promise { + let connections = 0; + const sockets: net.Socket[] = []; + const server = net.createServer(socket => { + connections++; + sockets.push(socket); + let buf = Buffer.alloc(0); + socket.on("data", d => { + buf = Buffer.concat([buf, d]); + if (buf.toString("latin1").endsWith("\r\n0\r\n\r\n")) { + socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); + } + }); + socket.on("error", () => {}); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const { port } = server.address() as net.AddressInfo; + const url = `http://127.0.0.1:${port}/up`; + const makeBody = () => + new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode("hello")); + c.close(); + }, + }); + try { + await fn({ + url, + makeBody, + expectConnections: async n => { + const probe = await fetch(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); + expect(probe.status).toBe(200); + expect(connections).toBe(n); + }, + }); + } finally { + for (const s of sockets) s.destroy(); + await new Promise(r => server.close(() => r())); + } + } + it.concurrent( "fetch: re-fetching a Request whose stream body was consumed rejects before any network I/O", async () => { - let connections = 0; - const sockets: net.Socket[] = []; - const server = net.createServer(socket => { - connections++; - sockets.push(socket); - let buf = Buffer.alloc(0); - socket.on("data", d => { - buf = Buffer.concat([buf, d]); - if (buf.toString("latin1").endsWith("\r\n0\r\n\r\n")) { - socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); - } - }); - socket.on("error", () => {}); - }); - server.listen(0, "127.0.0.1"); - await once(server, "listening"); - const { port } = server.address() as net.AddressInfo; - const url = `http://127.0.0.1:${port}/up`; - - try { - const makeBody = () => - new ReadableStream({ - start(c) { - c.enqueue(new TextEncoder().encode("hello")); - c.close(); - }, - }); + await withConnectionCountingServer(async ({ url, makeBody, expectConnections }) => { const req = new Request(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); const first = await fetch(req); @@ -175,55 +201,21 @@ describe("body-mixin-errors", () => { ); } - // Probe with a fresh body so every accept queued before this one has - // been delivered by the time the response arrives. - const probe = await fetch(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); - expect(probe.status).toBe(200); - // First fetch + probe only. The three re-fetches must not have opened // connections or written request heads to the origin. - expect(connections).toBe(2); + await expectConnections(2); expect(errors).toHaveLength(3); for (const e of errors) { expect(e).toBeInstanceOf(TypeError); expect((e as any).code).toBe("ERR_BODY_ALREADY_USED"); } - } finally { - for (const s of sockets) s.destroy(); - server.close(); - } + }); }, ); it.concurrent("fetch: Request with a locked stream body rejects before any network I/O", async () => { - let connections = 0; - const sockets: net.Socket[] = []; - const server = net.createServer(socket => { - connections++; - sockets.push(socket); - let buf = Buffer.alloc(0); - socket.on("data", d => { - buf = Buffer.concat([buf, d]); - if (buf.toString("latin1").endsWith("\r\n0\r\n\r\n")) { - socket.end("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); - } - }); - socket.on("error", () => {}); - }); - server.listen(0, "127.0.0.1"); - await once(server, "listening"); - const { port } = server.address() as net.AddressInfo; - const url = `http://127.0.0.1:${port}/up`; - - try { - const makeBody = () => - new ReadableStream({ - start(c) { - c.enqueue(new TextEncoder().encode("hello")); - c.close(); - }, - }); + await withConnectionCountingServer(async ({ url, makeBody, expectConnections }) => { const req = new Request(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); // Lock the stream without disturbing it. req.body!.getReader(); @@ -235,19 +227,11 @@ describe("body-mixin-errors", () => { e => (err = e), ); - // Probe with a fresh body so every accept queued before this one has - // been delivered by the time the response arrives. - const probe = await fetch(url, { method: "POST", body: makeBody(), duplex: "half" } as RequestInit); - expect(probe.status).toBe(200); - // Probe only. The rejected fetch must not have opened a connection. - expect(connections).toBe(1); + await expectConnections(1); expect(err).toBeInstanceOf(TypeError); expect((err as any).code).toBe("ERR_BODY_ALREADY_USED"); - } finally { - for (const s of sockets) s.destroy(); - server.close(); - } + }); }); });