From 987d2629f3ba7d0296c9685454d08cd1c7ff4d7f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 17 Oct 2026 20:58:31 +0000 Subject: [PATCH 1/5] node:http: parse the request trailer section once The wire parser's verdict on the trailer section of a chunked request keeps the fields that it accepts as field records, the form that request headers already have. req.rawTrailers is built from those records. The second parse at 'end' and the leniency flag that JS passed to it are gone. That flag was server.insecureHTTPParser === true, which is false for --insecure-http-parser and for httpValidation, so a trailer value with a control byte dropped every trailer field of the request. The raw section stays in the parser's own buffer, so a body fin that follows no verdict cannot hand it to the request. --- packages/bun-uws/src/ChunkedEncoding.h | 9 +- packages/bun-uws/src/HttpContext.h | 4 +- packages/bun-uws/src/HttpParser.h | 92 ++-- packages/bun-uws/src/HttpResponseData.h | 11 +- src/js/internal/http.ts | 13 +- src/jsc/bindings/NodeHTTP.cpp | 20 +- .../bindings/node/JSNodeHTTPServerSocket.cpp | 45 +- .../bindings/node/JSNodeHTTPServerSocket.h | 4 - src/runtime/server/NodeHTTPResponse.rs | 54 +-- .../http/node-http-request-trailers.test.ts | 439 ++++++++++++++++++ 10 files changed, 556 insertions(+), 135 deletions(-) create mode 100644 test/js/node/http/node-http-request-trailers.test.ts diff --git a/packages/bun-uws/src/ChunkedEncoding.h b/packages/bun-uws/src/ChunkedEncoding.h index 567fc941f678..9f4afa14289a 100644 --- a/packages/bun-uws/src/ChunkedEncoding.h +++ b/packages/bun-uws/src/ChunkedEncoding.h @@ -191,8 +191,9 @@ namespace uWS { * line is incomplete, i.e. before STATE_HAS_SIZE is set. _DONE means the * section (and thus the message) completed and the fin chunk was emitted; the * next call resets the state without touching the remaining bytes. The - * sub-state must not be derived from the captured section's contents: the fin - * delivery can synchronously run JS that consumes (and clears) the capture. */ + * sub-state must not be derived from the captured section's contents: the + * caller empties the capture when it takes its verdict on the section, before + * it delivers the fin (HttpParser::acceptNodeTrailerSection). */ constexpr uint64_t STATE_IS_TRAILERS = STATE_HAS_SIZE | STATE_IS_CHUNKED | STATE_WAITING_FOR_LF; constexpr uint64_t STATE_IS_TRAILERS_DONE = STATE_HAS_SIZE | STATE_WAITING_FOR_LF; @@ -228,7 +229,9 @@ namespace uWS { * 0-size chunk, capturing its raw bytes so the server can populate * req.trailers. The terminating empty chunk (fin) is only emitted once * the whole section (including its final CRLF) has been consumed, so - * trailers are always available by the time the message completes. */ + * trailers are always available by the time the message completes. + * trailerSection is the caller's buffer (HttpParser::fallback): empty + * when the 0-size chunk is read, and emptied by the caller at the fin. */ if (trailerSection && state == STATE_IS_TRAILERS) [[unlikely]] { while (data.length()) { char c = data[0]; diff --git a/packages/bun-uws/src/HttpContext.h b/packages/bun-uws/src/HttpContext.h index 696c9c6cd4cf..b54a69f2c029 100644 --- a/packages/bun-uws/src/HttpContext.h +++ b/packages/bun-uws/src/HttpContext.h @@ -425,8 +425,8 @@ struct HttpContext { /* The return value is entirely up to us to interpret. The HttpParser cares only for whether the returned value is DIFFERENT from passed user */ - /* node:http compat: the trailer capture lives in the IsNodeHttp=true ext - * block; the Bun.serve instantiation passes nullptr (and its parser + /* node:http compat: the accepted trailer fields live in the IsNodeHttp=true + * ext block; the Bun.serve instantiation passes nullptr (and its parser * instantiation contains no use of it). */ std::string *nodeHttpRequestTrailers = nullptr; if constexpr (IsNodeHttp) { diff --git a/packages/bun-uws/src/HttpParser.h b/packages/bun-uws/src/HttpParser.h index 71ed1b8dabd1..1855b423fd3b 100644 --- a/packages/bun-uws/src/HttpParser.h +++ b/packages/bun-uws/src/HttpParser.h @@ -26,6 +26,7 @@ /* The HTTP parser is an independent module subject to unit testing / fuzz testing */ #include +#include #include #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #include #include "MoveOnlyFunction.h" #include "ChunkedEncoding.h" @@ -578,7 +580,8 @@ struct HttpResponseData; bool hasBufferedPartialRequestHeaders() const { for (char c : fallback) { if (!isNewline((unsigned char) c)) { - return true; + /* With a body in flight, the buffer holds that body's trailer section. */ + return !remainingStreamingBytes; } } return false; @@ -600,19 +603,18 @@ struct HttpResponseData; static constexpr unsigned MAX_TRAILER_FIELDS = UWS_HTTP_MAX_HEADERS_COUNT - 1; /* Parse a complete trailer section (the bytes between the 0-size chunk and the - * final CRLF, as captured into nodeHttpRequestTrailers) into key/value pairs, + * final CRLF, as the chunk iterator captured them) into key/value pairs, * reusing the same consumeFieldName / tryConsumeFieldValue / OWS-trim primitives * that getHeaders uses for the main request header block. Wire casing of * field names is preserved (req.rawTrailers). Returns the number of fields * written to out[]. The captured section is raw wire bytes (the chunk * iterator only size-caps it), so this is also the only gate on NUL / - * bare-CR/LF in a trailer line: any malformed line makes the call return 0 - * and no trailer is surfaced, where Node's llhttp rejects the message. + * bare-CR/LF in a trailer line: any malformed line makes the call return 0. * Consumes the section: it is post-padded in place and the returned * string_views point into it, so it must outlive their use. * KEEP IN LOCKSTEP with getHeaders' field-line loop below (same * consumeFieldName → tryConsumeFieldValue → CRLF/OWS sequence). */ - static unsigned parseTrailerFields(std::string §ion, std::pair *out, bool useInsecureHTTPParser = false, unsigned outCapacity = MAX_TRAILER_FIELDS) { + static unsigned parseTrailerFields(std::string §ion, std::pair *out, bool useInsecureHTTPParser, unsigned outCapacity = MAX_TRAILER_FIELDS) { if (section.size() < 4) { return 0; } @@ -662,11 +664,25 @@ struct HttpResponseData; return count; } - /* node:http compat: validate a captured, complete trailer section before the - * message is completed. Node's llhttp fails the message on a malformed trailer - * field line (clientError HPE_INVALID_HEADER_TOKEN) instead of completing it - * with req.trailers silently dropped; a CTL byte in a value is only accepted - * under insecureHTTPParser, exactly like a header value. A Content-Length or + /* node:http gets the header fields of a request, and the trailer fields that acceptNodeTrailerSection() + * accepted, as a run of field records (NodeHTTP.cpp reads it). A field record is + * [u32 nameLen][u32 valueLen][name][value]. These are its two lengths, little-endian. u32: maxHeaderSize + * has no upper bound, and a u16 would truncate a value over 64 KiB and desync the run. */ + static std::array fieldRecordLengths(std::string_view name, std::string_view value) { + const uint32_t nameLen = (uint32_t) name.length(); + const uint32_t valueLen = (uint32_t) value.length(); + return { + (uint8_t) (nameLen & 0xff), (uint8_t) ((nameLen >> 8) & 0xff), (uint8_t) ((nameLen >> 16) & 0xff), (uint8_t) (nameLen >> 24), + (uint8_t) (valueLen & 0xff), (uint8_t) ((valueLen >> 8) & 0xff), (uint8_t) ((valueLen >> 16) & 0xff), (uint8_t) (valueLen >> 24) + }; + } + + private: + /* node:http compat: the verdict on the trailer section of a chunked request, taken once: when the + * section is complete, before the fin completes the message. Node's llhttp fails the message on a + * malformed trailer field line (clientError HPE_INVALID_HEADER_TOKEN). llhttp does so at the offending + * byte, this parser when the final CRLF of the section arrives. A CTL byte in a value is only + * accepted under insecureHTTPParser, exactly like a header value. A Content-Length or * Transfer-Encoding field in the trailer section is rejected exactly like * llhttp does (it runs trailers through the same header state machine, so * the already-set F_CHUNKED collides), unless insecureHTTPParser is set @@ -674,27 +690,39 @@ struct HttpResponseData; * section (bare CRLF, no trailers) is valid. Node counts trailer fields from * zero against server.maxHeadersCount (maxHeadersCount here, 0 = not set). * + * The fields of an accepted section go to *records, a field record each (fieldRecordLengths()), and only + * after every field passed every rule: a rejected section leaves no record. req.rawTrailers is built from + * the records, so no later step parses the section or decides again what it holds. The section itself + * never leaves the parser: it is emptied here, whatever the verdict. + * * Known bound: parseTrailerFields stops at MAX_TRAILER_FIELDS, so a section with * more valid fields than that followed by a malformed line is accepted where node * still errors; reaching it requires a deliberately padded (but size-capped) * section, and rejecting it would need a second scanning mode. */ - static HttpParserError validateNodeTrailerSection(const std::string *section, bool useInsecureHTTPParser, bool useLenientTransferEncoding, uint32_t maxHeadersCount) { - if (!section || section->size() <= 2) { + HttpParserError acceptNodeTrailerSection(std::string *records, bool useInsecureHTTPParser, bool useLenientTransferEncoding, uint32_t maxHeadersCount) { + struct ClearOnReturn { + std::string §ion; + ~ClearOnReturn() { section.clear(); } + } clearOnReturn { fallback }; + if (fallback.size() <= 2) { return HTTP_PARSER_ERROR_NONE; } - /* parseTrailerFields consumes (post-pads) its input, so validate a copy. */ - std::string copy(*section); - std::pair scratch[MAX_TRAILER_FIELDS]; - unsigned count = parseTrailerFields(copy, scratch, useInsecureHTTPParser); + /* A record holds the length of a field in 32 bits. */ + if (fallback.size() > UINT32_MAX) { + return HTTP_PARSER_ERROR_TRAILER_FIELDS_TOO_LARGE; + } + std::pair fields[MAX_TRAILER_FIELDS]; + unsigned count = parseTrailerFields(fallback, fields, useInsecureHTTPParser); if (count == 0) { return HTTP_PARSER_ERROR_INVALID_HEADER_TOKEN; } if (maxHeadersCount && count > maxHeadersCount) { return HTTP_PARSER_ERROR_TRAILER_FIELDS_TOO_LARGE; } - if (!useLenientTransferEncoding) { - for (unsigned i = 0; i < count; i++) { - std::string_view name = scratch[i].first; + size_t recordsSize = 0; + for (unsigned i = 0; i < count; i++) { + std::string_view name = fields[i].first; + if (!useLenientTransferEncoding) { if (name.length() == 14 && !strncasecmp(name.data(), "content-length", 14)) { return HTTP_PARSER_ERROR_TRAILER_CONTENT_LENGTH; } @@ -702,11 +730,18 @@ struct HttpResponseData; return HTTP_PARSER_ERROR_INVALID_TRANSFER_ENCODING; } } + recordsSize += 8 + name.length() + fields[i].second.length(); + } + records->reserve(recordsSize); + for (unsigned i = 0; i < count; i++) { + const std::array lens = fieldRecordLengths(fields[i].first, fields[i].second); + records->append((const char *) lens.data(), lens.size()).append(fields[i].first).append(fields[i].second); } return HTTP_PARSER_ERROR_NONE; } - private: + /* A field section that is not complete yet: the head of the next request while no body is in flight, or + * (node:http) the trailer section of the chunked body in flight, until acceptNodeTrailerSection(). */ std::string fallback; public: /* node:http under LENIENT_TRANSFER_ENCODING: the current request's @@ -1502,11 +1537,13 @@ struct HttpResponseData; /* We already validated that chunked is last if present, before calling the handler */ remainingStreamingBytes = STATE_IS_CHUNKED; *chunkedExtensionsByteCount = 0; + /* node:http captures the trailer section of this body in fallback. */ + ASSERT(fallback.empty()); /* If consume minimally, we do not want to consume anything but we want to mark this as being chunked */ if constexpr (!ConsumeMinimally) { /* Go ahead and parse it (todo: better heuristics for emitting FIN to the app level) */ std::string_view dataToConsume(data, length); - for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, nodeHttpRequestTrailers, maxBufferedHeaderSize)) { + for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, IsNodeHttp ? &fallback : nullptr, maxBufferedHeaderSize)) { /* llhttp errors at the offending extension byte, before any body bytes from * that chunk reach the application; check before every dispatch. */ if (*chunkedExtensionsByteCount > MAX_CHUNK_EXTENSION_SIZE) [[unlikely]] { @@ -1515,7 +1552,7 @@ struct HttpResponseData; /* The fin dispatch completes the message: a malformed or * framing-field trailer must fail it first (node: HPE_*). */ if (IsNodeHttp && chunk.length() == 0) { - if (HttpParserError trailerError = validateNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { + if (HttpParserError trailerError = acceptNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { return HttpParserResult::error(HTTP_ERROR_400_BAD_REQUEST, trailerError); } } @@ -1606,14 +1643,14 @@ struct HttpResponseData; } else if (isParsingChunkedEncoding(remainingStreamingBytes)) { /* It's either chunked or with a content-length */ std::string_view dataToConsume(data, length); - for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, nodeHttpRequestTrailers, maxFallbackSize)) { + for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, IsNodeHttp ? &fallback : nullptr, maxFallbackSize)) { if (*chunkedExtensionsByteCount > MAX_CHUNK_EXTENSION_SIZE) [[unlikely]] { return HttpParserResult::error(HTTP_ERROR_413_PAYLOAD_TOO_LARGE, HTTP_PARSER_ERROR_CHUNK_EXTENSIONS_OVERFLOW); } /* The fin dispatch completes the message: a malformed or * framing-field trailer must fail it first (node: HPE_*). */ if (IsNodeHttp && chunk.length() == 0) { - if (HttpParserError trailerError = validateNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { + if (HttpParserError trailerError = acceptNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { return HttpParserResult::error(HTTP_ERROR_400_BAD_REQUEST, trailerError); } } @@ -1702,6 +1739,7 @@ struct HttpResponseData; * of "had" being larger than what we consumed, and that we would drop data */ /* The answer was user, so the parser is alive: it gets the block back for the next head that takes several reads. */ reassembled.clear(); + ASSERT(fallback.empty()); fallback = std::move(reassembled); data += consumedBytes - had; length -= consumedBytes - had; @@ -1722,14 +1760,14 @@ struct HttpResponseData; } else if (isParsingChunkedEncoding(remainingStreamingBytes)) { /* It's either chunked or with a content-length */ std::string_view dataToConsume(data, length); - for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, nodeHttpRequestTrailers, maxFallbackSize)) { + for (auto chunk : uWS::ChunkIterator(&dataToConsume, &remainingStreamingBytes, false, chunkedExtensionsByteCount, IsNodeHttp ? &fallback : nullptr, maxFallbackSize)) { if (*chunkedExtensionsByteCount > MAX_CHUNK_EXTENSION_SIZE) [[unlikely]] { return HttpParserResult::error(HTTP_ERROR_413_PAYLOAD_TOO_LARGE, HTTP_PARSER_ERROR_CHUNK_EXTENSIONS_OVERFLOW); } /* The fin dispatch completes the message: a malformed or * framing-field trailer must fail it first (node: HPE_*). */ if (IsNodeHttp && chunk.length() == 0) { - if (HttpParserError trailerError = validateNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { + if (HttpParserError trailerError = acceptNodeTrailerSection(nodeHttpRequestTrailers, useInsecureHTTPParser, useLenientTransferEncoding, maxHeadersCount)) [[unlikely]] { return HttpParserResult::error(HTTP_ERROR_400_BAD_REQUEST, trailerError); } } @@ -1801,6 +1839,8 @@ struct HttpResponseData; if (length) { if (length < maxFallbackSize) { + /* A partial head, so no body is in flight. */ + ASSERT(!remainingStreamingBytes); fallback.append(data, length); } else { return HttpParserResult::error(HTTP_ERROR_431_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_PARSER_ERROR_REQUEST_HEADER_FIELDS_TOO_LARGE); diff --git a/packages/bun-uws/src/HttpResponseData.h b/packages/bun-uws/src/HttpResponseData.h index 454793c07481..62ff84120f49 100644 --- a/packages/bun-uws/src/HttpResponseData.h +++ b/packages/bun-uws/src/HttpResponseData.h @@ -292,11 +292,12 @@ struct HttpResponseData : HttpResponseData { * chunked framing for the response body. HTTP_NODE_HAS_RESPONSE_TRAILERS in * the shared flags word mirrors !empty(). */ std::string nodeHttpResponseTrailers; - /* Raw bytes of the trailer section received after the final 0-size chunk - * of the current request's chunked body, including its terminating CRLF. - * Cleared when a new request is dispatched; consumed by the JS layer when - * the request reaches EOF (req.trailers/rawTrailers). The parser gets it - * as a nullable pointer (see HttpParser::consumePostPadded). */ + /* The trailer fields that the parser accepted after the final 0-size chunk + * of the current request's chunked body, as field records + * (HttpParser::fieldRecordLengths): never raw wire bytes. Cleared when a + * new request is dispatched; moved onto the request at its body fin + * (req.trailers/rawTrailers). The parser gets it as a nullable pointer + * (see HttpParser::consumePostPadded). */ std::string nodeHttpRequestTrailers; bool headersCompleted = false; /* Timeout sweep already reported this message; reset when it completes. */ diff --git a/src/js/internal/http.ts b/src/js/internal/http.ts index e7c046ac88c5..e0dbaee083ec 100644 --- a/src/js/internal/http.ts +++ b/src/js/internal/http.ts @@ -136,16 +136,13 @@ function emitEOFIncomingMessageOuter(self) { self.complete = true; // node:http server: trailer fields received after a chunked request body // populate req.trailers/rawTrailers before 'end' is emitted, like Node's - // parserOnMessageComplete. Native moved the section onto THIS request's - // handle at its body fin, so pipelined requests can neither inherit nor - // overwrite another request's trailers. + // parserOnMessageComplete. Native moved the fields that the parser accepted + // onto THIS request's handle at its body fin, so pipelined requests can + // neither inherit nor overwrite another request's trailers. // Trailers can only follow a chunked request body: a no-body request has - // none, so skip the native call (and the socket/server option walk) for the - // common GET/HEAD case. + // none, so skip the native call for the common GET/HEAD case. if (self[kHandle] !== undefined && !self[noBodySymbol]) { - // The lenient (insecureHTTPParser) value bytes must match what the parser - // accepted on the wire, or a CTL byte in a trailer value would vanish here. - const rawTrailers = self[kHandle].takeRequestTrailers(self.socket?.server?.insecureHTTPParser === true); + const rawTrailers = self[kHandle].takeRequestTrailers(); if (rawTrailers !== undefined) { self._addHeaderLines(rawTrailers, rawTrailers.length); } diff --git a/src/jsc/bindings/NodeHTTP.cpp b/src/jsc/bindings/NodeHTTP.cpp index 1290a9a55a1e..5716e974cef1 100644 --- a/src/jsc/bindings/NodeHTTP.cpp +++ b/src/jsc/bindings/NodeHTTP.cpp @@ -80,7 +80,7 @@ static bool svValueHasToken(std::string_view value, std::string_view lowerToken) // One pass over the request: append url, method and jsNumber(dispatch // bitfield) to `args`, and capture the raw header bytes into `flatHeaders` -// as [u32 nameLen][u32 valueLen][name][value]... so req.rawHeaders / +// as field records (uWS::HttpParser::fieldRecordLengths) so req.rawHeaders / // req.headers can be materialized lazily (Bun__NodeHTTP__buildRawHeadersArray, // Bun__NodeHTTP__buildHeadersObject) only when user code reads them. static void assignHeadersFromUWebSocketsForCall(uWS::HttpRequest* request, JSValue methodString, MarkedArgumentBuffer& args, WTF::Vector& flatHeaders, JSC::JSGlobalObject* globalObject, JSC::VM& vm) @@ -111,18 +111,8 @@ static void assignHeadersFromUWebSocketsForCall(uWS::HttpRequest* request, JSVal const std::string_view name = pair.first; const std::string_view value = pair.second; - // u32 length prefixes: header sizes are usually tiny, but maxHeaderSize - // is user-configurable with no upper bound, so a u16 would silently - // truncate a >64 KiB value and desync the buffer. - const uint32_t nameLen = static_cast(name.length()); - const uint32_t valueLen = static_cast(value.length()); - uint8_t lens[8] = { - static_cast(nameLen & 0xff), static_cast((nameLen >> 8) & 0xff), - static_cast((nameLen >> 16) & 0xff), static_cast(nameLen >> 24), - static_cast(valueLen & 0xff), static_cast((valueLen >> 8) & 0xff), - static_cast((valueLen >> 16) & 0xff), static_cast(valueLen >> 24) - }; - flatHeaders.append(std::span { lens, 8 }); + const std::array lens = uWS::HttpParser::fieldRecordLengths(name, value); + flatHeaders.append(std::span { lens }); flatHeaders.append(std::span { reinterpret_cast(name.data()), name.length() }); flatHeaders.append(std::span { reinterpret_cast(value.data()), value.length() }); @@ -176,7 +166,8 @@ static String headerValueString(NodeHTTPRequestHeaderValues& remembered, HTTPHea return *slot; } -// The next [u32 nameLen][u32 valueLen][name][value] of what assignHeadersFromUWebSocketsForCall captured. +// The next field record (uWS::HttpParser::fieldRecordLengths) of a run: the header fields that +// assignHeadersFromUWebSocketsForCall captured, or the trailer fields that the parser accepted. static bool nextCapturedHeader(const uint8_t* data, size_t length, size_t& offset, std::span& name, std::span& value) { if (offset + 8 > length) @@ -280,6 +271,7 @@ static JSString* sameHeaderValue(VM& vm, JSObject* headers, const Identifier& na // touches req.rawHeaders, or req.headers of a request that Bun__NodeHTTP__buildHeadersObject // leaves to JS (via NodeHTTPResponse.takeRawHeaders). `encodedHeaders` is req.headers when // that was read first: built from these bytes, it has the value strings already. +// Also builds req.rawTrailers, from the fields that the parser accepted (NodeHTTPResponse.takeRequestTrailers). extern "C" EncodedJSValue Bun__NodeHTTP__buildRawHeadersArray(JSC::JSGlobalObject* globalObject, const uint8_t* data, size_t length, EncodedJSValue encodedHeaders) { auto& vm = JSC::getVM(globalObject); diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp index 67990a061c7f..8ae3bea3eba8 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp @@ -240,7 +240,8 @@ static std::string* requestTrailersFor(us_socket_t* socket) return &httpResponseData->nodeHttpRequestTrailers; } -/* Move the connection's captured trailer section out, returning its (ptr, length) +/* Move the trailer fields that the parser accepted for the connection's current request + * (field records, see uWS::HttpParser::fieldRecordLengths) out, returning their (ptr, length) * through a thread-local buffer that stays valid until the next call on this * thread. Called by NodeHTTPResponse at the request's body fin, still inside the * parser, so a pipelined request cannot overwrite or inherit another's trailers. */ @@ -261,48 +262,6 @@ extern "C" size_t Bun__NodeHTTP__takeRequestTrailerBytes(bool is_ssl, us_socket_ return taken.size(); } -/* Parse a raw trailer section into a flat [name, value, ...] JSArray, or - * jsUndefined() when it contains no fields. */ -extern "C" JSC::EncodedJSValue Bun__NodeHTTP__parseRequestTrailers(JSC::JSGlobalObject* globalObject, const char* data, size_t length, bool useInsecureHTTPParser) -{ - auto& vm = globalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - - /* parseTrailerFields post-pads the section in place, so it needs an owned copy. */ - std::string section(data, length); - - /* Parse with the same field-line primitives the request-header parser uses - * (uWS::HttpParser::consumeFieldName / tryConsumeFieldValue / OWS-trim). */ - std::pair fields[uWS::HttpParser::MAX_TRAILER_FIELDS]; - unsigned count = uWS::HttpParser::parseTrailerFields(section, fields, useInsecureHTTPParser); - if (count == 0) { - return JSC::JSValue::encode(JSC::jsUndefined()); - } - - JSC::JSArray* array = JSC::constructEmptyArray(globalObject, nullptr, count * 2); - RETURN_IF_EXCEPTION(scope, {}); - - unsigned index = 0; - for (unsigned i = 0; i < count; i++) { - // HTTP/1.1 obs-text bytes (0x80-0xFF) are valid header content (RFC 9110 §5.5); preserve - // them 1:1 as Latin-1 like Node's req.rawTrailers (OneByteString) and like NodeHTTP.cpp's - // rawHeaders construction. UTF-8 decoding would corrupt them to U+FFFD. - std::span nameData; - auto nameString = WTF::String::createUninitialized(fields[i].first.size(), nameData); - if (!fields[i].first.empty()) - memcpy(nameData.data(), fields[i].first.data(), fields[i].first.size()); - array->putDirectIndex(globalObject, index++, JSC::jsString(vm, nameString)); - RETURN_IF_EXCEPTION(scope, {}); - std::span valueData; - auto valueString = WTF::String::createUninitialized(fields[i].second.size(), valueData); - if (!fields[i].second.empty()) - memcpy(valueData.data(), fields[i].second.data(), fields[i].second.size()); - array->putDirectIndex(globalObject, index++, JSC::jsString(vm, valueString)); - RETURN_IF_EXCEPTION(scope, {}); - } - return JSC::JSValue::encode(array); -} - template static std::string& responseTrailersFor(us_socket_t* socket) { diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocket.h b/src/jsc/bindings/node/JSNodeHTTPServerSocket.h index 7f553e1f540f..42ad3f176006 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocket.h +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocket.h @@ -159,10 +159,6 @@ class JSNodeHTTPServerSocket : public JSC::JSDestructibleObject { /* The WebSocket that adopted the connection reads from here on. */ void releaseTunnelReadsForUpgrade(); - /* Trailer fields received after the current request's chunked body, as a - * flat [name, value, ...] JS array preserving wire casing; jsUndefined() - * when there are none. Clears the captured section. */ - /* Set the trailer fields (pre-rendered "name: value\r\n" lines) to write * between the terminating 0 chunk and the final CRLF of the current * response's chunked body. */ diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 88f212f60932..5320d2a3c4eb 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -92,10 +92,12 @@ pub(crate) struct NodeHTTPResponse { pub(crate) promise: JsCell, // Strong.Optional pub(crate) server: AnyServer, - /// node:http: the raw trailer section that followed THIS request's chunked - /// body. Moved off the connection's single per-parse buffer the moment the - /// body finishes (still inside the parser), because a pipelined request's - /// parse would otherwise overwrite it before this request's JS reads it. + /// node:http: the trailer fields the parser accepted after THIS request's + /// chunked body, as [u32 nameLen][u32 valueLen][name][value]... like + /// raw_request_headers. Moved off the connection's single per-parse buffer + /// the moment the body finishes (still inside the parser), because a + /// pipelined request's parse would otherwise overwrite them before this + /// request's JS reads them. pub(crate) request_trailers: JsCell>, /// The JS wrapper whose `ondata` slot was armed for THIS request body. `get_this_value()` /// resolves through the socket's current response, which under pipelining is a different @@ -191,24 +193,18 @@ unsafe extern "C" { safe fn Bun__NodeHTTP__notifyWhenReadParsed(ssl: core::ffi::c_int, socket: *mut c_void) -> bool; - // Moves the connection's captured node:http request-trailer section out. `*out` points into + // Moves the trailer fields the parser accepted for the connection's current node:http request + // out ([u32 nameLen][u32 valueLen][name][value]...). `*out` points into // a C++ thread-local valid until the next call on this thread; caller copies immediately. - // Returns 0 when nothing captured or socket closed. + // Returns 0 when there are none or the socket is closed. safe fn Bun__NodeHTTP__takeRequestTrailerBytes( is_ssl: bool, socket: *mut c_void, out: *mut *const u8, ) -> usize; - // Parses a raw trailer section into a flat [name, value, ...] JSArray, or - // jsUndefined() when it contains no fields. - safe fn Bun__NodeHTTP__parseRequestTrailers( - global_object: &JSGlobalObject, - data: *const u8, - length: usize, - use_insecure_http_parser: bool, - ) -> JSValue; // Builds req.rawHeaders' flat [name, value, ...] JSArray from the header - // bytes captured at dispatch ([u32 nameLen][u32 valueLen][name][value]...). + // bytes captured at dispatch ([u32 nameLen][u32 valueLen][name][value]...), + // and req.rawTrailers' from the accepted trailer fields, which have that form. // `headers` is req.headers if that was built first, for its value strings. safe fn Bun__NodeHTTP__buildRawHeadersArray( global_object: &JSGlobalObject, @@ -470,9 +466,9 @@ impl NodeHTTPResponse { } /// Called at this request's body fin, still inside the parser: move the - /// connection's captured trailer section onto this request before the next - /// pipelined message's parse can overwrite it. A no-op unless a chunked - /// body's trailer section was captured for this exact message. + /// connection's accepted trailer fields onto this request before the next + /// pipelined message's parse can overwrite them. A no-op unless the parser + /// accepted trailer fields for this exact message. fn capture_request_trailers(&self) { let flags = self.flags.get(); if flags.contains(Flags::SOCKET_CLOSED) || flags.contains(Flags::UPGRADED) { @@ -2470,26 +2466,24 @@ impl NodeHTTPResponse { Ok(headers) } - /// `handle.takeRequestTrailers()` — this request's captured trailer section - /// parsed into a flat [name, value, ...] array, or undefined. Consumes it. + /// `handle.takeRequestTrailers()` — the trailer fields the parser accepted + /// for this request as a flat [name, value, ...] array, or undefined when + /// it has none (or they were already taken). Consumes them. pub(crate) fn take_request_trailers( &self, global_object: &JSGlobalObject, - callframe: &CallFrame, + _callframe: &CallFrame, ) -> JsResult { - let section = self.request_trailers.replace(Vec::new()); - if section.is_empty() { + let fields = self.request_trailers.replace(Vec::new()); + if fields.is_empty() { return Ok(JSValue::UNDEFINED); } - // Lenient (insecureHTTPParser) servers accept CTL bytes in trailer values on - // the wire; parse them with the same leniency so they surface on req.trailers. - let use_insecure_http_parser = callframe.argument(0).to_boolean(); bun_jsc::call_zero_is_throw(global_object, || { - Bun__NodeHTTP__parseRequestTrailers( + Bun__NodeHTTP__buildRawHeadersArray( global_object, - section.as_ptr(), - section.len(), - use_insecure_http_parser, + fields.as_ptr(), + fields.len(), + JSValue::UNDEFINED, ) }) } diff --git a/test/js/node/http/node-http-request-trailers.test.ts b/test/js/node/http/node-http-request-trailers.test.ts new file mode 100644 index 000000000000..09bba2d39cfa --- /dev/null +++ b/test/js/node/http/node-http-request-trailers.test.ts @@ -0,0 +1,439 @@ +/** + * All tests in this file run in both Bun and Node.js: `bun test` runs them + * here, and the last test runs this same file under Node.js. + * + * The trailer fields that a request has at 'end' are the ones its HTTP parser + * accepted, as the wire carried them. Node hands them over once, when the + * message completes, and nothing parses or judges them a second time: + * https://github.com/nodejs/node/blob/v26.3.0/lib/_http_common.js#L143-L152 + * The expected values below were recorded from Node v26.3.0. + */ +import assert from "node:assert"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { readFileSync } from "node:fs"; +import http from "node:http"; +import https from "node:https"; +import { connect, type AddressInfo } from "node:net"; +import { dirname, join } from "node:path"; +import type { Duplex } from "node:stream"; +import { describe, test } from "node:test"; +import { connect as tlsConnect } from "node:tls"; +import { fileURLToPath } from "node:url"; + +// Only in Bun: the environment that silences a debug build, and the path of Node.js for the last test. +const harness = typeof Bun !== "undefined" ? await import("harness") : undefined; + +const fixtures = join(dirname(fileURLToPath(import.meta.url)), "fixtures"); +const cert = readFileSync(join(fixtures, "cert.pem"), "utf8"); +const key = readFileSync(join(fixtures, "cert.key"), "utf8"); + +// Node v26.3.0 and Bun have the httpValidation option. A Node without it ignores the option. +const validationTest = process.versions.bun || "httpValidation" in http.createServer() ? test : test.skip; +// Where Bun does not do what Node v26.3.0 does. Each case says what Node does. +const bunOnlyTest = process.versions.bun ? test : test.skip; + +const relaxed = { httpValidation: "relaxed" } as http.ServerOptions; + +async function withServer(server: http.Server | https.Server, run: (port: number) => Promise) { + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + try { + await run((server.address() as AddressInfo).port); + } finally { + server.closeAllConnections(); + server.close(); + } +} + +type Outcome = { trailers: Record; raw: string[] } | { clientError: string | undefined }; + +// Sends `payload` on one connection. Answers what the request has at its 'end', or the code of the 'clientError'. +// `event` is "request", or "upgrade": its listener gets the socket where "request" gets the response. +async function outcomeOf( + server: http.Server | https.Server, + payload: string, + { event = "request", secure = false } = {}, +) { + const { promise, resolve, reject } = Promise.withResolvers(); + const opened: { destroy(): unknown }[] = []; + server.on(event, (req: http.IncomingMessage, resOrSocket: http.ServerResponse | Duplex) => { + opened.push(resOrSocket.on("error", () => {})); + req.resume(); + req.on("end", () => { + resolve({ trailers: { ...req.trailers }, raw: [...req.rawTrailers] }); + resOrSocket.end(); + }); + }); + server.on("clientError", (err: NodeJS.ErrnoException, socket: Duplex) => { + socket.destroy(); + resolve({ clientError: err.code }); + }); + await withServer(server, async port => { + const socket = secure + ? tlsConnect({ port, host: "127.0.0.1", rejectUnauthorized: false }) + : connect(port, "127.0.0.1"); + opened.push(socket); + socket.on("error", reject); + socket.on("close", () => reject(new Error("the connection closed with no 'end' and no 'clientError'"))); + socket.once(secure ? "secureConnect" : "connect", () => socket.write(payload, "latin1")); + try { + await promise; + } finally { + for (const each of opened) each.destroy(); + } + }); + return promise; +} + +// The parser of a lenient server accepts a control byte in a trailer value. The request then has every field of +// the section, whichever option or flag made the server lenient. +describe("a trailer value with a control byte on a lenient server", () => { + const request = + "POST / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n" + + "3\r\nabc\r\n0\r\nT: a\x01b\r\nU: 1\r\n\r\n"; + const delivered = { trailers: { t: "a\x01b", u: "1" }, raw: ["T", "a\x01b", "U", "1"] }; + + test("insecureHTTPParser: true", async () => { + assert.deepStrictEqual(await outcomeOf(http.createServer({ insecureHTTPParser: true }), request), delivered); + }); + + test("server.insecureHTTPParser = 1 before listen()", async () => { + const server = Object.assign(http.createServer(), { insecureHTTPParser: 1 }); + assert.deepStrictEqual(await outcomeOf(server, request), delivered); + }); + + // Node reads the option once, when it accepts the connection. + test("insecureHTTPParser: true that the 'request' listener sets to false", async () => { + const server = http.createServer({ insecureHTTPParser: true }); + server.on("request", () => { + Object.assign(server, { insecureHTTPParser: false }); + }); + assert.deepStrictEqual(await outcomeOf(server, request), delivered); + }); + + validationTest('httpValidation: "relaxed"', async () => { + assert.deepStrictEqual(await outcomeOf(http.createServer(relaxed), request), delivered); + }); + + validationTest('httpValidation: "insecure"', async () => { + const server = http.createServer({ httpValidation: "insecure" } as http.ServerOptions); + assert.deepStrictEqual(await outcomeOf(server, request), delivered); + }); + + validationTest('server.httpValidation = "relaxed" before listen()', async () => { + const server = Object.assign(http.createServer(), { httpValidation: "relaxed" }); + assert.deepStrictEqual(await outcomeOf(server, request), delivered); + }); + + validationTest('https, httpValidation: "relaxed"', async () => { + const server = https.createServer({ cert, key, ...relaxed } as https.ServerOptions); + assert.deepStrictEqual(await outcomeOf(server, request, { secure: true }), delivered); + }); + + validationTest('an Upgrade request with a body, httpValidation: "relaxed"', async () => { + const upgrade = + "POST / HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: custom\r\nTransfer-Encoding: chunked\r\n\r\n" + + "3\r\nabc\r\n0\r\nT: a\x01b\r\nU: 1\r\n\r\n"; + assert.deepStrictEqual(await outcomeOf(http.createServer(relaxed), upgrade, { event: "upgrade" }), delivered); + }); + + // The flag is for the whole process, so its rows run in a child of this runtime. A strict option wins over it. + validationTest("--insecure-http-parser", async () => { + const script = ` + const { createServer } = require("node:http"); + const { connect } = require("node:net"); + const { once } = require("node:events"); + async function outcomeOf(options) { + const { promise, resolve } = Promise.withResolvers(); + const server = createServer(options, (req, res) => { + req.resume(); + req.on("end", () => { + resolve(req.rawTrailers); + res.end(); + }); + }); + server.on("clientError", (err, socket) => { + socket.destroy(); + resolve(err.code); + }); + await once(server.listen(0, "127.0.0.1"), "listening"); + const socket = connect(server.address().port, "127.0.0.1", () => socket.write(${JSON.stringify(request)}, "latin1")); + socket.on("error", () => {}); + const outcome = await promise; + socket.destroy(); + server.close(); + return outcome; + } + (async () => { + console.log(JSON.stringify({ + flagAlone: await outcomeOf({}), + insecureHTTPParserFalse: await outcomeOf({ insecureHTTPParser: false }), + httpValidationStrict: await outcomeOf({ httpValidation: "strict" }), + })); + })(); + `; + const child = spawn(process.execPath, ["--insecure-http-parser", "-e", script], { + env: harness?.bunEnv ?? process.env, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", chunk => (stdout += chunk)); + child.stderr.setEncoding("utf8").on("data", chunk => (stderr += chunk)); + const [exitCode] = await once(child, "close"); + assert.deepStrictEqual( + { stdout: exitCode === 0 ? JSON.parse(stdout) : stdout + stderr, exitCode }, + { + stdout: { + flagAlone: delivered.raw, + insecureHTTPParserFalse: "HPE_INVALID_HEADER_TOKEN", + httpValidationStrict: "HPE_INVALID_HEADER_TOKEN", + }, + exitCode: 0, + }, + ); + }); +}); + +// Sends `payload` on one connection and resolves when the server has closed it. +async function roundtrip(port: number, payload: string) { + const socket = connect(port, "127.0.0.1"); + socket.resume(); + socket.write(payload, "latin1"); + await once(socket, "close"); +} + +test("trailers keep their wire names and bytes, and leave the headers of the next request alone", async () => { + const seen: unknown[] = []; + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + seen.push({ + url: req.url, + host: req.headers.host, + contentType: req.headers["content-type"], + raw: [...req.rawTrailers], + trailers: { ...req.trailers }, + }); + res.end(); + }); + }); + await withServer(server, port => + roundtrip( + port, + "POST /a HTTP/1.1\r\nHost: first\r\nContent-Type: text/a\r\nTransfer-Encoding: chunked\r\n\r\n" + + "3\r\nabc\r\n0\r\n" + + "X-Mixed-Case: one\r\n" + + "x-mixed-case: two\r\n" + + // Named like request headers whose last value Bun remembers from one request to the next. + "Host: trailer-host\r\n" + + "content-type: text/trailer\r\n" + + "ETag: \xe9\xff\x80\r\n" + + "X-Empty:\r\n" + + "X-Ows: \t padded \t\r\n" + + "Set-Cookie: a=1\r\n" + + "set-cookie: b=2\r\n" + + "\r\n" + + "POST /b HTTP/1.1\r\nHost: second\r\nContent-Type: text/b\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n" + + "0\r\nHost: second-trailer\r\n\r\n", + ), + ); + assert.deepStrictEqual(seen, [ + { + url: "/a", + host: "first", + contentType: "text/a", + raw: [ + ...["X-Mixed-Case", "one", "x-mixed-case", "two", "Host", "trailer-host", "content-type", "text/trailer"], + ...["ETag", "\xe9\xff\x80", "X-Empty", "", "X-Ows", "padded", "Set-Cookie", "a=1", "set-cookie", "b=2"], + ], + trailers: { + "x-mixed-case": "one, two", + host: "trailer-host", + "content-type": "text/trailer", + etag: "\xe9\xff\x80", + "x-empty": "", + "x-ows": "padded", + "set-cookie": ["a=1", "b=2"], + }, + }, + { + url: "/b", + host: "second", + contentType: "text/b", + raw: ["Host", "second-trailer"], + trailers: { host: "second-trailer" }, + }, + ]); +}); + +test("a trailer value over 64 KiB keeps the field after it", async () => { + const big = Buffer.alloc(70_000, "b").toString(); + let raw: string[] = []; + const server = http.createServer({ maxHeaderSize: 128 * 1024 }, (req, res) => { + req.resume(); + req.on("end", () => { + raw = [...req.rawTrailers]; + res.end(); + }); + }); + await withServer(server, port => + roundtrip( + port, + "POST / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n" + + `0\r\nX-Big: ${big}\r\nX-After: 1\r\n\r\n`, + ), + ); + // The long value by name, so that a failure does not print 70,000 characters. + const named = raw.map(each => (each === big ? "big" : each.length > 100 ? `${each.length} other characters` : each)); + assert.deepStrictEqual(named, ["X-Big", "big", "X-After", "1"]); +}); + +// The parser keeps a trailer section that is not complete from one read to the next, in the buffer where it also +// keeps a request head that is not complete. Each connection below cuts the same two requests into reads at +// other places. +validationTest("a request has the same trailers wherever its bytes are cut into reads", async () => { + const post = "POST /a HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: chunked\r\n\r\n"; + const body = "3\r\nabc\r\n"; + // The last chunk and its trailer section. A "|" is a place where one connection cuts them into two reads. + const marked = "|0|\r\n|T|: a|\x01b\r|\n|U: 2\r\n|\r|\n|"; + const section = marked.replaceAll("|", ""); + const stream = post + body + section + "GET /b HTTP/1.1\r\nHost: b\r\nConnection: close\r\n\r\n"; + const sectionStart = post.length + body.length; + const sectionEnd = sectionStart + section.length; + + // One cut in the first head, the cuts of the section, one cut in the second head. + const plans: number[][] = [[20]]; + let at = sectionStart; + for (const part of marked.split("|").slice(0, -1)) plans.push([(at += part.length)]); + plans.push([sectionEnd + 16]); + // A head from two reads, then its body from one more read or two. + plans.push([20, sectionStart], [20, sectionStart + 9, sectionEnd + 16]); + + const seen: unknown[] = []; + const server = http.createServer(relaxed, (req, res) => { + if (req.url === "/barrier") { + res.end(); + return; + } + let received = ""; + req.setEncoding("latin1"); + req.on("data", chunk => (received += chunk)); + // The first read of the headers is here, after the parser has used the block of a head from two reads again. + req.on("end", () => { + seen.push({ url: req.url, host: req.headers.host, rawHeaders: req.rawHeaders, received, raw: req.rawTrailers }); + res.end(); + }); + }); + + const results: Record = {}; + await withServer(server, async port => { + for (const plan of plans) { + const socket = connect(port, "127.0.0.1"); + socket.resume(); + const closed = once(socket, "close"); + let from = 0; + for (const cut of plan) { + socket.write(stream.slice(from, cut), "latin1"); + from = cut; + // A part of a message emits nothing on the server, so a whole request on a second connection is the + // barrier: when the server has answered and closed that connection, it has read the write above. The + // next write then reaches the parser in a read of its own. + await roundtrip(port, "GET /barrier HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n"); + } + socket.write(stream.slice(from), "latin1"); + await closed; + results[plan.join(",")] = seen.splice(0); + } + }); + + const unsplit = [ + { + url: "/a", + host: "a", + rawHeaders: ["Host", "a", "Transfer-Encoding", "chunked"], + received: "abc", + raw: ["T", "a\x01b", "U", "2"], + }, + { url: "/b", host: "b", rawHeaders: ["Host", "b", "Connection", "close"], received: "", raw: [] }, + ]; + assert.deepStrictEqual(results, Object.fromEntries(plans.map(plan => [plan.join(","), unsplit]))); +}); + +// The peer's FIN cuts off the body of an accepted Upgrade request. The parser gave no verdict on the trailer +// section then, or it rejected the section, so the request has no trailer field. +describe("an Upgrade request body that the peer's FIN cuts off has no trailer fields", () => { + const head = + "POST / HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: custom\r\nTransfer-Encoding: chunked\r\n\r\n" + + "3\r\nabc\r\n0\r\n"; + + // What req.rawTrailers holds when the FIN reaches the socket of the 'upgrade' listener. + async function rawTrailersAtFin(section: string, maxHeadersCount?: number) { + const { promise, resolve, reject } = Promise.withResolvers(); + const opened: Duplex[] = []; + const server = http.createServer(); + if (maxHeadersCount) server.maxHeadersCount = maxHeadersCount; + server.on("upgrade", (req: http.IncomingMessage, socket: Duplex) => { + opened.push(socket.on("error", () => {})); + req.resume(); + socket.on("end", () => resolve([...req.rawTrailers])); + }); + // A listener that leaves the socket open, so that the FIN reaches it. + server.on("clientError", () => {}); + await withServer(server, async port => { + const socket = connect({ port, host: "127.0.0.1", allowHalfOpen: true }); + opened.push(socket); + socket.on("error", reject); + socket.end(head + section); + try { + await promise; + } finally { + for (const each of opened) each.destroy(); + } + }); + return promise; + } + + for (const [name, section] of [ + // The strict parser rejects a Content-Length or a Transfer-Encoding field in a trailer section. + ["a section that the parser rejected", "Content-Length: 5\r\n\r\n"], + ["a rejected section with a valid field in front of Content-Length", "X-Ok: 1\r\nContent-Length: 5\r\n\r\n"], + [ + "a rejected section with a valid field in front of Transfer-Encoding", + "X-Ok: 1\r\nTransfer-Encoding: chunked\r\n\r\n", + ], + ["a section that did not end", Buffer.alloc(199 * 6, "a: 1\r\n").toString()], + ]) { + test(name, async () => { + assert.deepStrictEqual(await rawTrailersAtFin(section), []); + }); + } + + // Node v26.3.0 gives the request the first 4 fields of this section. Node rejects the section from v26.5.1. + bunOnlyTest("a rejected section with more fields than server.maxHeadersCount", async () => { + assert.deepStrictEqual(await rawTrailersAtFin("A: 1\r\nB: 2\r\nC: 3\r\nD: 4\r\nE: 5\r\n\r\n", 4), []); + }); +}); + +// Only in Bun: when Node.js runs this file it must not spawn itself again. +if (harness) { + const node = harness.nodeExe(); + + describe("Node.js compatibility", () => { + // The timeout is for the first start of Node.js after a build: it reads its binary from the disk again, + // and that took up to 14 s here. The tests take 0.3 s. + (node ? test : test.skip)("all tests pass in Node.js", { timeout: 60_000 }, async () => { + // A direct run, not `node --test`: the runner mode forks a second node + // process per file. node:test still exits non-zero on any failure. + await using proc = Bun.spawn({ + cmd: [node!, "--v8-pool-size=1", fileURLToPath(import.meta.url)], + env: { ...harness.bunEnv, UV_THREADPOOL_SIZE: "2" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + assert.deepStrictEqual({ exitCode, output: exitCode === 0 ? "" : stdout + stderr }, { exitCode: 0, output: "" }); + }); + }); +} From c5ae096e264885a2ed1b9c68df4b6c6189cf9230 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:08:34 +0000 Subject: [PATCH 2/5] node:http: free the trailer section at the verdict The verdict moves a trailer section with fields out of the parser's buffer and frees it on return. The take at the fin no longer swaps the block of the previous take into the connection. A connection then holds no block for a trailer section that is over. The test that runs the file under Node.js uses the default timeout, like the other files with that test. --- packages/bun-uws/src/HttpParser.h | 15 ++++++++------- src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp | 4 ++-- .../node/http/node-http-request-trailers.test.ts | 4 +--- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/bun-uws/src/HttpParser.h b/packages/bun-uws/src/HttpParser.h index 1855b423fd3b..0890ec1cf812 100644 --- a/packages/bun-uws/src/HttpParser.h +++ b/packages/bun-uws/src/HttpParser.h @@ -693,26 +693,27 @@ struct HttpResponseData; * The fields of an accepted section go to *records, a field record each (fieldRecordLengths()), and only * after every field passed every rule: a rejected section leaves no record. req.rawTrailers is built from * the records, so no later step parses the section or decides again what it holds. The section itself - * never leaves the parser: it is emptied here, whatever the verdict. + * never leaves the parser: it ends here, whatever the verdict. * * Known bound: parseTrailerFields stops at MAX_TRAILER_FIELDS, so a section with * more valid fields than that followed by a malformed line is accepted where node * still errors; reaching it requires a deliberately padded (but size-capped) * section, and rejecting it would need a second scanning mode. */ HttpParserError acceptNodeTrailerSection(std::string *records, bool useInsecureHTTPParser, bool useLenientTransferEncoding, uint32_t maxHeadersCount) { - struct ClearOnReturn { - std::string §ion; - ~ClearOnReturn() { section.clear(); } - } clearOnReturn { fallback }; if (fallback.size() <= 2) { + /* No fields. clear() keeps the block, as the parser does for a head that took several reads. */ + fallback.clear(); return HTTP_PARSER_ERROR_NONE; } + /* This frame owns a section with fields: a connection holds no block for a section that is over. */ + std::string section = std::move(fallback); + fallback.clear(); /* A record holds the length of a field in 32 bits. */ - if (fallback.size() > UINT32_MAX) { + if (section.size() > UINT32_MAX) { return HTTP_PARSER_ERROR_TRAILER_FIELDS_TOO_LARGE; } std::pair fields[MAX_TRAILER_FIELDS]; - unsigned count = parseTrailerFields(fallback, fields, useInsecureHTTPParser); + unsigned count = parseTrailerFields(section, fields, useInsecureHTTPParser); if (count == 0) { return HTTP_PARSER_ERROR_INVALID_HEADER_TOKEN; } diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp index 8ae3bea3eba8..518a4d82a006 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp @@ -256,8 +256,8 @@ extern "C" size_t Bun__NodeHTTP__takeRequestTrailerBytes(bool is_ssl, us_socket_ return 0; } static thread_local std::string taken; - taken = std::move(*trailers); - trailers->clear(); + // Not `taken = std::move(*trailers)`: libstdc++ hands the old block of `taken` to the string it moves from, and the connection would keep that block. + taken = std::exchange(*trailers, std::string()); *out = taken.data(); return taken.size(); } diff --git a/test/js/node/http/node-http-request-trailers.test.ts b/test/js/node/http/node-http-request-trailers.test.ts index 09bba2d39cfa..6758f4f2df1e 100644 --- a/test/js/node/http/node-http-request-trailers.test.ts +++ b/test/js/node/http/node-http-request-trailers.test.ts @@ -421,9 +421,7 @@ if (harness) { const node = harness.nodeExe(); describe("Node.js compatibility", () => { - // The timeout is for the first start of Node.js after a build: it reads its binary from the disk again, - // and that took up to 14 s here. The tests take 0.3 s. - (node ? test : test.skip)("all tests pass in Node.js", { timeout: 60_000 }, async () => { + (node ? test : test.skip)("all tests pass in Node.js", async () => { // A direct run, not `node --test`: the runner mode forks a second node // process per file. node:test still exits non-zero on any failure. await using proc = Bun.spawn({ From 0b5792ce02fd6872de6464bdf25449af63524707 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 20 Oct 2026 04:46:08 +0000 Subject: [PATCH 3/5] node:http: reject a trailer section with more than 199 fields The verdict accepted a trailer section with more fields than it can hold. It kept the first 199 and did not read the lines after them. It now fails the request with HPE_HEADER_OVERFLOW, as the parser does for too many header fields. A line that is not a field after the 199th field fails the request with HPE_INVALID_HEADER_TOKEN, as in Node.js. The helper of the Upgrade tests rejects when a socket closes before the FIN reaches the upgraded socket. Each comment that this change edits is one line. --- packages/bun-uws/src/ChunkedEncoding.h | 9 ++--- packages/bun-uws/src/HttpContext.h | 4 +-- packages/bun-uws/src/HttpParser.h | 36 +++++++------------ packages/bun-uws/src/HttpResponseData.h | 10 +++--- src/js/internal/http.ts | 6 ++-- src/jsc/bindings/NodeHTTP.cpp | 6 ++-- .../bindings/node/JSNodeHTTPServerSocket.cpp | 3 +- src/runtime/server/NodeHTTPResponse.rs | 28 ++++++--------- .../http/node-http-request-trailers.test.ts | 30 +++++++++++++++- 9 files changed, 69 insertions(+), 63 deletions(-) diff --git a/packages/bun-uws/src/ChunkedEncoding.h b/packages/bun-uws/src/ChunkedEncoding.h index 9f4afa14289a..147a16a1b8aa 100644 --- a/packages/bun-uws/src/ChunkedEncoding.h +++ b/packages/bun-uws/src/ChunkedEncoding.h @@ -191,9 +191,8 @@ namespace uWS { * line is incomplete, i.e. before STATE_HAS_SIZE is set. _DONE means the * section (and thus the message) completed and the fin chunk was emitted; the * next call resets the state without touching the remaining bytes. The - * sub-state must not be derived from the captured section's contents: the - * caller empties the capture when it takes its verdict on the section, before - * it delivers the fin (HttpParser::acceptNodeTrailerSection). */ + * sub-state must not be derived from the captured section's contents: the fin + * is delivered after the caller's verdict has emptied the capture. */ constexpr uint64_t STATE_IS_TRAILERS = STATE_HAS_SIZE | STATE_IS_CHUNKED | STATE_WAITING_FOR_LF; constexpr uint64_t STATE_IS_TRAILERS_DONE = STATE_HAS_SIZE | STATE_WAITING_FOR_LF; @@ -229,9 +228,7 @@ namespace uWS { * 0-size chunk, capturing its raw bytes so the server can populate * req.trailers. The terminating empty chunk (fin) is only emitted once * the whole section (including its final CRLF) has been consumed, so - * trailers are always available by the time the message completes. - * trailerSection is the caller's buffer (HttpParser::fallback): empty - * when the 0-size chunk is read, and emptied by the caller at the fin. */ + * trailers are always available by the time the message completes. */ if (trailerSection && state == STATE_IS_TRAILERS) [[unlikely]] { while (data.length()) { char c = data[0]; diff --git a/packages/bun-uws/src/HttpContext.h b/packages/bun-uws/src/HttpContext.h index b54a69f2c029..ebf868ce22c6 100644 --- a/packages/bun-uws/src/HttpContext.h +++ b/packages/bun-uws/src/HttpContext.h @@ -425,8 +425,8 @@ struct HttpContext { /* The return value is entirely up to us to interpret. The HttpParser cares only for whether the returned value is DIFFERENT from passed user */ - /* node:http compat: the accepted trailer fields live in the IsNodeHttp=true - * ext block; the Bun.serve instantiation passes nullptr (and its parser + /* node:http compat: the accepted trailers live in the IsNodeHttp=true ext + * block; the Bun.serve instantiation passes nullptr (and its parser * instantiation contains no use of it). */ std::string *nodeHttpRequestTrailers = nullptr; if constexpr (IsNodeHttp) { diff --git a/packages/bun-uws/src/HttpParser.h b/packages/bun-uws/src/HttpParser.h index 0890ec1cf812..c090c6d7b331 100644 --- a/packages/bun-uws/src/HttpParser.h +++ b/packages/bun-uws/src/HttpParser.h @@ -664,10 +664,7 @@ struct HttpResponseData; return count; } - /* node:http gets the header fields of a request, and the trailer fields that acceptNodeTrailerSection() - * accepted, as a run of field records (NodeHTTP.cpp reads it). A field record is - * [u32 nameLen][u32 valueLen][name][value]. These are its two lengths, little-endian. u32: maxHeaderSize - * has no upper bound, and a u16 would truncate a value over 64 KiB and desync the run. */ + /* The two lengths of a field record, [u32 nameLen][u32 valueLen][name][value], little-endian. NodeHTTP.cpp reads the records. */ static std::array fieldRecordLengths(std::string_view name, std::string_view value) { const uint32_t nameLen = (uint32_t) name.length(); const uint32_t valueLen = (uint32_t) value.length(); @@ -678,27 +675,18 @@ struct HttpResponseData; } private: - /* node:http compat: the verdict on the trailer section of a chunked request, taken once: when the - * section is complete, before the fin completes the message. Node's llhttp fails the message on a - * malformed trailer field line (clientError HPE_INVALID_HEADER_TOKEN). llhttp does so at the offending - * byte, this parser when the final CRLF of the section arrives. A CTL byte in a value is only - * accepted under insecureHTTPParser, exactly like a header value. A Content-Length or + /* node:http compat: validate a captured, complete trailer section before the + * message is completed. Node's llhttp fails the message on a malformed trailer + * field line (clientError HPE_INVALID_HEADER_TOKEN) instead of completing it + * with req.trailers silently dropped; a CTL byte in a value is only accepted + * under insecureHTTPParser, exactly like a header value. A Content-Length or * Transfer-Encoding field in the trailer section is rejected exactly like * llhttp does (it runs trailers through the same header state machine, so * the already-set F_CHUNKED collides), unless insecureHTTPParser is set * (llhttp's LENIENT_CHUNKED_LENGTH / LENIENT_TRANSFER_ENCODING, which "relaxed" does not set). An empty * section (bare CRLF, no trailers) is valid. Node counts trailer fields from * zero against server.maxHeadersCount (maxHeadersCount here, 0 = not set). - * - * The fields of an accepted section go to *records, a field record each (fieldRecordLengths()), and only - * after every field passed every rule: a rejected section leaves no record. req.rawTrailers is built from - * the records, so no later step parses the section or decides again what it holds. The section itself - * never leaves the parser: it ends here, whatever the verdict. - * - * Known bound: parseTrailerFields stops at MAX_TRAILER_FIELDS, so a section with - * more valid fields than that followed by a malformed line is accepted where node - * still errors; reaching it requires a deliberately padded (but size-capped) - * section, and rejecting it would need a second scanning mode. */ + * The section ends here: an accepted one leaves its fields in *records (fieldRecordLengths()), a rejected one leaves nothing. */ HttpParserError acceptNodeTrailerSection(std::string *records, bool useInsecureHTTPParser, bool useLenientTransferEncoding, uint32_t maxHeadersCount) { if (fallback.size() <= 2) { /* No fields. clear() keeps the block, as the parser does for a head that took several reads. */ @@ -712,12 +700,13 @@ struct HttpResponseData; if (section.size() > UINT32_MAX) { return HTTP_PARSER_ERROR_TRAILER_FIELDS_TOO_LARGE; } - std::pair fields[MAX_TRAILER_FIELDS]; - unsigned count = parseTrailerFields(section, fields, useInsecureHTTPParser); + /* One slot more than a section may have fields: a section that fills it has too many. */ + std::pair fields[MAX_TRAILER_FIELDS + 1]; + unsigned count = parseTrailerFields(section, fields, useInsecureHTTPParser, MAX_TRAILER_FIELDS + 1); if (count == 0) { return HTTP_PARSER_ERROR_INVALID_HEADER_TOKEN; } - if (maxHeadersCount && count > maxHeadersCount) { + if (count > MAX_TRAILER_FIELDS || (maxHeadersCount && count > maxHeadersCount)) { return HTTP_PARSER_ERROR_TRAILER_FIELDS_TOO_LARGE; } size_t recordsSize = 0; @@ -741,8 +730,7 @@ struct HttpResponseData; return HTTP_PARSER_ERROR_NONE; } - /* A field section that is not complete yet: the head of the next request while no body is in flight, or - * (node:http) the trailer section of the chunked body in flight, until acceptNodeTrailerSection(). */ + /* A partial head while no body is in flight, or (node:http) the trailer section of the chunked body in flight. */ std::string fallback; public: /* node:http under LENIENT_TRANSFER_ENCODING: the current request's diff --git a/packages/bun-uws/src/HttpResponseData.h b/packages/bun-uws/src/HttpResponseData.h index 62ff84120f49..f5e1f630efef 100644 --- a/packages/bun-uws/src/HttpResponseData.h +++ b/packages/bun-uws/src/HttpResponseData.h @@ -292,12 +292,10 @@ struct HttpResponseData : HttpResponseData { * chunked framing for the response body. HTTP_NODE_HAS_RESPONSE_TRAILERS in * the shared flags word mirrors !empty(). */ std::string nodeHttpResponseTrailers; - /* The trailer fields that the parser accepted after the final 0-size chunk - * of the current request's chunked body, as field records - * (HttpParser::fieldRecordLengths): never raw wire bytes. Cleared when a - * new request is dispatched; moved onto the request at its body fin - * (req.trailers/rawTrailers). The parser gets it as a nullable pointer - * (see HttpParser::consumePostPadded). */ + /* The accepted trailer fields of the current request's chunked body, as field records (HttpParser::fieldRecordLengths). + * Cleared when a new request is dispatched; consumed by the JS layer when + * the request reaches EOF (req.trailers/rawTrailers). The parser gets it + * as a nullable pointer (see HttpParser::consumePostPadded). */ std::string nodeHttpRequestTrailers; bool headersCompleted = false; /* Timeout sweep already reported this message; reset when it completes. */ diff --git a/src/js/internal/http.ts b/src/js/internal/http.ts index e0dbaee083ec..90b70f9344e2 100644 --- a/src/js/internal/http.ts +++ b/src/js/internal/http.ts @@ -136,9 +136,9 @@ function emitEOFIncomingMessageOuter(self) { self.complete = true; // node:http server: trailer fields received after a chunked request body // populate req.trailers/rawTrailers before 'end' is emitted, like Node's - // parserOnMessageComplete. Native moved the fields that the parser accepted - // onto THIS request's handle at its body fin, so pipelined requests can - // neither inherit nor overwrite another request's trailers. + // parserOnMessageComplete. Native moved the accepted fields onto THIS request's + // handle at its body fin, so pipelined requests can neither inherit nor + // overwrite another request's trailers. // Trailers can only follow a chunked request body: a no-body request has // none, so skip the native call for the common GET/HEAD case. if (self[kHandle] !== undefined && !self[noBodySymbol]) { diff --git a/src/jsc/bindings/NodeHTTP.cpp b/src/jsc/bindings/NodeHTTP.cpp index 5716e974cef1..04e3c6f5f91f 100644 --- a/src/jsc/bindings/NodeHTTP.cpp +++ b/src/jsc/bindings/NodeHTTP.cpp @@ -111,6 +111,9 @@ static void assignHeadersFromUWebSocketsForCall(uWS::HttpRequest* request, JSVal const std::string_view name = pair.first; const std::string_view value = pair.second; + // u32 length prefixes: header sizes are usually tiny, but maxHeaderSize + // is user-configurable with no upper bound, so a u16 would silently + // truncate a >64 KiB value and desync the buffer. const std::array lens = uWS::HttpParser::fieldRecordLengths(name, value); flatHeaders.append(std::span { lens }); flatHeaders.append(std::span { reinterpret_cast(name.data()), name.length() }); @@ -166,8 +169,7 @@ static String headerValueString(NodeHTTPRequestHeaderValues& remembered, HTTPHea return *slot; } -// The next field record (uWS::HttpParser::fieldRecordLengths) of a run: the header fields that -// assignHeadersFromUWebSocketsForCall captured, or the trailer fields that the parser accepted. +// The next field record (uWS::HttpParser::fieldRecordLengths) of the captured header fields or the accepted trailer fields. static bool nextCapturedHeader(const uint8_t* data, size_t length, size_t& offset, std::span& name, std::span& value) { if (offset + 8 > length) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp index 518a4d82a006..00b34e9798e1 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp @@ -240,8 +240,7 @@ static std::string* requestTrailersFor(us_socket_t* socket) return &httpResponseData->nodeHttpRequestTrailers; } -/* Move the trailer fields that the parser accepted for the connection's current request - * (field records, see uWS::HttpParser::fieldRecordLengths) out, returning their (ptr, length) +/* Move the connection's accepted trailer fields (field records) out, returning their (ptr, length) * through a thread-local buffer that stays valid until the next call on this * thread. Called by NodeHTTPResponse at the request's body fin, still inside the * parser, so a pipelined request cannot overwrite or inherit another's trailers. */ diff --git a/src/runtime/server/NodeHTTPResponse.rs b/src/runtime/server/NodeHTTPResponse.rs index 5320d2a3c4eb..727eba8bef78 100644 --- a/src/runtime/server/NodeHTTPResponse.rs +++ b/src/runtime/server/NodeHTTPResponse.rs @@ -92,12 +92,10 @@ pub(crate) struct NodeHTTPResponse { pub(crate) promise: JsCell, // Strong.Optional pub(crate) server: AnyServer, - /// node:http: the trailer fields the parser accepted after THIS request's - /// chunked body, as [u32 nameLen][u32 valueLen][name][value]... like - /// raw_request_headers. Moved off the connection's single per-parse buffer - /// the moment the body finishes (still inside the parser), because a - /// pipelined request's parse would otherwise overwrite them before this - /// request's JS reads them. + /// node:http: the accepted trailer section, in the form of raw_request_headers, that followed THIS request's chunked + /// body. Moved off the connection's single per-parse buffer the moment the + /// body finishes (still inside the parser), because a pipelined request's + /// parse would otherwise overwrite it before this request's JS reads it. pub(crate) request_trailers: JsCell>, /// The JS wrapper whose `ondata` slot was armed for THIS request body. `get_this_value()` /// resolves through the socket's current response, which under pipelining is a different @@ -193,18 +191,16 @@ unsafe extern "C" { safe fn Bun__NodeHTTP__notifyWhenReadParsed(ssl: core::ffi::c_int, socket: *mut c_void) -> bool; - // Moves the trailer fields the parser accepted for the connection's current node:http request - // out ([u32 nameLen][u32 valueLen][name][value]...). `*out` points into + // Moves the connection's accepted node:http request-trailer fields out. `*out` points into // a C++ thread-local valid until the next call on this thread; caller copies immediately. - // Returns 0 when there are none or the socket is closed. + // Returns 0 when nothing captured or socket closed. safe fn Bun__NodeHTTP__takeRequestTrailerBytes( is_ssl: bool, socket: *mut c_void, out: *mut *const u8, ) -> usize; // Builds req.rawHeaders' flat [name, value, ...] JSArray from the header - // bytes captured at dispatch ([u32 nameLen][u32 valueLen][name][value]...), - // and req.rawTrailers' from the accepted trailer fields, which have that form. + // bytes captured at dispatch ([u32 nameLen][u32 valueLen][name][value]...). // `headers` is req.headers if that was built first, for its value strings. safe fn Bun__NodeHTTP__buildRawHeadersArray( global_object: &JSGlobalObject, @@ -466,9 +462,9 @@ impl NodeHTTPResponse { } /// Called at this request's body fin, still inside the parser: move the - /// connection's accepted trailer fields onto this request before the next - /// pipelined message's parse can overwrite them. A no-op unless the parser - /// accepted trailer fields for this exact message. + /// connection's accepted trailer section onto this request before the next + /// pipelined message's parse can overwrite it. A no-op unless a chunked + /// body's trailer section was accepted with fields for this exact message. fn capture_request_trailers(&self) { let flags = self.flags.get(); if flags.contains(Flags::SOCKET_CLOSED) || flags.contains(Flags::UPGRADED) { @@ -2466,9 +2462,7 @@ impl NodeHTTPResponse { Ok(headers) } - /// `handle.takeRequestTrailers()` — the trailer fields the parser accepted - /// for this request as a flat [name, value, ...] array, or undefined when - /// it has none (or they were already taken). Consumes them. + /// `handle.takeRequestTrailers()`: this request's accepted trailer fields as a flat [name, value, ...] array, or undefined. Consumes them. pub(crate) fn take_request_trailers( &self, global_object: &JSGlobalObject, diff --git a/test/js/node/http/node-http-request-trailers.test.ts b/test/js/node/http/node-http-request-trailers.test.ts index 6758f4f2df1e..3a5e12b30d3f 100644 --- a/test/js/node/http/node-http-request-trailers.test.ts +++ b/test/js/node/http/node-http-request-trailers.test.ts @@ -290,6 +290,31 @@ test("a trailer value over 64 KiB keeps the field after it", async () => { assert.deepStrictEqual(named, ["X-Big", "big", "X-After", "1"]); }); +// Bun keeps at most 199 trailer fields for a request. Node keeps server.maxHeadersCount of them, 2000 by default. +describe("a trailer section with many fields", () => { + const request = (count: number, lastLine = "") => + "POST / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n0\r\n" + + Array.from({ length: count }, (_, i) => `F${i}: ${i}\r\n`).join("") + + lastLine + + "\r\n"; + + test("199 fields: the request has them all", async () => { + const outcome = await outcomeOf(http.createServer(), request(199)); + const summary = "raw" in outcome ? { entries: outcome.raw.length, last: outcome.raw.slice(-2) } : outcome; + assert.deepStrictEqual(summary, { entries: 398, last: ["F198", "198"] }); + }); + + test("199 fields and a line that is not a field: the request fails", async () => { + const outcome = await outcomeOf(http.createServer(), request(199, "not a field\r\n")); + assert.deepStrictEqual(outcome, { clientError: "HPE_INVALID_HEADER_TOKEN" }); + }); + + // Node v26.3.0 gives the request the 200 fields. + bunOnlyTest("200 fields: the request fails", async () => { + assert.deepStrictEqual(await outcomeOf(http.createServer(), request(200)), { clientError: "HPE_HEADER_OVERFLOW" }); + }); +}); + // The parser keeps a trailer section that is not complete from one read to the next, in the buffer where it also // keeps a request head that is not complete. Each connection below cuts the same two requests into reads at // other places. @@ -375,9 +400,11 @@ describe("an Upgrade request body that the peer's FIN cuts off has no trailer fi const server = http.createServer(); if (maxHeadersCount) server.maxHeadersCount = maxHeadersCount; server.on("upgrade", (req: http.IncomingMessage, socket: Duplex) => { - opened.push(socket.on("error", () => {})); + opened.push(socket); req.resume(); socket.on("end", () => resolve([...req.rawTrailers])); + socket.on("error", reject); + socket.on("close", () => reject(new Error("the upgraded socket closed before the FIN reached it"))); }); // A listener that leaves the socket open, so that the FIN reaches it. server.on("clientError", () => {}); @@ -385,6 +412,7 @@ describe("an Upgrade request body that the peer's FIN cuts off has no trailer fi const socket = connect({ port, host: "127.0.0.1", allowHalfOpen: true }); opened.push(socket); socket.on("error", reject); + socket.on("close", () => reject(new Error("the connection closed before the FIN reached the upgraded socket"))); socket.end(head + section); try { await promise; From 86dcb77559301b818cb7d3cc52cb75d6e5ca4a8c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 20 Oct 2026 06:40:33 +0000 Subject: [PATCH 4/5] ci: retrigger From 111942a58eeee2829b98659b915adb944ffd096a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:42:18 +0000 Subject: [PATCH 5/5] node:http: correct Node's default trailer field limit in a test comment Node's default limit is 1000 fields, not 2000. MAX_HEADER_PAIRS = 2000 counts names and values, and server.maxHeadersCount is null until it is set. --- test/js/node/http/node-http-request-trailers.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/js/node/http/node-http-request-trailers.test.ts b/test/js/node/http/node-http-request-trailers.test.ts index 3a5e12b30d3f..7144c61b3a20 100644 --- a/test/js/node/http/node-http-request-trailers.test.ts +++ b/test/js/node/http/node-http-request-trailers.test.ts @@ -290,7 +290,8 @@ test("a trailer value over 64 KiB keeps the field after it", async () => { assert.deepStrictEqual(named, ["X-Big", "big", "X-After", "1"]); }); -// Bun keeps at most 199 trailer fields for a request. Node keeps server.maxHeadersCount of them, 2000 by default. +// Bun keeps at most 199 trailer fields for a request. Node's limit is server.maxHeadersCount, 1000 when it is not set. +// MAX_HEADER_PAIRS = 2000 counts names and values: https://github.com/nodejs/node/blob/v26.3.0/lib/_http_common.js#L53 describe("a trailer section with many fields", () => { const request = (count: number, lastLine = "") => "POST / HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n0\r\n" +