Skip to content
Closed
15 changes: 8 additions & 7 deletions src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3711,6 +3711,9 @@ impl<'a> HTTPClient<'a> {
}};
}

// Not the 16 KB server-side `MAX_HTTP_HEADER_SIZE`: large `Location`/`Set-Cookie` responses are legitimate.
const MAX_RESPONSE_HEADER_BUFFER: usize = 1024 * 1024;

let shared_resp = scratch::response_headers();
let mut response = loop {
let mut amount_read: usize = 0;
Expand All @@ -3728,13 +3731,6 @@ impl<'a> HTTPClient<'a> {
) {
Ok(r) => r,
Err(picohttp::ParseResponseError::ShortRead) => {
// `MAX_HTTP_HEADER_SIZE` (default 16 KB) is the *server*/
// request-side knob (Node `--max-http-header-size`); reusing
// it here rejects legitimate responses with large
// `Location`/`Set-Cookie` headers. The intent is to bound
// `response_message_buffer` growth, so use a generous fixed
// cap independent of that knob.
const MAX_RESPONSE_HEADER_BUFFER: usize = 1024 * 1024;
if to_read.len() > MAX_RESPONSE_HEADER_BUFFER {
self.close_and_fail::<IS_SSL>(
crate::Error::ResponseHeadersTooLarge,
Expand All @@ -3750,6 +3746,11 @@ impl<'a> HTTPClient<'a> {
}
};

if parsed.bytes_read > MAX_RESPONSE_HEADER_BUFFER {
self.close_and_fail::<IS_SSL>(crate::Error::ResponseHeadersTooLarge, socket);
return;
}

let bytes_read = parsed.bytes_read.min(to_read.len());
to_read = &to_read[bytes_read..];

Expand Down
1 change: 1 addition & 0 deletions src/http_jsc/websocket_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,7 @@ pub enum ErrorCode {
ProxyAuthenticationRequired = 34,
ProxyTunnelFailed = 36,
UnexpectedRsv1 = 37,
ResponseHeadersTooLarge = 38,
}

// ──────────────────────────────────────────────────────────────────────────
Expand Down
27 changes: 25 additions & 2 deletions src/http_jsc/websocket_client/WebSocketUpgradeClient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ fn handshake_timeout_seconds() -> core::ffi::c_uint {
)
}

/// Raw bound: `max_http_header_size` plus the framing of 128 fields, which llhttp does not count.
#[inline]
fn max_response_head_len() -> usize {
bun_http::max_http_header_size().saturating_add(128 * 4 + 64)
}

/// `uws.NewSocketHandler(ssl)`
type Socket<const SSL: bool> = SocketHandler<SSL>;

Expand Down Expand Up @@ -95,6 +101,7 @@ enum HeadParse {
head_len: usize,
},
Invalid,
TooLarge,
NeedMore,
}

Expand Down Expand Up @@ -710,6 +717,10 @@ where
};

match parsed {
// The cap applies to the head length, complete or not.
Ok(HeadParse::Done { head_len, .. }) if head_len > max_response_head_len() => {
HeadParse::TooLarge
}
Ok(done) => done,
Err(picohttp::ParseResponseError::MalformedHttpResponse) => HeadParse::Invalid,
Err(picohttp::ParseResponseError::ShortRead) => {
Expand All @@ -720,8 +731,8 @@ where
// `body` is part of an incomplete header — cap that, not
// total bytes received (which may include pipelined
// WebSocket frames once the header does complete).
if self.body.get().len() > bun_http::max_http_header_size() {
HeadParse::Invalid
if self.body.get().len() > max_response_head_len() {
HeadParse::TooLarge
} else {
HeadParse::NeedMore
}
Expand Down Expand Up @@ -781,6 +792,10 @@ where
Self::terminate(this, ErrorCode::InvalidResponse);
return;
}
HeadParse::TooLarge => {
Self::terminate(this, ErrorCode::ResponseHeadersTooLarge);
return;
}
HeadParse::NeedMore => return,
};
Self::process_websocket_upgrade_response(this, &full);
Expand Down Expand Up @@ -854,6 +869,10 @@ where
Self::terminate(this, ErrorCode::InvalidResponse);
return;
}
HeadParse::TooLarge => {
Self::terminate(this, ErrorCode::ResponseHeadersTooLarge);
return;
}
HeadParse::NeedMore => return,
};

Expand Down Expand Up @@ -1028,6 +1047,10 @@ where
Self::terminate(this, ErrorCode::InvalidResponse);
return;
}
HeadParse::TooLarge => {
Self::terminate(this, ErrorCode::ResponseHeadersTooLarge);
return;
}
HeadParse::NeedMore => return,
};
Self::process_websocket_upgrade_response(this, &full);
Expand Down
4 changes: 4 additions & 0 deletions src/jsc/bindings/webcore/WebSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,10 @@ void WebSocket::didFailWithErrorCode(Bun::WebSocketErrorCode code)
didReceiveClose(CleanStatus::NotClean, 1002, "Invalid response"_s, true);
break;
}
case Bun::WebSocketErrorCode::response_headers_too_large: {
didReceiveClose(CleanStatus::NotClean, 1002, "Response headers exceed --max-http-header-size"_s, true);
break;
}
case Bun::WebSocketErrorCode::expected_101_status_code: {
didReceiveClose(CleanStatus::NotClean, 1002, "Expected 101 status code"_s, true);
break;
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/webcore/WebSocketErrorCode.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ enum class WebSocketErrorCode : int32_t {
proxy_authentication_required = 34,
proxy_tunnel_failed = 36,
unexpected_rsv1 = 37,
response_headers_too_large = 38,
};

}
85 changes: 85 additions & 0 deletions test/js/web/fetch/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4197,3 +4197,88 @@ it("verbose fetch logging prints [redacted] in place of Authorization credential
expect(stderr).not.toContain("sekret-token");
expect(exitCode).toBe(0);
});

describe("response header size cap", () => {
// The fetch client rejects a response head larger than 1 MiB with
// ResponseHeadersTooLarge. The decision must depend on the size of the
// head only, not on how the peer's writes line up with the client's reads.
const MAX_RESPONSE_HEAD = 1024 * 1024;

function buildHead(totalBytes: number): Uint8Array {
const prefix = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n";
const lines: string[] = [];
let size = prefix.length + 2; // trailing CRLF
let i = 0;
const filler = Buffer.alloc(100_000, "a").toString();
while (totalBytes - size > 100_000 + 16) {
const line = `x-${String(i++).padStart(3, "0")}: ${filler}\r\n`;
lines.push(line);
size += line.length;
}
const padName = "x-pad: ";
const padLen = totalBytes - size - padName.length - 2;
expect(padLen).toBeGreaterThanOrEqual(0);
lines.push(`${padName}${Buffer.alloc(padLen, "b").toString()}\r\n`);
const head = prefix + lines.join("") + "\r\n";
expect(head.length).toBe(totalBytes);
return Buffer.from(head + "ok", "latin1");
}

async function fetchFromRawServer(payload: Uint8Array, writeSize: number): Promise<string> {
// Raw TCP origin: one request, one canned response, then close.
await using listener = Bun.listen<{ queue: Uint8Array[]; responded: boolean }>({
hostname: "127.0.0.1",
port: 0,
socket: {
open(socket) {
socket.data = { queue: [], responded: false };
},
data(socket) {
if (socket.data.responded) return;
socket.data.responded = true;
for (let off = 0; off < payload.length; off += writeSize) {
socket.data.queue.push(payload.subarray(off, Math.min(off + writeSize, payload.length)));
}
pump(socket);
},
drain(socket) {
pump(socket);
},
error() {},
},
});

function pump(socket: Bun.Socket<{ queue: Uint8Array[]; responded: boolean }>) {
const { queue } = socket.data;
while (queue.length > 0) {
const chunk = queue[0];
const written = socket.write(chunk);
if (written < chunk.length) {
queue[0] = chunk.subarray(Math.max(written, 0));
return;
}
queue.shift();
}
socket.end();
}

try {
const res = await fetch(`http://127.0.0.1:${listener.port}/`, { keepalive: false });
return await res.text();
} catch (e: any) {
return `error:${e.code}`;
}
}

it("accepts a head of exactly 1 MiB sent in 4 KiB writes", async () => {
expect(await fetchFromRawServer(buildHead(MAX_RESPONSE_HEAD), 4096)).toBe("ok");
});

it("rejects a head of 1 MiB + 1 byte sent in one write", async () => {
expect(await fetchFromRawServer(buildHead(MAX_RESPONSE_HEAD + 1), 1 << 30)).toBe("error:ResponseHeadersTooLarge");
});

it("rejects a head of 1 MiB + 1 byte sent in 4 KiB writes", async () => {
expect(await fetchFromRawServer(buildHead(MAX_RESPONSE_HEAD + 1), 4096)).toBe("error:ResponseHeadersTooLarge");
});
});
91 changes: 90 additions & 1 deletion test/js/web/websocket/websocket-client-short-read.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ describe("WebSocket", () => {
});

describe("WebSocket upgrade split across reads", () => {
const TOO_LARGE = "Response headers exceed --max-http-header-size";

function makeAccept(key: string): string {
const hasher = new Bun.CryptoHasher("sha1");
hasher.update(key);
Expand Down Expand Up @@ -235,11 +237,98 @@ describe("WebSocket upgrade split across reads", () => {

try {
const msg = await promise;
expect(msg).toContain("Invalid response");
expect(msg).toContain(TOO_LARGE);
} finally {
ws.close();
}
});

// The bound is on the size of the head, not on where the reads end.
// max_http_header_size limits what llhttp counts, not framing (": ", "\r\n"),
// so the bound on raw bytes adds the framing of 128 header fields.
const MAX_HTTP_HEADER_SIZE = 16384; // default
const MAX_HEAD = MAX_HTTP_HEADER_SIZE + 128 * 4 + 64;

// With `splitAt`, the head goes out in two writes so the client reads an
// incomplete head of `splitAt` bytes first.
function serve101(headSize: number, splitAt?: number) {
return Bun.listen<{ buf: string; done: boolean }>({
hostname: "127.0.0.1",
port: 0,
socket: {
open(socket) {
socket.data = { buf: "", done: false };
},
data(socket, chunk) {
const st = socket.data;
if (st.done) return;
st.buf += chunk.toString("latin1");
if (!st.buf.includes("\r\n\r\n")) return;
st.done = true;
const m = /Sec-WebSocket-Key:\s*(\S+)/i.exec(st.buf);
if (!m) {
socket.end();
return;
}
const fixed =
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
`Sec-WebSocket-Accept: ${makeAccept(m[1])}\r\n` +
"X-Pad: ";
const padLen = headSize - fixed.length - "\r\n\r\n".length;
const head = fixed + Buffer.alloc(padLen, "a").toString() + "\r\n\r\n";
expect(head.length).toBe(headSize);
if (splitAt === undefined) {
socket.write(head);
socket.flush();
return;
}
socket.write(head.slice(0, splitAt));
socket.flush();
setTimeout(() => {
socket.write(head.slice(splitAt));
socket.flush();
}, 50);
},
},
});
}

function connect(port: number): Promise<string> {
const { promise, resolve } = Promise.withResolvers<string>();
const ws = new globalThis.WebSocket(`ws://127.0.0.1:${port}`);
ws.onopen = () => {
resolve("open");
ws.close();
};
ws.onerror = ev => resolve("error: " + ((ev as ErrorEvent).message ?? "error"));
Comment thread
robobun marked this conversation as resolved.
Resolved
ws.onclose = ev => resolve(`close: ${ev.code} ${ev.reason}`);
return promise;
}

test("101 head of exactly the bound in one write opens", async () => {
using server = serve101(MAX_HEAD);
expect(await connect(server.port)).toBe("open");
});

test("101 head one byte over the bound in one write is rejected", async () => {
using server = serve101(MAX_HEAD + 1);
expect(await connect(server.port)).toContain(TOO_LARGE);
});

test("101 head over the bound is rejected when the first read stays under the bound", async () => {
// The first read is an incomplete head under the bound, so the short-read
// check passes. The completed head is over the bound and must still fail.
using server = serve101(21000, 16000);
expect(await connect(server.port)).toContain(TOO_LARGE);
});

test("101 head that Node accepts opens when the first read is over max_http_header_size", async () => {
// Node opens this 16400 byte head: the bytes llhttp counts stay under 16384.
using server = serve101(16400, MAX_HTTP_HEADER_SIZE + 6);
expect(await connect(server.port)).toBe("open");
});
});

describe("WebSocket buffered handshake data", () => {
Expand Down
Loading