Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/runtime/webcore/Body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
30 changes: 30 additions & 0 deletions src/runtime/webcore/Request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,19 @@ impl Request {
<Self as BodyMixin>::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<bool> {
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],
Expand Down Expand Up @@ -1037,6 +1050,7 @@ impl Request {
let url_or_object = arguments[0];
let url_or_object_type = url_or_object.js_type();
let mut fields: EnumSet<Fields> = EnumSet::empty();
let mut skip_body_check = false;

let is_first_argument_a_url =
// fastest path:
Expand Down Expand Up @@ -1191,6 +1205,7 @@ impl Request {
Err(e) => bail!(Err(e)),
}
fields.insert(Fields::Body);
skip_body_check = true;
}
}
}
Expand Down Expand Up @@ -1328,6 +1343,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)),
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
Expand Down Expand Up @@ -1398,6 +1418,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();
Expand Down
29 changes: 28 additions & 1 deletion src/runtime/webcore/Response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -1011,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)?;
}
}

Expand Down Expand Up @@ -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)?;
Comment thread
robobun marked this conversation as resolved.
Resolved
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'",
Expand Down Expand Up @@ -1320,6 +1324,29 @@ 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")))
}
}

// https://developer.mozilla.org/en-US/docs/Web/API/Headers
Expand Down
2 changes: 1 addition & 1 deletion test/js/bun/http/async-iterator-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
1 change: 1 addition & 0 deletions test/js/bun/util/heap-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
9 changes: 7 additions & 2 deletions test/js/web/fetch/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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",
},
Expand Down Expand Up @@ -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", () => {
Expand Down
67 changes: 66 additions & 1 deletion test/js/web/fetch/response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.75 KB) {
ok: true,
url: "",
status: 200,
Expand Down Expand Up @@ -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);
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([
["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();
Expand Down
3 changes: 3 additions & 0 deletions test/js/web/fetch/utf8-bom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
});
Expand All @@ -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" },
});
Expand All @@ -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" },
});
Expand Down
12 changes: 9 additions & 3 deletions test/js/web/html/FormData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } = {};
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading