From 588ee95ddca53c35f572ef93a83387c2ef583de5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:12:47 +0000 Subject: [PATCH 01/14] Validate GET/HEAD bodies in new Request() and statusText in new Response() new Request() now throws a TypeError when the method is GET or HEAD and the body is not null or empty, the same check fetch() already has. new Response(), Response.json() and Response.redirect() now throw a TypeError when statusText contains a code unit outside the reason-phrase production (HTAB, 0x20-0x7E, 0x80-0xFF). Tests that built a Request with a body and the default GET method now pass method: "POST". --- src/runtime/webcore/Request.rs | 10 ++++ src/runtime/webcore/Response.rs | 32 ++++++++++- .../js/bun/http/async-iterator-stream.test.ts | 2 +- test/js/bun/util/heap-snapshot.test.ts | 1 + test/js/web/fetch/body-clone.test.ts | 7 ++- test/js/web/fetch/fetch.test.ts | 9 ++- test/js/web/fetch/response.test.ts | 49 ++++++++++++++++- test/js/web/fetch/utf8-bom.test.ts | 3 + test/js/web/html/FormData.test.ts | 12 +++- test/js/web/request/request.test.ts | 55 +++++++++++++++++++ test/js/web/streams/streams.test.js | 2 +- 11 files changed, 170 insertions(+), 12 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 8ceaadd119dd..d2660771a2da 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1398,6 +1398,16 @@ impl Request { req.url.set(href); + // Fetch spec `new Request()` step 36. `fetch()` has the same check in + // `fetch_impl`, and an empty string body counts as no body in both. + if matches!(req.method, Method::GET | Method::HEAD) + && !matches!(req.body_value(), BodyValue::Null | BodyValue::Empty) + { + bail!(Err(global_this.throw_type_error(format_args!( + "Request with GET/HEAD method cannot have body." + )))); + } + if matches!(req.body_value(), BodyValue::Blob(_)) && req.headers.get().is_some() { if let BodyValue::Blob(blob) = req.body_value() { let ct: &[u8] = blob.content_type_slice(); diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 679a8137ec92..0fac50a718ed 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -922,6 +922,7 @@ impl Response { }); } else { if let Some(init) = Init::init(global_this, arg_init)? { + init.validate_status_text(global_this)?; response.init.set(init); } } @@ -1003,6 +1004,7 @@ impl Response { response.init.with_mut(|i| i.status_code = status); } else if let Some(init) = Init::init(global_this, arg_init)? { // cleanup is handled by Init's drop glue on `?` below + init.validate_status_text(global_this)?; response.init.set(init); let status = response.init.get().status_code; @@ -1128,7 +1130,9 @@ impl Response { }; } if arguments[1].is_object() { - break 'brk Init::init(global_this, arguments[1])?.expect("unreachable"); + let init = Init::init(global_this, arguments[1])?.expect("unreachable"); + init.validate_status_text(global_this)?; + break 'brk init; } return Err(global_this.throw_invalid_arguments(format_args!( "Failed to construct 'Response': The provided body value is not of type 'ResponseInit'", @@ -1320,6 +1324,32 @@ impl Init { Ok(Some(result)) } + + /// Fetch spec: `ResponseInit["statusText"]` must match the `reason-phrase` + /// production (HTAB, SP / VCHAR 0x20-0x7E, obs-text 0x80-0xFF). Only the + /// `Response` constructors call this: `Request` also parses its init + /// through `Init::init` and ignores `statusText`. + pub(crate) fn validate_status_text(&self, global_this: &JSGlobalObject) -> JsResult<()> { + fn is_reason_phrase_unit(c: u32) -> bool { + c == 0x09 || (0x20..=0x7E).contains(&c) || (0x80..=0xFF).contains(&c) + } + let status_text = &self.status_text; + let valid = if status_text.is_utf16() { + status_text + .utf16() + .iter() + .all(|&c| is_reason_phrase_unit(u32::from(c))) + } else { + status_text + .byte_slice() + .iter() + .all(|&c| is_reason_phrase_unit(u32::from(c))) + }; + if valid { + return Ok(()); + } + Err(global_this.throw_type_error(format_args!("Invalid statusText"))) + } } // https://developer.mozilla.org/en-US/docs/Web/API/Headers diff --git a/test/js/bun/http/async-iterator-stream.test.ts b/test/js/bun/http/async-iterator-stream.test.ts index 537f30cc3000..869d7cc4306e 100644 --- a/test/js/bun/http/async-iterator-stream.test.ts +++ b/test/js/bun/http/async-iterator-stream.test.ts @@ -332,7 +332,7 @@ describe.concurrent("Streaming body via", () => { for (let bodyInit of [fn, { [Symbol.asyncIterator]: fn }] as const) { for (let [label, constructFn] of [ ["Response", () => new Response(bodyInit)], - ["Request", () => new Request({ "url": "https://example.com", body: bodyInit })], + ["Request", () => new Request({ "url": "https://example.com", method: "POST", body: bodyInit })], ]) { for (let method of ["arrayBuffer", "bytes", "text"]) { test(`${label}(${method})`, async () => { diff --git a/test/js/bun/util/heap-snapshot.test.ts b/test/js/bun/util/heap-snapshot.test.ts index 12bc18ca8cc9..5b8d481a9490 100644 --- a/test/js/bun/util/heap-snapshot.test.ts +++ b/test/js/bun/util/heap-snapshot.test.ts @@ -34,6 +34,7 @@ describe("Native types report their size correctly", () => { it("Request", () => { var request = new Request("https://example.com", { + method: "POST", body: Buffer.alloc(1024 * 1024 * 2, "yoo"), }); globalThis.request = request; diff --git a/test/js/web/fetch/body-clone.test.ts b/test/js/web/fetch/body-clone.test.ts index 2b1a40941e22..d631f9c86f71 100644 --- a/test/js/web/fetch/body-clone.test.ts +++ b/test/js/web/fetch/body-clone.test.ts @@ -1050,9 +1050,10 @@ test("new Request(src, init) with a user ReadableStream body: both derived and s const twoArg = new Request(twoArgSrc, { headers: { "x-a": "1" } }); const oneArgSrc = make(); const oneArg = new Request(oneArgSrc); - // Bun extension: a Response as the second argument contributes its body via - // the sibling Response-source branch in construct_into. - const responseSrc = new Response(stream()); + // Bun extension: a Response as the second argument contributes its body and + // method via the sibling Response-source branch in construct_into. + // @ts-expect-error method is a Bun extension on ResponseInit + const responseSrc = new Response(stream(), { method: "POST" }); // @ts-expect-error Bun accepts a Response as init const fromResponse = new Request("http://example.com/", responseSrc); expect({ diff --git a/test/js/web/fetch/fetch.test.ts b/test/js/web/fetch/fetch.test.ts index 74d9b469f0f5..59d26fc76e76 100644 --- a/test/js/web/fetch/fetch.test.ts +++ b/test/js/web/fetch/fetch.test.ts @@ -1269,7 +1269,11 @@ describe("Blob", () => { const data = new TypedArray(sample); if (withGC) gc(); const input = - Constructor === Blob ? [data] : Constructor === Request ? { body: data, url: "http://example.com" } : data; + Constructor === Blob + ? [data] + : Constructor === Request + ? { body: data, url: "http://example.com", method: "POST" } + : data; if (withGC) gc(); const blob = new Constructor(input as any); if (withGC) gc(); @@ -1596,6 +1600,7 @@ describe("Request", () => { it("clone", async () => { gc(); var body = new Request("https://hello.com", { + method: "POST", headers: { "content-type": "text/html; charset=utf-8", }, @@ -1654,7 +1659,7 @@ describe("Request", () => { expect(cloned.signal.aborted).toBe(true); }); - testBlobInterface(data => new Request("https://hello.com", { body: data }), true); + testBlobInterface(data => new Request("https://hello.com", { method: "POST", body: data }), true); }); describe("Headers", () => { diff --git a/test/js/web/fetch/response.test.ts b/test/js/web/fetch/response.test.ts index a4e286172358..03b54de1e9e9 100644 --- a/test/js/web/fetch/response.test.ts +++ b/test/js/web/fetch/response.test.ts @@ -49,7 +49,7 @@ describe("2-arg form", () => { test("print size", () => { expect(normalizeBunSnapshot(Bun.inspect(new Response(Bun.file(import.meta.filename)))), import.meta.dir) .toMatchInlineSnapshot(` - "Response (8.0 KB) { + "Response (9.87 KB) { ok: true, url: "", status: 200, @@ -144,6 +144,53 @@ test("new Response(123, { statusText: 123 }) does not throw", () => { expect(new Response("123", { statusText: 123 }).statusText).toBe("123"); }); +// https://github.com/oven-sh/bun/issues/42499 +describe("statusText reason-phrase validation", () => { + const invalid: [string, string][] = [ + ["CR LF", "a\r\nb"], + ["LF", "a\nb"], + ["CR", "a\rb"], + ["NUL", "a\0b"], + ["DEL", "a\x7fb"], + ["control byte", "a\x01b"], + ["non-Latin-1 code unit", "a\u0100b"], + ["NUL in a UTF-16 string", "\u00ff\u0100\0"], + ]; + + test.each(invalid)("new Response() rejects %s", (_name, statusText) => { + expect(() => new Response(null, { statusText })).toThrow(new TypeError("Invalid statusText")); + expect(() => new Response("body", { status: 201, statusText })).toThrow(new TypeError("Invalid statusText")); + }); + + test.each(invalid)("Response.json() rejects %s", (_name, statusText) => { + expect(() => Response.json({ a: 1 }, { statusText })).toThrow(new TypeError("Invalid statusText")); + }); + + test.each(invalid)("Response.redirect() rejects %s", (_name, statusText) => { + expect(() => Response.redirect("http://example.com/", { status: 301, statusText })).toThrow( + new TypeError("Invalid statusText"), + ); + }); + + test("a status out of range is reported before an invalid statusText", () => { + expect(() => new Response(null, { status: 600, statusText: "a\nb" })).toThrow(RangeError); + }); + + test.each([ + ["HTAB and SP", "a\tb c"], + ["VCHAR range", " !\"#$%&'()*+,-./0123456789:;<=>?@ABCXYZ[\\]^_`abcxyz{|}~"], + ["obs-text", "\u0080\u00a9\u00ff"], + ["empty", ""], + ])("new Response() keeps %s", (_name, statusText) => { + expect(new Response(null, { statusText }).statusText).toBe(statusText); + expect(Response.json(1, { statusText }).statusText).toBe(statusText); + }); + + test("new Request() ignores statusText", () => { + expect(() => new Request("http://example.com/", { statusText: "a\nb" } as RequestInit)).not.toThrow(); + }); +}); + test("new Response(123, { method: 456 }) does not throw", () => { // @ts-expect-error expect(() => new Response("123", { method: 456 })).not.toThrow(); diff --git a/test/js/web/fetch/utf8-bom.test.ts b/test/js/web/fetch/utf8-bom.test.ts index 08d5023775f2..764515034211 100644 --- a/test/js/web/fetch/utf8-bom.test.ts +++ b/test/js/web/fetch/utf8-bom.test.ts @@ -76,6 +76,7 @@ describe("UTF-8 BOM should be ignored", () => { describe("Request", () => { it("in text()", async () => { const request = new Request("https://example.com", { + method: "POST", body: Buffer.from("\uFEFFHello, World!"), headers: { "content-type": "text/plain" }, }); @@ -84,6 +85,7 @@ describe("UTF-8 BOM should be ignored", () => { it("in json()", async () => { const request = new Request("https://example.com", { + method: "POST", body: Buffer.from('\uFEFF{"hello":"World"}'), headers: { "content-type": "application/json" }, }); @@ -92,6 +94,7 @@ describe("UTF-8 BOM should be ignored", () => { it("in formData()", async () => { const request = new Request("https://example.com", { + method: "POST", body: Buffer.from("\uFEFFhello=world"), headers: { "content-type": "application/x-www-form-urlencoded" }, }); diff --git a/test/js/web/html/FormData.test.ts b/test/js/web/html/FormData.test.ts index 311852c31eaa..1190d6364a4e 100644 --- a/test/js/web/html/FormData.test.ts +++ b/test/js/web/html/FormData.test.ts @@ -163,7 +163,9 @@ describe("FormData", () => { for (const C of Class) { it(`should parse multipart/form-data (${name}) with ${C.name}`, async () => { const response = - C === Response ? new Response(body, { headers }) : new Request({ headers, body, url: "http://hello.com" }); + C === Response + ? new Response(body, { headers }) + : new Request({ headers, body, url: "http://hello.com", method: "POST" }); const formData = await response.formData(); expect(formData instanceof FormData).toBe(true); const entry: { [k: string]: any } = {}; @@ -192,7 +194,9 @@ describe("FormData", () => { it(`should roundtrip multipart/form-data (${name}) with ${C.name}`, async () => { const response = - C === Response ? new Response(body, { headers }) : new Request({ headers, body, url: "http://hello.com" }); + C === Response + ? new Response(body, { headers }) + : new Request({ headers, body, url: "http://hello.com", method: "POST" }); const formData = await response.formData(); expect(formData instanceof FormData).toBe(true); @@ -584,7 +588,9 @@ describe("FormData", () => { const formData = new FormData(); formData.append("foo", Bun.file(path)); const response = - C === Response ? new Response(formData) : new Request({ body: formData, url: "http://example.com" }); + C === Response + ? new Response(formData) + : new Request({ body: formData, url: "http://example.com", method: "POST" }); expect(response.headers.get("content-type")?.startsWith("multipart/form-data;")).toBe(true); const formData2 = await response.formData(); diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index 85e42bf8e420..389ef35d4d90 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -76,6 +76,61 @@ test("clone() does not lock original body when body was accessed before clone", expect(clonedText).toBe("Hello, world!"); }); +// https://github.com/oven-sh/bun/issues/42499 +describe("new Request() with a GET/HEAD method and a body", () => { + const message = "Request with GET/HEAD method cannot have body."; + + test.each(["GET", "HEAD", "get", "head"])("method %s with a string body throws TypeError", method => { + expect(() => new Request("http://example.com/", { method, body: "x" })).toThrow(new TypeError(message)); + }); + + test("default method with a body throws TypeError", () => { + expect(() => new Request("http://example.com/", { body: "x" })).toThrow(new TypeError(message)); + }); + + test.each([ + ["Uint8Array", () => new Uint8Array([1])], + ["Blob", () => new Blob(["x"])], + ["ReadableStream", () => new ReadableStream()], + ["URLSearchParams", () => new URLSearchParams("a=1")], + [ + "FormData", + () => { + const fd = new FormData(); + fd.set("a", "1"); + return fd; + }, + ], + ])("GET with a %s body throws TypeError", (_name, body) => { + expect(() => new Request("http://example.com/", { method: "GET", body: body() })).toThrow(new TypeError(message)); + }); + + test("a POST input Request combined with method GET throws TypeError", () => { + const post = new Request("http://example.com/", { method: "POST", body: "x" }); + expect(() => new Request(post, { method: "GET" })).toThrow(new TypeError(message)); + // The failed construction does not consume the input body. + expect(post.bodyUsed).toBe(false); + }); + + test("an invalid URL wins over the body check", () => { + expect(() => new Request("not a url", { method: "GET", body: "x" })).toThrow(/Invalid URL/); + }); + + test("a null, undefined or empty body is accepted", async () => { + expect(new Request("http://example.com/", { method: "GET", body: null }).body).toBeNull(); + expect(new Request("http://example.com/", { method: "HEAD", body: undefined }).body).toBeNull(); + // fetch() treats an empty string as no body. The constructor does the same. + expect(await new Request("http://example.com/", { method: "GET", body: "" }).text()).toBe(""); + }); + + test("other methods keep their body", async () => { + for (const method of ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) { + const request = new Request("http://example.com/", { method, body: "x" }); + expect(await request.text()).toBe("x"); + } + }); +}); + describe("RequestInit signal presence", () => { // Fetch spec step 27: "If init['signal'] exists, then set signal to it." // A present `signal: null` must replace (detach from) the input Request's signal. diff --git a/test/js/web/streams/streams.test.js b/test/js/web/streams/streams.test.js index 55902077cad3..9715ff298914 100644 --- a/test/js/web/streams/streams.test.js +++ b/test/js/web/streams/streams.test.js @@ -514,7 +514,7 @@ it("new Request({body: stream}).body", async () => { }, cancel() {}, }); - var response = new Request({ body: stream, url: "https://example.com" }); + var response = new Request({ method: "POST", body: stream, url: "https://example.com" }); expect(response.body).toBe(stream); expect(await response.text()).toBe("helloworld"); }); From 408456da5e828fa0a6987d8e024cfc3ceedaab79 Mon Sep 17 00:00:00 2001 From: robobun Date: Sat, 12 Sep 2026 20:51:25 +0000 Subject: [PATCH 02/14] Match fetch()'s zero-byte body rule in the new Request() GET/HEAD check --- src/runtime/webcore/Body.rs | 12 ++++++++++++ src/runtime/webcore/Request.rs | 8 ++++---- test/js/web/request/request.test.ts | 9 +++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/runtime/webcore/Body.rs b/src/runtime/webcore/Body.rs index 8e3ef3b70497..cf85c811c923 100644 --- a/src/runtime/webcore/Body.rs +++ b/src/runtime/webcore/Body.rs @@ -765,6 +765,18 @@ impl Value { } } + /// Whether a GET/HEAD request carrying this body must be rejected. Mirrors + /// `HTTPRequestBody::has_body` in `fetch_impl`: a zero-byte body (`""`, + /// `new Uint8Array(0)`, `new Blob([])`, `new URLSearchParams()`) counts as + /// no body so `new Request(url, init)` and `fetch(url, init)` agree. + pub(crate) fn has_request_body(&mut self) -> bool { + match self { + Value::Null | Value::Empty => false, + Value::Blob(_) | Value::InternalBlob(_) | Value::WTFStringImpl(_) => self.size() > 0, + Value::Locked(_) | Value::Used | Value::Error(_) => true, + } + } + pub(crate) fn memory_cost(&self) -> usize { match self { Value::InternalBlob(b) => b.memory_cost(), diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index d2660771a2da..36bab4bfacdf 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1398,10 +1398,10 @@ impl Request { req.url.set(href); - // Fetch spec `new Request()` step 36. `fetch()` has the same check in - // `fetch_impl`, and an empty string body counts as no body in both. - if matches!(req.method, Method::GET | Method::HEAD) - && !matches!(req.body_value(), BodyValue::Null | BodyValue::Empty) + // Fetch spec `new Request()` step 36. Looser than the spec (which + // rejects any non-null body) to match `fetch_impl`: a zero-byte body + // is treated as absent by both entry points. + if matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() { bail!(Err(global_this.throw_type_error(format_args!( "Request with GET/HEAD method cannot have body." diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index 389ef35d4d90..d35918dd8da5 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -123,6 +123,15 @@ describe("new Request() with a GET/HEAD method and a body", () => { expect(await new Request("http://example.com/", { method: "GET", body: "" }).text()).toBe(""); }); + test.each([ + ["Uint8Array(0)", () => new Uint8Array(0)], + ["Blob([])", () => new Blob([])], + ["URLSearchParams()", () => new URLSearchParams()], + ])("a zero-byte %s body is accepted, matching fetch()", async (_name, body) => { + // fetch_impl only rejects a GET/HEAD body with size > 0; the constructor uses the same rule. + expect(await new Request("http://example.com/", { method: "GET", body: body() }).text()).toBe(""); + }); + test("other methods keep their body", async () => { for (const method of ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) { const request = new Request("http://example.com/", { method, body: "x" }); From e72bd413e56c588e849ecc4fb72cb4e9a92079f1 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:54:02 +0000 Subject: [PATCH 03/14] [autofix.ci] apply automated fixes --- src/runtime/webcore/Request.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 36bab4bfacdf..016dffe11374 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1401,7 +1401,8 @@ impl Request { // Fetch spec `new Request()` step 36. Looser than the spec (which // rejects any non-null body) to match `fetch_impl`: a zero-byte body // is treated as absent by both entry points. - if matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() + if matches!(req.method, Method::GET | Method::HEAD) + && req.body_value_mut().has_request_body() { bail!(Err(global_this.throw_type_error(format_args!( "Request with GET/HEAD method cannot have body." From 81a387b8a671c9058cd1fe1faf692e6b653ccad0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:56:16 +0000 Subject: [PATCH 04/14] Shorten the doc comments on the new Request and Response checks --- src/runtime/webcore/Body.rs | 5 +---- src/runtime/webcore/Request.rs | 4 +--- src/runtime/webcore/Response.rs | 5 +---- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/src/runtime/webcore/Body.rs b/src/runtime/webcore/Body.rs index cf85c811c923..37d0cab18834 100644 --- a/src/runtime/webcore/Body.rs +++ b/src/runtime/webcore/Body.rs @@ -765,10 +765,7 @@ impl Value { } } - /// Whether a GET/HEAD request carrying this body must be rejected. Mirrors - /// `HTTPRequestBody::has_body` in `fetch_impl`: a zero-byte body (`""`, - /// `new Uint8Array(0)`, `new Blob([])`, `new URLSearchParams()`) counts as - /// no body so `new Request(url, init)` and `fetch(url, init)` agree. + /// Same rule as `HTTPRequestBody::has_body` in `fetch_impl`: a zero-byte body is no body. pub(crate) fn has_request_body(&mut self) -> bool { match self { Value::Null | Value::Empty => false, diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 016dffe11374..6ea250182d60 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1398,9 +1398,7 @@ impl Request { req.url.set(href); - // Fetch spec `new Request()` step 36. Looser than the spec (which - // rejects any non-null body) to match `fetch_impl`: a zero-byte body - // is treated as absent by both entry points. + // Fetch spec `new Request()` step 36, with the zero-byte rule `fetch()` uses. if matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() { diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 0fac50a718ed..fdabbdda45e2 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -1325,10 +1325,7 @@ impl Init { Ok(Some(result)) } - /// Fetch spec: `ResponseInit["statusText"]` must match the `reason-phrase` - /// production (HTAB, SP / VCHAR 0x20-0x7E, obs-text 0x80-0xFF). Only the - /// `Response` constructors call this: `Request` also parses its init - /// through `Init::init` and ignores `statusText`. + /// Fetch spec: `statusText` must match `reason-phrase` (HTAB, 0x20-0x7E, 0x80-0xFF). pub(crate) fn validate_status_text(&self, global_this: &JSGlobalObject) -> JsResult<()> { fn is_reason_phrase_unit(c: u32) -> bool { c == 0x09 || (0x20..=0x7E).contains(&c) || (0x80..=0xFF).contains(&c) From 95a799f24fc9854e93bd9f223b469de1068ac66c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:18:20 +0000 Subject: [PATCH 05/14] Keep the body a Response init contributes to new Request() --- src/runtime/webcore/Request.rs | 6 +++++- test/js/web/fetch/body-clone.test.ts | 7 +++---- test/js/web/request/request.test.ts | 7 +++++++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 6ea250182d60..044be4025730 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1037,6 +1037,7 @@ impl Request { let url_or_object = arguments[0]; let url_or_object_type = url_or_object.js_type(); let mut fields: EnumSet = EnumSet::empty(); + let mut body_from_response = false; let is_first_argument_a_url = // fastest path: @@ -1191,6 +1192,7 @@ impl Request { Err(e) => bail!(Err(e)), } fields.insert(Fields::Body); + body_from_response = true; } } } @@ -1399,7 +1401,9 @@ impl Request { req.url.set(href); // Fetch spec `new Request()` step 36, with the zero-byte rule `fetch()` uses. - if matches!(req.method, Method::GET | Method::HEAD) + // A body taken from a Response init is a Bun extension outside the spec. + if !body_from_response + && matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() { bail!(Err(global_this.throw_type_error(format_args!( diff --git a/test/js/web/fetch/body-clone.test.ts b/test/js/web/fetch/body-clone.test.ts index d631f9c86f71..2b1a40941e22 100644 --- a/test/js/web/fetch/body-clone.test.ts +++ b/test/js/web/fetch/body-clone.test.ts @@ -1050,10 +1050,9 @@ test("new Request(src, init) with a user ReadableStream body: both derived and s const twoArg = new Request(twoArgSrc, { headers: { "x-a": "1" } }); const oneArgSrc = make(); const oneArg = new Request(oneArgSrc); - // Bun extension: a Response as the second argument contributes its body and - // method via the sibling Response-source branch in construct_into. - // @ts-expect-error method is a Bun extension on ResponseInit - const responseSrc = new Response(stream(), { method: "POST" }); + // Bun extension: a Response as the second argument contributes its body via + // the sibling Response-source branch in construct_into. + const responseSrc = new Response(stream()); // @ts-expect-error Bun accepts a Response as init const fromResponse = new Request("http://example.com/", responseSrc); expect({ diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index d35918dd8da5..492c68de58c4 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -132,6 +132,13 @@ describe("new Request() with a GET/HEAD method and a body", () => { expect(await new Request("http://example.com/", { method: "GET", body: body() }).text()).toBe(""); }); + test("a body taken from a Response init is kept (Bun extension)", async () => { + // @ts-expect-error Bun accepts a Response as init + const request = new Request("http://example.com/", new Response("from response")); + expect(request.method).toBe("GET"); + expect(await request.text()).toBe("from response"); + }); + test("other methods keep their body", async () => { for (const method of ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) { const request = new Request("http://example.com/", { method, body: "x" }); From 8a4ec67a0e924dd3ca4a459647fad039b89acca4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:19:00 +0000 Subject: [PATCH 06/14] Shorten the comment on the Request body check --- src/runtime/webcore/Request.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 044be4025730..58c6b8fdfc4c 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1400,8 +1400,7 @@ impl Request { req.url.set(href); - // Fetch spec `new Request()` step 36, with the zero-byte rule `fetch()` uses. - // A body taken from a Response init is a Bun extension outside the spec. + // Fetch spec `new Request()` step 36. A Response init body is a Bun extension. if !body_from_response && matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() From 799f29818ccd6536f9d05b4fe9a007922f4f20ed Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:43:00 +0000 Subject: [PATCH 07/14] Skip the GET/HEAD body check for a method token Bun does not know Init::init maps an unknown method token such as "Post" or "LIST" to GET. The body check now tells that fallback apart from a real GET or HEAD, so those requests keep their body as before. Response.redirect() checks the status before statusText, so a status out of range reports a RangeError first, as at the other sites. --- src/runtime/webcore/Request.rs | 25 ++++++++++++++++++++++--- src/runtime/webcore/Response.rs | 2 +- test/js/web/fetch/response.test.ts | 20 +++++++++++++++++++- test/js/web/request/request.test.ts | 9 +++++++++ 4 files changed, 51 insertions(+), 5 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 58c6b8fdfc4c..f56e30ee96fe 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -973,6 +973,20 @@ impl Request { ::check_body_stream_ref(self, global_object) } + /// `Init::init` maps a method token it does not know to `GET`. Tell that + /// fallback apart from a real `GET`/`HEAD` so the body check skips it. + fn init_method_is_unknown(global_this: &JSGlobalObject, init: JSValue) -> JsResult { + let Some(method) = init.fast_get_truthy(global_this, bun_jsc::BuiltinName::method)? else { + return Ok(false); + }; + let str = BunString::from_js(method, global_this)?; + let utf8 = str.to_utf8(); + let token: &[u8] = &utf8; + Ok(Method::which(token).is_none() + && !token.eq_ignore_ascii_case(b"GET") + && !token.eq_ignore_ascii_case(b"HEAD")) + } + pub(crate) fn construct_into( global_this: &JSGlobalObject, arguments: &[JSValue], @@ -1037,7 +1051,7 @@ impl Request { let url_or_object = arguments[0]; let url_or_object_type = url_or_object.js_type(); let mut fields: EnumSet = EnumSet::empty(); - let mut body_from_response = false; + let mut skip_body_check = false; let is_first_argument_a_url = // fastest path: @@ -1192,7 +1206,7 @@ impl Request { Err(e) => bail!(Err(e)), } fields.insert(Fields::Body); - body_from_response = true; + skip_body_check = true; } } } @@ -1330,6 +1344,11 @@ impl Request { if !fields.contains(Fields::Method) { req.method = response_init.method; fields.insert(Fields::Method); + match Self::init_method_is_unknown(global_this, value) { + Ok(true) => skip_body_check = true, + Ok(false) => {} + Err(e) => bail!(Err(e)), + } } } } @@ -1401,7 +1420,7 @@ impl Request { req.url.set(href); // Fetch spec `new Request()` step 36. A Response init body is a Bun extension. - if !body_from_response + if !skip_body_check && matches!(req.method, Method::GET | Method::HEAD) && req.body_value_mut().has_request_body() { diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index fdabbdda45e2..59f2527898b0 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -1004,7 +1004,6 @@ impl Response { response.init.with_mut(|i| i.status_code = status); } else if let Some(init) = Init::init(global_this, arg_init)? { // cleanup is handled by Init's drop glue on `?` below - init.validate_status_text(global_this)?; response.init.set(init); let status = response.init.get().status_code; @@ -1013,6 +1012,7 @@ impl Response { Self::validate_redirect_status_code(global_this, i32::from(status))?; response.init.with_mut(|i| i.status_code = status); } + response.init.get().validate_status_text(global_this)?; } } diff --git a/test/js/web/fetch/response.test.ts b/test/js/web/fetch/response.test.ts index 03b54de1e9e9..3bcc8404c745 100644 --- a/test/js/web/fetch/response.test.ts +++ b/test/js/web/fetch/response.test.ts @@ -49,7 +49,7 @@ describe("2-arg form", () => { test("print size", () => { expect(normalizeBunSnapshot(Bun.inspect(new Response(Bun.file(import.meta.filename)))), import.meta.dir) .toMatchInlineSnapshot(` - "Response (9.87 KB) { + "Response (10.75 KB) { ok: true, url: "", status: 200, @@ -174,6 +174,24 @@ describe("statusText reason-phrase validation", () => { test("a status out of range is reported before an invalid statusText", () => { expect(() => new Response(null, { status: 600, statusText: "a\nb" })).toThrow(RangeError); + expect(() => Response.redirect("http://example.com/", { status: 404, statusText: "a\nb" })).toThrow(RangeError); + }); + + test("a fetched Response with a non-Latin-1 reason phrase is rejected as an init", async () => { + using listener = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { + data(socket) { + socket.end(Buffer.from("HTTP/1.1 200 \x80OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", "latin1")); + }, + }, + }); + const fetched = await fetch(`http://127.0.0.1:${listener.port}/`); + // The lone 0x80 byte is not valid UTF-8, so it decodes to U+FFFD. + expect(fetched.statusText).toBe("\uFFFDOK"); + expect(() => new Response(null, fetched)).toThrow(new TypeError("Invalid statusText")); + expect(() => new Response(null, { statusText: fetched.statusText })).toThrow(new TypeError("Invalid statusText")); }); test.each([ diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index 492c68de58c4..4e3b57dc5862 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -132,6 +132,15 @@ describe("new Request() with a GET/HEAD method and a body", () => { expect(await new Request("http://example.com/", { method: "GET", body: body() }).text()).toBe(""); }); + test.each(["Get", "Head", "gEt"])("mixed-case %s with a body throws TypeError", method => { + expect(() => new Request("http://example.com/", { method, body: "x" })).toThrow(new TypeError(message)); + }); + + test.each(["Post", "LIST", "Purge"])("a method token Bun does not know (%s) keeps its body", async method => { + const request = new Request("http://example.com/", { method, body: "x" }); + expect(await request.text()).toBe("x"); + }); + test("a body taken from a Response init is kept (Bun extension)", async () => { // @ts-expect-error Bun accepts a Response as init const request = new Request("http://example.com/", new Response("from response")); From 557d65024f64ecc567c06b74f46891072cde1c2c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:43:45 +0000 Subject: [PATCH 08/14] Shorten the comment on init_method_is_unknown --- src/runtime/webcore/Request.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index f56e30ee96fe..86fc472f2a4a 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -973,8 +973,7 @@ impl Request { ::check_body_stream_ref(self, global_object) } - /// `Init::init` maps a method token it does not know to `GET`. Tell that - /// fallback apart from a real `GET`/`HEAD` so the body check skips it. + /// True when `Init::init` fell back to `GET` for a method token it does not know. fn init_method_is_unknown(global_this: &JSGlobalObject, init: JSValue) -> JsResult { let Some(method) = init.fast_get_truthy(global_this, bun_jsc::BuiltinName::method)? else { return Ok(false); From 2e895395b1b0fa5c63f8c0d82f7a5b08b22a5ddc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:59:55 +0000 Subject: [PATCH 09/14] Check statusText where the ResponseInit dictionary is parsed Init::init now takes a FOR_RESPONSE flag and rejects an invalid statusText right after it reads the dictionary field. new Request() passes false. A Response used as the init is cloned before that point, so new Response(body, upstream) keeps working for a reason phrase the wire decoded to a code unit above 0xFF. --- src/runtime/webcore/Request.rs | 2 +- src/runtime/webcore/Response.rs | 48 ++++++++++++------------------ test/js/web/fetch/response.test.ts | 8 ++--- 3 files changed, 24 insertions(+), 34 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 86fc472f2a4a..1945674c4db0 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1313,7 +1313,7 @@ impl Request { } if !fields.contains(Fields::Method) || !fields.contains(Fields::Headers) { - match crate::webcore::response::Init::init(global_this, value) { + match crate::webcore::response::Init::init::(global_this, value) { Ok(Some(response_init)) => { let header_check = !explicit_check || (explicit_check diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 59f2527898b0..f29f5ceea50c 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -921,8 +921,7 @@ impl Response { u16::try_from(0.max(arg_init.to_int32()).min(i32::from(u16::MAX))).unwrap(); }); } else { - if let Some(init) = Init::init(global_this, arg_init)? { - init.validate_status_text(global_this)?; + if let Some(init) = Init::init::(global_this, arg_init)? { response.init.set(init); } } @@ -1002,7 +1001,7 @@ impl Response { let status = Self::validate_redirect_status_code(global_this, arg_init.to_int32())?; response.init.with_mut(|i| i.status_code = status); - } else if let Some(init) = Init::init(global_this, arg_init)? { + } else if let Some(init) = Init::init::(global_this, arg_init)? { // cleanup is handled by Init's drop glue on `?` below response.init.set(init); @@ -1012,7 +1011,6 @@ impl Response { Self::validate_redirect_status_code(global_this, i32::from(status))?; response.init.with_mut(|i| i.status_code = status); } - response.init.get().validate_status_text(global_this)?; } } @@ -1130,9 +1128,7 @@ impl Response { }; } if arguments[1].is_object() { - let init = Init::init(global_this, arguments[1])?.expect("unreachable"); - init.validate_status_text(global_this)?; - break 'brk init; + break 'brk Init::init::(global_this, arguments[1])?.expect("unreachable"); } return Err(global_this.throw_invalid_arguments(format_args!( "Failed to construct 'Response': The provided body value is not of type 'ResponseInit'", @@ -1231,7 +1227,9 @@ impl Init { }) } - pub(crate) fn init( + /// `FOR_RESPONSE` applies the `ResponseInit` checks that `new Request()`, + /// which parses its `RequestInit` through this too, must not run. + pub(crate) fn init( global_this: &JSGlobalObject, response_init: JSValue, ) -> JsResult> { @@ -1312,6 +1310,9 @@ impl Init { response_init.fast_get_truthy(global_this, BuiltinName::statusText)? { result.status_text = status_text.to_bun_string(global_this)?; + if FOR_RESPONSE && !is_reason_phrase(&result.status_text) { + return Err(global_this.throw_type_error(format_args!("Invalid statusText"))); + } } if let Some(method_value) = @@ -1324,28 +1325,17 @@ impl Init { Ok(Some(result)) } +} - /// Fetch spec: `statusText` must match `reason-phrase` (HTAB, 0x20-0x7E, 0x80-0xFF). - pub(crate) fn validate_status_text(&self, global_this: &JSGlobalObject) -> JsResult<()> { - fn is_reason_phrase_unit(c: u32) -> bool { - c == 0x09 || (0x20..=0x7E).contains(&c) || (0x80..=0xFF).contains(&c) - } - let status_text = &self.status_text; - let valid = if status_text.is_utf16() { - status_text - .utf16() - .iter() - .all(|&c| is_reason_phrase_unit(u32::from(c))) - } else { - status_text - .byte_slice() - .iter() - .all(|&c| is_reason_phrase_unit(u32::from(c))) - }; - if valid { - return Ok(()); - } - Err(global_this.throw_type_error(format_args!("Invalid statusText"))) +/// Fetch spec `reason-phrase`: HTAB, 0x20-0x7E, 0x80-0xFF, per code unit. +fn is_reason_phrase(status_text: &BunString) -> bool { + fn ok(c: u32) -> bool { + c == 0x09 || (0x20..=0x7E).contains(&c) || (0x80..=0xFF).contains(&c) + } + if status_text.is_utf16() { + status_text.utf16().iter().all(|&c| ok(u32::from(c))) + } else { + status_text.byte_slice().iter().all(|&c| ok(u32::from(c))) } } diff --git a/test/js/web/fetch/response.test.ts b/test/js/web/fetch/response.test.ts index 3bcc8404c745..06289c7ac602 100644 --- a/test/js/web/fetch/response.test.ts +++ b/test/js/web/fetch/response.test.ts @@ -49,7 +49,7 @@ describe("2-arg form", () => { test("print size", () => { expect(normalizeBunSnapshot(Bun.inspect(new Response(Bun.file(import.meta.filename)))), import.meta.dir) .toMatchInlineSnapshot(` - "Response (10.75 KB) { + "Response (10.71 KB) { ok: true, url: "", status: 200, @@ -174,10 +174,9 @@ describe("statusText reason-phrase validation", () => { test("a status out of range is reported before an invalid statusText", () => { expect(() => new Response(null, { status: 600, statusText: "a\nb" })).toThrow(RangeError); - expect(() => Response.redirect("http://example.com/", { status: 404, statusText: "a\nb" })).toThrow(RangeError); }); - test("a fetched Response with a non-Latin-1 reason phrase is rejected as an init", async () => { + test("a fetched Response with a non-Latin-1 reason phrase can still be re-wrapped", async () => { using listener = Bun.listen({ hostname: "127.0.0.1", port: 0, @@ -190,7 +189,8 @@ describe("statusText reason-phrase validation", () => { const fetched = await fetch(`http://127.0.0.1:${listener.port}/`); // The lone 0x80 byte is not valid UTF-8, so it decodes to U+FFFD. expect(fetched.statusText).toBe("\uFFFDOK"); - expect(() => new Response(null, fetched)).toThrow(new TypeError("Invalid statusText")); + // The check applies to a ResponseInit dictionary, not to a Response used as the init. + expect(new Response("proxied", fetched).statusText).toBe("\uFFFDOK"); expect(() => new Response(null, { statusText: fetched.statusText })).toThrow(new TypeError("Invalid statusText")); }); From 2b1d92a83e80b10145619723be9a3e27b9bfcd1b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 22:00:32 +0000 Subject: [PATCH 10/14] Shorten the comment on Init::init --- src/runtime/webcore/Response.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index f29f5ceea50c..3546c6a3a6e4 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -1227,8 +1227,7 @@ impl Init { }) } - /// `FOR_RESPONSE` applies the `ResponseInit` checks that `new Request()`, - /// which parses its `RequestInit` through this too, must not run. + /// `FOR_RESPONSE` is false when `new Request()` parses its `RequestInit` through this. pub(crate) fn init( global_this: &JSGlobalObject, response_init: JSValue, From 8cc5afbdb447bad64d2c1e9b312b425e06fa57cd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 22:22:24 +0000 Subject: [PATCH 11/14] Read the raw method token only when Init::init produced GET --- src/runtime/webcore/Request.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 1945674c4db0..6a7cedef6068 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1343,10 +1343,12 @@ impl Request { if !fields.contains(Fields::Method) { req.method = response_init.method; fields.insert(Fields::Method); - match Self::init_method_is_unknown(global_this, value) { - Ok(true) => skip_body_check = true, - Ok(false) => {} - Err(e) => bail!(Err(e)), + if req.method == Method::GET { + match Self::init_method_is_unknown(global_this, value) { + Ok(true) => skip_body_check = true, + Ok(false) => {} + Err(e) => bail!(Err(e)), + } } } } From 2f7fb502fbbdb5ab7fa63551aa1aa86368a95a50 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 22:33:40 +0000 Subject: [PATCH 12/14] Record the unknown method token in Init instead of reading it again Init::init sets method_unknown when the dictionary names a token that Method::which does not know and that is not a case variant of GET or HEAD. new Request() reads that flag for the body check, so init.method is read once. --- src/runtime/webcore/Request.rs | 21 ++------------------- src/runtime/webcore/Response.rs | 14 ++++++++++++-- test/js/web/request/request.test.ts | 12 ++++++++++++ 3 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 6a7cedef6068..7f259ea4a3f9 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -973,19 +973,6 @@ impl Request { ::check_body_stream_ref(self, global_object) } - /// True when `Init::init` fell back to `GET` for a method token it does not know. - fn init_method_is_unknown(global_this: &JSGlobalObject, init: JSValue) -> JsResult { - let Some(method) = init.fast_get_truthy(global_this, bun_jsc::BuiltinName::method)? else { - return Ok(false); - }; - let str = BunString::from_js(method, global_this)?; - let utf8 = str.to_utf8(); - let token: &[u8] = &utf8; - Ok(Method::which(token).is_none() - && !token.eq_ignore_ascii_case(b"GET") - && !token.eq_ignore_ascii_case(b"HEAD")) - } - pub(crate) fn construct_into( global_this: &JSGlobalObject, arguments: &[JSValue], @@ -1343,12 +1330,8 @@ impl Request { if !fields.contains(Fields::Method) { req.method = response_init.method; fields.insert(Fields::Method); - if req.method == Method::GET { - match Self::init_method_is_unknown(global_this, value) { - Ok(true) => skip_body_check = true, - Ok(false) => {} - Err(e) => bail!(Err(e)), - } + if response_init.method_unknown { + skip_body_check = true; } } } diff --git a/src/runtime/webcore/Response.rs b/src/runtime/webcore/Response.rs index 3546c6a3a6e4..2b76c19f8fb4 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -1197,6 +1197,8 @@ pub struct Init { pub(crate) status_code: u16, pub(crate) status_text: BunString, pub method: Method, + /// `method` is the `GET` fallback for a token `Method::which` does not know (#42497). + pub(crate) method_unknown: bool, } impl Default for Init { @@ -1206,6 +1208,7 @@ impl Default for Init { status_code: 0, status_text: BunString::EMPTY, method: Method::GET, + method_unknown: false, } } } @@ -1224,6 +1227,7 @@ impl Init { status_code: self.status_code, status_text: self.status_text.clone(), method: self.method, + method_unknown: self.method_unknown, }) } @@ -1317,8 +1321,14 @@ impl Init { if let Some(method_value) = response_init.fast_get_truthy(global_this, BuiltinName::method)? { - if let Some(method) = bun_http_jsc::method_jsc::from_js(global_this, method_value)? { - result.method = method; + let token = method_value.to_utf8(global_this)?; + match Method::which(&token) { + Some(method) => result.method = method, + // A case variant of GET or HEAD keeps the fallback on purpose. + None => { + result.method_unknown = + !token.eq_ignore_ascii_case(b"GET") && !token.eq_ignore_ascii_case(b"HEAD") + } } } diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index 4e3b57dc5862..e013eb2916e0 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -141,6 +141,18 @@ describe("new Request() with a GET/HEAD method and a body", () => { expect(await request.text()).toBe("x"); }); + test("init.method is read once, so a getter cannot change the answer", () => { + let reads = 0; + const init = { + get method() { + return reads++ === 0 ? "GET" : "LIST"; + }, + body: "x", + }; + expect(() => new Request("http://example.com/", init)).toThrow(new TypeError(message)); + expect(reads).toBe(1); + }); + test("a body taken from a Response init is kept (Bun extension)", async () => { // @ts-expect-error Bun accepts a Response as init const request = new Request("http://example.com/", new Response("from response")); From c36bc8e9c7bf47aabea1b2fa96e731a2082e5d13 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 22:48:40 +0000 Subject: [PATCH 13/14] ci: retrigger From b6db40e67ba98c25e57d2c3a920aff3bdc17ec90 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 12 Sep 2026 22:57:27 +0000 Subject: [PATCH 14/14] Skip the GET/HEAD body check for a body inherited with its method new Request(input, init) copies the input's method and body when the init does not name them. That pair already passed the check when the input was built, so the check runs again only when the init sets the method. --- src/runtime/webcore/Request.rs | 7 ++++++- test/js/web/request/request.test.ts | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/runtime/webcore/Request.rs b/src/runtime/webcore/Request.rs index 7f259ea4a3f9..6f7bc1e5d16e 100644 --- a/src/runtime/webcore/Request.rs +++ b/src/runtime/webcore/Request.rs @@ -1102,7 +1102,8 @@ impl Request { return Ok(req); } - if !fields.contains(Fields::Method) { + let method_from_input = !fields.contains(Fields::Method); + if method_from_input { req.method = request.method; fields.insert(Fields::Method); } @@ -1144,6 +1145,10 @@ impl Request { Err(e) => bail!(Err(e)), } fields.insert(Fields::Body); + // The input passed this check when it was built. + if method_from_input { + skip_body_check = true; + } } } } diff --git a/test/js/web/request/request.test.ts b/test/js/web/request/request.test.ts index e013eb2916e0..595fcf6217b6 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -153,6 +153,16 @@ describe("new Request() with a GET/HEAD method and a body", () => { expect(reads).toBe(1); }); + test("a Request built under an exemption can be wrapped again with an init", async () => { + // @ts-expect-error Bun accepts a Response as init + const fromResponse = new Request("http://example.com/", new Response("from response")); + expect(await new Request(fromResponse, { headers: { "x-a": "1" } }).text()).toBe("from response"); + const unknownMethod = new Request("http://example.com/", { method: "LIST", body: "x" }); + expect(await new Request(unknownMethod, {}).text()).toBe("x"); + // An explicit GET in the init still applies the check. + expect(() => new Request(unknownMethod, { method: "GET" })).toThrow(new TypeError(message)); + }); + test("a body taken from a Response init is kept (Bun extension)", async () => { // @ts-expect-error Bun accepts a Response as init const request = new Request("http://example.com/", new Response("from response"));