Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
24 changes: 24 additions & 0 deletions packages/bun-uws/src/HttpResponse.h
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ struct HttpResponse : public AsyncSocket<SSL> {

HttpResponseData<SSL> *httpResponseData = getHttpResponseData();

/* A no-body status (1xx / 204) must not carry a Content-Length header
* (RFC 9110 8.6). end() short-circuits on noBodyStatus, but tryEnd()
* reaches here directly with allowContentLength defaulted to true. */
if (httpResponseData->noBodyStatus) {
allowContentLength = false;
}
Comment thread
robobun marked this conversation as resolved.
Resolved

/* In some cases, such as when refusing huge data we want to close the connection when drained */
if (closeConnection) {
/* We can only write the header once */
Expand Down Expand Up @@ -418,6 +425,17 @@ struct HttpResponse : public AsyncSocket<SSL> {
return this;
}

/* RFC 9110 8.6: a server MUST NOT send Content-Length in a response
* with a 1xx or 204 status, and such a response never has a body. The
* status line is the one point every response passes through, so
* record that here rather than at each caller. 304 also has no body
* but MAY carry a Content-Length; callers that want it suppressed for
* 304 (node:http) set noBodyStatus themselves. */
Comment thread
robobun marked this conversation as resolved.
Resolved
if (status.length() >= 3 && (status.length() == 3 || status[3] == ' ')
&& (status[0] == '1' || (status[0] == '2' && status[1] == '0' && status[2] == '4'))) {
httpResponseData->noBodyStatus = true;
}

/* Update status */
httpResponseData->state |= HttpResponseData<SSL>::HTTP_STATUS_CALLED;

Expand All @@ -442,6 +460,12 @@ struct HttpResponse : public AsyncSocket<SSL> {
HttpResponse *writeHeader(std::string_view key, uint64_t value) {
writeStatus(HTTP_200_OK);

/* Every integer Content-Length write funnels through this overload;
* a 1xx / 204 response must not carry one (RFC 9110 8.6). */
if (getHttpResponseData()->noBodyStatus && key.length() == 14 && !strncasecmp(key.data(), "content-length", 14)) {
return this;
}

Super::write(key.data(), (int) key.length());
Super::write(": ", 2);
writeUnsigned64(value);
Expand Down
5 changes: 3 additions & 2 deletions packages/bun-uws/src/HttpResponseData.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,9 @@ struct HttpResponseData : AsyncSocketData<SSL>, HttpParser {
uint8_t idleTimeout = 10; // default HTTP_TIMEOUT 10 seconds
bool fromAncientRequest = false;
bool isConnectRequest = false;
/* 204/304 responses must not carry any body framing (no Content-Length,
* no chunked encoding, no terminating chunk), see RFC 9110 6.4.1. */
/* When set, the response carries no body framing at all: no Content-Length,
* no chunked encoding, no terminating chunk. writeStatus() sets it for 1xx
* and 204 (RFC 9110 8.6); node:http additionally sets it for 304. */
bool noBodyStatus = false;
/* The response body is delimited by connection close: write it raw with
* no Content-Length and no chunked framing, then close. Used by node:http
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/server/FileRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,15 +476,11 @@
break 'brk 416;
}
if matches!(range, RangeRequest::Result::Satisfiable { .. }) {
break 'brk 206;
}

if size == 0 && file_type == FileType::File && this.status_code == 200 {
break 'brk 204;
}

this.status_code
};

Check failure on line 483 in src/runtime/server/FileRoute.rs

View check run for this annotation

Claude / Claude Code Review

FileRoute with status 101: Content-Length suppressed but file body still streamed → keep-alive desync

The same gap exists in `FileRoute` for status 101, which `writeStatus` now also flags as `noBodyStatus` but which is not in this `204 | 205 | 304 | 307 | 308` early-return list. `new Response(Bun.file(p), { status: 101 })` as a static route reaches `write_header_int("content-length", size)` (silently dropped by the new `writeHeader(key, uint64_t)` guard) and then `FileResponseStream::start`, which ships the file bytes via OS sendfile / `HttpResponse::write()` — neither goes through `internalEnd`
Comment thread
robobun marked this conversation as resolved.
Resolved

req.set_yield(false);

Expand Down
85 changes: 52 additions & 33 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2422,6 +2422,15 @@ where

let resp = this.resp.expect("infallible: resp bound");
this.set_response(response);

// `render` drops the body for these statuses on GET, so HEAD must not
// derive framing from that body (or the user headers) either
// (RFC 9110 §9.3.2): render the exact metadata+framing GET would.
if matches!(response.status_code(), 101 | 103 | 204 | 205 | 304) {
Self::do_render_blob_corked(std::ptr::from_mut::<Self>(this));
return;
}

let Some(server) = this.server else {
// server detached?
this.render_metadata();
Expand All @@ -2432,43 +2441,59 @@ where
};
// SAFETY: BACKREF
let global_this = server.global_this();

// A body, when present, decides the framing: GET puts its byte count
// on the wire and strips any handler-supplied Content-Length /
// Transfer-Encoding, so HEAD must report the same (RFC 9110 §9.3.2).
// Only a bodiless Response leaves those headers as the sole
// description of what a GET would have sent (issue #15355).
let body_decides_framing = {
let body_value = response.get_body_value();
body_value.to_blob_if_possible();
!matches!(
body_value,
Body::Value::Used | Body::Value::Null | Body::Value::Empty | Body::Value::Error(_)
)
};
// `fast_get`/`fast_has` take `&mut self` (FFI shim), so use the `_mut`
// accessor — `get_fetch_headers()` and `get_init_headers()` alias the
// same `init.headers` field.
if let Some(headers) = response.get_init_headers_mut() {
// first respect the headers
if !HTTP3 {
if let Some(transfer_encoding) =
headers.fast_get(jsc::HTTPHeaderName::TransferEncoding)
{
// fastGet() borrows the header map's StringImpl; renderMetadata() ->
// doWriteHeaders() calls fastRemove(.TransferEncoding) and derefs the
// FetchHeaders, freeing that StringImpl before we write it. Clone so
// the bytes outlive renderMetadata().
let transfer_encoding_str = transfer_encoding.to_slice_clone();
if !body_decides_framing {
if let Some(headers) = response.get_init_headers_mut() {
// first respect the headers
if !HTTP3 {
if let Some(transfer_encoding) =
headers.fast_get(jsc::HTTPHeaderName::TransferEncoding)
{
// fastGet() borrows the header map's StringImpl; renderMetadata() ->
// doWriteHeaders() calls fastRemove(.TransferEncoding) and derefs the
// FetchHeaders, freeing that StringImpl before we write it. Clone so
// the bytes outlive renderMetadata().
let transfer_encoding_str = transfer_encoding.to_slice_clone();
this.render_metadata();
resp.write_header(b"transfer-encoding", transfer_encoding_str.slice());
this.end_without_body(this.should_close_connection());
return;
}
}
if let Some(content_length) = headers.fast_get(jsc::HTTPHeaderName::ContentLength) {
// Parse before renderMetadata(): doWriteHeaders() will fastRemove(.ContentLength)
// and deref the FetchHeaders, freeing the borrowed StringImpl.
let content_length_str = content_length.to_slice();
let len: usize = HTTP::parse_content_length(content_length_str.slice());
drop(content_length_str);

this.render_metadata();
resp.write_header(b"transfer-encoding", transfer_encoding_str.slice());
// SAFETY: FFI handle
resp.write_header_int(b"content-length", len as u64);
this.end_without_body(this.should_close_connection());
return;
}
}
if let Some(content_length) = headers.fast_get(jsc::HTTPHeaderName::ContentLength) {
// Parse before renderMetadata(): doWriteHeaders() will fastRemove(.ContentLength)
// and deref the FetchHeaders, freeing the borrowed StringImpl.
let content_length_str = content_length.to_slice();
let len: usize = HTTP::parse_content_length(content_length_str.slice());
drop(content_length_str);

this.render_metadata();
// SAFETY: FFI handle
resp.write_header_int(b"content-length", len as u64);
this.end_without_body(this.should_close_connection());
return;
}
}
// not content-length or transfer-encoding so we need to respect the body
// the body decides the framing (or there is neither a body nor a
// handler-supplied Content-Length / Transfer-Encoding header)
let body_value = response.get_body_value();
body_value.to_blob_if_possible();
match body_value {
Body::Value::InternalBlob(_) | Body::Value::WTFStringImpl(_) => {
let mut blob = body_value.use_as_any_blob_allow_non_utf8_string();
Expand Down Expand Up @@ -3448,12 +3473,6 @@ where
self.blob.size()
};

status = if status == 200 && size == 0 && !self.blob.is_detached() {
204
} else {
status
};

let (content_type, needs_content_type, content_type_needs_free) =
get_content_type(response.get_init_headers_mut(), &self.blob);
// NOTE: `MimeType` owns a `Cow<'static, [u8]>`; Drop handles the owned case.
Expand Down
11 changes: 1 addition & 10 deletions src/runtime/server/StaticRoute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,16 +480,7 @@ impl StaticRoute {
}

fn render_metadata(&self, resp: AnyResponse) {
let mut status = self.status_code;
let size = self.cached_blob_size;

status = if status == 200 && size == 0 && !self.blob.is_detached() {
204
} else {
status
};

self.do_write_status(status, resp);
self.do_write_status(self.status_code, resp);
self.do_write_headers(resp);
}

Expand Down
45 changes: 35 additions & 10 deletions test/js/bun/http/bun-serve-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,20 +137,19 @@ describe("Bun.file in serve routes", () => {

it("serves empty file", async () => {
const res = await fetch(new URL(`/empty.txt`, server.url));
expect(res.status).toBe(204);
// An empty file is a valid zero-byte representation: a plain 200 with
// `Content-Length: 0`, the same framing every other empty body form
// (`new Response("")`, `new Blob([])`, ...) gets.
expect(res.status).toBe(200);
expect(await res.text()).toBe("");
// A server MUST NOT send a Content-Length header field in any response
// with a status code of 1xx (Informational) or 204 (No Content). A server
// MUST NOT send a Content-Length header field in any 2xx (Successful)
// response to a CONNECT request (Section 9.3.6).
expect(res.headers.get("Content-Length")).toBeNull();

const headers = res.headers.toJSON();
delete headers.date;
delete headers["last-modified"];

expect(headers).toMatchInlineSnapshot(`
{
"content-length": "0",
"content-type": "text/plain;charset=utf-8",
}
`);
Expand Down Expand Up @@ -549,10 +548,36 @@ describe("Bun.file in serve routes", () => {
});

describe.concurrent("Special status codes", () => {
it("returns 204 for empty files with 200 status", async () => {
const res = await fetch(new URL(`/empty.txt`, server.url));
expect(res.status).toBe(204);
expect(await res.text()).toBe("");
// Bun used to rewrite the default 200 of an empty file-backed body to
// 204. No other empty body form got that treatment, HEAD of the same URL
// did not, and a server-invented 204 dropped the Content-Type.
it("returns 200 for empty files, for GET and HEAD alike", async () => {
for (const method of ["GET", "HEAD"]) {
const res = await fetch(new URL(`/empty.txt`, server.url), { method });
expect({ method, status: res.status, contentLength: res.headers.get("Content-Length") }).toEqual({
method,
status: 200,
contentLength: "0",
});
expect(await res.text()).toBe("");
}
});

it("returns 200 for empty files served from the fetch handler, for GET and HEAD alike", async () => {
const emptyPath = join(tempDir, "empty.txt");
using handlerServer = Bun.serve({
port: 0,
fetch: () => new Response(Bun.file(emptyPath)),
});
for (const method of ["GET", "HEAD"]) {
const res = await fetch(handlerServer.url, { method });
expect({ method, status: res.status, contentLength: res.headers.get("Content-Length") }).toEqual({
method,
status: 200,
contentLength: "0",
});
expect(await res.text()).toBe("");
}
});

it("preserves custom status for empty files", async () => {
Expand Down
8 changes: 5 additions & 3 deletions test/js/bun/http/bun-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1101,7 +1101,9 @@ describe("HEAD requests #15355", () => {
//
// Passing duplicate header entries makes FetchHeaders combine them via
// makeString(), producing a fresh StringImpl owned solely by the map so the
// remove actually frees it. `Malloc=1` routes bmalloc through the system
// remove actually frees it. The bodies are null so this stays on the
// fastGet path: HEAD only reads the handler-supplied framing headers for a
// bodiless Response. `Malloc=1` routes bmalloc through the system
// allocator so ASAN-enabled builds observe the use-after-free; release
// builds fall through and validate the header values round-trip.
test("transfer-encoding / content-length whose StringImpl is held only by the header map", async () => {
Expand All @@ -1115,14 +1117,14 @@ describe("HEAD requests #15355", () => {
port: 0,
fetch(req) {
if (req.url.endsWith("/te")) {
return new Response("hello", {
return new Response(null, {
headers: [
["Transfer-Encoding", "gzip"],
["Transfer-Encoding", "chunked"],
],
});
}
return new Response("hello", {
return new Response(null, {
headers: [
["Content-Length", "1"],
["Content-Length", "2"],
Expand Down
Loading
Loading