diff --git a/src/runtime/webcore/Body.rs b/src/runtime/webcore/Body.rs index 8e3ef3b70497..37d0cab18834 100644 --- a/src/runtime/webcore/Body.rs +++ b/src/runtime/webcore/Body.rs @@ -765,6 +765,15 @@ impl Value { } } + /// 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, + 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 8ceaadd119dd..6f7bc1e5d16e 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 skip_body_check = false; let is_first_argument_a_url = // fastest path: @@ -1101,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); } @@ -1143,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; + } } } } @@ -1191,6 +1197,7 @@ impl Request { Err(e) => bail!(Err(e)), } fields.insert(Fields::Body); + skip_body_check = true; } } } @@ -1298,7 +1305,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 @@ -1328,6 +1335,9 @@ impl Request { if !fields.contains(Fields::Method) { req.method = response_init.method; fields.insert(Fields::Method); + if response_init.method_unknown { + skip_body_check = true; + } } } } @@ -1398,6 +1408,16 @@ impl Request { req.url.set(href); + // Fetch spec `new Request()` step 36. A Response init body is a Bun extension. + if !skip_body_check + && 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." + )))); + } + 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..2b76c19f8fb4 100644 --- a/src/runtime/webcore/Response.rs +++ b/src/runtime/webcore/Response.rs @@ -921,7 +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)? { + if let Some(init) = Init::init::(global_this, arg_init)? { response.init.set(init); } } @@ -1001,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); @@ -1128,7 +1128,7 @@ impl Response { }; } if arguments[1].is_object() { - break 'brk Init::init(global_this, arguments[1])?.expect("unreachable"); + 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'", @@ -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,10 +1227,12 @@ impl Init { status_code: self.status_code, status_text: self.status_text.clone(), method: self.method, + method_unknown: self.method_unknown, }) } - pub(crate) fn init( + /// `FOR_RESPONSE` is false when `new Request()` parses its `RequestInit` through this. + pub(crate) fn init( global_this: &JSGlobalObject, response_init: JSValue, ) -> JsResult> { @@ -1308,13 +1313,22 @@ 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) = 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") + } } } @@ -1322,5 +1336,17 @@ impl Init { } } +/// 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))) + } +} + // https://developer.mozilla.org/en-US/docs/Web/API/Headers // TODO: move to the http module. this has nothing to do with jsc or WebCore 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/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..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 (8.0 KB) { + "Response (10.71 KB) { ok: true, url: "", status: 200, @@ -144,6 +144,71 @@ 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("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, + 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"); + // 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")); + }); + + 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..595fcf6217b6 100644 --- a/test/js/web/request/request.test.ts +++ b/test/js/web/request/request.test.ts @@ -76,6 +76,108 @@ 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.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.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("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 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")); + 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" }); + 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"); });