fix(http): enforce maxBodyBytes while reading fetch request bodies

The fetch adapter read every body through request.arrayBuffer() and
compared the length afterwards, so Deno, Bun and the edge buffered an
oversized upload in full before refusing it. readFetchBytes now reads
request.body chunk by chunk, stops at the chunk that crosses the limit
and cancels the reader, so no further chunk is pulled.

A content-length that already declares more than the limit is refused
before anything is read, on both adapters. On Node the request used to
wait for its first chunk, which a client that sends only headers never
delivers. A malformed or absent header is ignored and the running count
enforces the limit. The response is the same 413 through onError, and
the route-over-server precedence for maxBodyBytes and maxParts is
untouched; the new tests pin it.

The over-read is proven with a counting stream rather than a status
code, which is the same 413 either way. The stream uses a high-water
mark of 0: the default of 1 pulls a chunk at construction, before any
reader exists, which would make "nothing was read" unprovable.

Socket-level tests on Deno, Bun and workerd use a 1000-byte route limit
so every refused body fits in the socket buffer. With a multi-megabyte
body the client is still writing when the 413 lands and sometimes sees
ECONNRESET instead, which is the transport racing the answer. The Bun
socket test also disables keep-alive: Bun's own fetch client reuses a
socket after a response that arrived before the body was read, and its
next request on it comes back 400 or 431. Node's fetch against the same
Bun server does not.

Closes #105

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-09 13:59:47 -05:00
1 parent 0540bef07b
commit ae60cd68a2
12 files changed
+559 -26

No files matched your search

+59 -17
View File
@@ -11,7 +11,7 @@ import {
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types';
@@ -97,9 +97,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
/**
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
*
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
* or not at all, so the limit can only be checked once the bytes are already in memory. That
* difference is exactly why the limit is passed in rather than applied by the shared core.
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* the whole body or not at all and so could only check the limit once every byte was in memory.
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
*/
function readFetchBytes(
source: unknown,
@@ -110,21 +110,63 @@ function readFetchBytes(
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => {
if (arrayBuffer.byteLength > limit) {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
// effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
request.body.cancel().catch(() => {});
return tooLarge(request, opts);
}
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
return readBounded(request.body.getReader(), limit).then((bytes) =>
bytes === null ? tooLarge(request, opts) : { bytes },
);
}
/**
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
* propagates exactly as a rejected `arrayBuffer()` used to.
*
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
* The answer is the same 413 either way; only how early it comes differs.
*/
async function readBounded(
reader: ReadableStreamDefaultReader<Uint8Array>,
limit: number,
): Promise<Buffer | undefined | null> {
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
reader.cancel().catch(() => {});
return null;
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
chunks.push(value);
}
return total === 0 ? undefined : Buffer.concat(chunks, total);
}
/** The over-limit answer, shared by the declared-length check and the stream count. */
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
/**