Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1604,7 +1604,15 @@ function renderNativeHeaders(res) {
closeDelimited = true;
res[kMustCloseConnection] = true;
} else if (res._removedContLen) {
forceChunked = true;
// Node's _storeHeader takes the `!useChunkedEncodingByDefault` branch
// (HTTP/1.0, or the user cleared the flag) before it ever auto-adds
// Transfer-Encoding, so the response is close-delimited there too.
if (res.useChunkedEncodingByDefault === false) {
closeDelimited = true;
res[kMustCloseConnection] = true;
} else {
forceChunked = true;
}
}
}

Expand Down
26 changes: 26 additions & 0 deletions src/jsc/bindings/NodeHTTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,23 @@ static bool connectionValueHasClose(const WTF::String& value)
return false;
}

// Transfer-Encoding is `1#transfer-coding` (RFC 9112 §6.1): look for the
// "chunked" token anywhere in a comma-separated list. Mirrors node:http's
// /(?:^|\W)chunked(?:$|\W)/i chunkExpression.
static bool transferEncodingHasChunked(const WTF::String& value)
{
size_t pos = 0;
while ((pos = value.findIgnoringASCIICase("chunked"_s, pos)) != WTF::notFound) {
bool leftOk = pos == 0 || !isASCIIAlphanumeric(value[pos - 1]);
size_t end = pos + 7;
bool rightOk = end >= value.length() || !isASCIIAlphanumeric(value[end]);
if (leftOk && rightOk)
return true;
pos = end;
}
return false;
}

template<bool isSSL>
static void writeFetchHeadersToUWSResponse(WebCore::FetchHeaders& headers, uWS::HttpResponse<isSSL>* res)
{
Expand Down Expand Up @@ -668,6 +685,12 @@ static void writeFetchHeadersToUWSResponse(WebCore::FetchHeaders& headers, uWS::
// Prevent automatic Transfer-Encoding: chunked insertion when user provides one
if (header.key == WebCore::HTTPHeaderName::TransferEncoding) {
data->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_TRANSFER_ENCODING_HEADER;
// The uWS writer never chunk-frames an HTTP/1.0 (fromAncientRequest)
// response on its own, but once Transfer-Encoding: chunked is on the
// wire the body MUST be chunk-framed to match it (Node does the same).
if (data->fromAncientRequest && transferEncodingHasChunked(value)) {
data->fromAncientRequest = false;
}
}

// RFC 9112 §9.6: a server that sends the "close" connection option MUST
Expand Down Expand Up @@ -766,6 +789,9 @@ static void NodeHTTPServer__writeHead(
httpResponseData->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_DATE_HEADER;
} else if (headerName == WebCore::HTTPHeaderName::TransferEncoding) {
httpResponseData->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_TRANSFER_ENCODING_HEADER;
if (httpResponseData->fromAncientRequest && transferEncodingHasChunked(value)) {
httpResponseData->fromAncientRequest = false;
}
}
}

Expand Down
87 changes: 86 additions & 1 deletion test/js/node/http/node-http-transfer-encoding.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
import { expect, test } from "bun:test";
import { describe, expect, test } from "bun:test";
import { once } from "events";
import { createServer, request } from "http";
import { AddressInfo, connect, Server } from "net";

async function rawHTTP10(port: number, path: string): Promise<{ head: string; body: string }> {
const { promise, resolve, reject } = Promise.withResolvers<{ head: string; body: string }>();
const chunks: Buffer[] = [];
const socket = connect(port, "127.0.0.1", () => {
socket.write(`GET ${path} HTTP/1.0\r\nHost: localhost\r\n\r\n`);
});
socket.on("data", d => chunks.push(d));
socket.on("error", reject);
socket.on("close", () => {
const raw = Buffer.concat(chunks).toString("latin1");
const i = raw.indexOf("\r\n\r\n");
resolve({ head: raw.slice(0, i), body: raw.slice(i + 4) });
});
return promise;
}

const fixture = "node-http-transfer-encoding-fixture.ts";
test(`should not duplicate transfer-encoding header in request`, async () => {
const { resolve, promise } = Promise.withResolvers();
Expand Down Expand Up @@ -94,3 +110,72 @@ test("should not duplicate transfer-encoding header in response when explicitly
expect(bodySection).toContain("Hello, World!");
expect(bodySection).toContain("Goodbye, World!");
});

// The declared Transfer-Encoding and the emitted body framing must agree for
// HTTP/1.0 requests; a mismatch made curl --http1.0 die with
// "curl: (56) chunk hex-length char not a hex digit".
describe("HTTP/1.0 response framing matches the advertised headers", () => {
test("removing Content-Length does not invent Transfer-Encoding: chunked", async () => {
await using server = createServer((req, res) => {
res.setHeader("Content-Length", 5);
res.removeHeader("Content-Length");
res.end("hello");
});
await once(server.listen(0, "127.0.0.1"), "listening");
const { port } = server.address() as AddressInfo;

const { head, body } = await rawHTTP10(port, "/");
// Node.js never auto-adds Transfer-Encoding here (useChunkedEncodingByDefault
// is false for HTTP/1.0); the response is close-delimited instead.
expect(head.toLowerCase()).not.toContain("transfer-encoding");
expect(head.toLowerCase()).not.toContain("content-length");
expect(head).toContain("Connection: close");
expect(body).toBe("hello");
});

test.each([
["writeHead", (res: any) => res.writeHead(200, { "Transfer-Encoding": "chunked" })],
["setHeader", (res: any) => res.setHeader("Transfer-Encoding", "chunked")],
])("an explicit Transfer-Encoding: chunked via %s chunk-frames the one-shot body", async (_, setup) => {
await using server = createServer((req, res) => {
setup(res);
res.end("hello");
});
await once(server.listen(0, "127.0.0.1"), "listening");
const { port } = server.address() as AddressInfo;

const { head, body } = await rawHTTP10(port, "/");
expect(head).toContain("Transfer-Encoding: chunked");
// Node.js chunk-frames the body to match the header it committed to.
expect(body).toBe("5\r\nhello\r\n0\r\n\r\n");
});

test("an explicit Transfer-Encoding: chunked chunk-frames streaming writes", async () => {
await using server = createServer((req, res) => {
res.writeHead(200, { "Transfer-Encoding": "chunked" });
res.write("hel");
res.end("lo");
});
await once(server.listen(0, "127.0.0.1"), "listening");
const { port } = server.address() as AddressInfo;

const { head, body } = await rawHTTP10(port, "/");
expect(head).toContain("Transfer-Encoding: chunked");
expect(body).toBe("3\r\nhel\r\n2\r\nlo\r\n0\r\n\r\n");
});

test("a Transfer-Encoding value without 'chunked' does not chunk-frame the body", async () => {
// Node.js only sets chunkedEncoding when the TE value contains the
// 'chunked' token; other codings pass through with identity body bytes.
await using server = createServer((req, res) => {
res.setHeader("Transfer-Encoding", "gzip");
res.end("hello");
});
await once(server.listen(0, "127.0.0.1"), "listening");
const { port } = server.address() as AddressInfo;

const { head, body } = await rawHTTP10(port, "/");
expect(head).toContain("Transfer-Encoding: gzip");
expect(body).toBe("hello");
});
});
Loading