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

+75 -1
View File
@@ -1,6 +1,20 @@
import { describe, it, expect, afterEach } from 'vitest';
import { describe, it, expect, afterEach, vi } from 'vitest';
import { createApp, Route, Post, Module, body } from '../src';
// Counts calls into the multipart parser while still running the real one, so a test can prove
// busboy was never reached rather than inferring it from the status code.
const parsed = vi.hoisted(() => ({ calls: 0 }));
vi.mock('../src/multipart', async (importOriginal) => {
const real = await importOriginal<typeof import('../src/multipart')>();
return {
...real,
parseMultipart: (...args: Parameters<typeof real.parseMultipart>) => {
parsed.calls++;
return real.parseMultipart(...args);
},
};
});
let app: any;
afterEach(async () => { await app?.close(); });
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
expect(await post('/b')).toEqual({ x: ['1', '2'] });
});
});
// #105: multipart is parsed from the bytes the bounded reader returns, so the byte limit has to stop
// a request before busboy ever sees it, and `maxParts` has to keep working on what gets through.
describe('multipart limits on app.fetch (#105)', () => {
const form = (fields: number, size = 1) => {
const fd = new FormData();
for (let i = 0; i < fields; i++) fd.set(`f${i}`, 'x'.repeat(size));
return fd;
};
it('T6: a multipart body over maxBodyBytes is 413 and never reaches the parser', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1, 5000) }));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T6: the same holds when the multipart body arrives without a content-length', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const encoded = new Request('http://x', { method: 'POST', body: form(1, 5000) });
const r = await app.fetch(new Request('http://x/u', {
method: 'POST',
headers: { 'content-type': encoded.headers.get('content-type')! },
body: encoded.body,
duplex: 'half',
} as RequestInit));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T7: under the byte limit but over maxParts is 400 Invalid multipart body', async () => {
@Route('/') class C { @Post('/u', { maxParts: 2 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }));
expect(r.status).toBe(400);
expect(await r.text()).toContain('Invalid multipart body');
});
it('T7: the server-level maxParts applies when the route sets none', async () => {
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod], limits: { maxParts: 2 } });
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1) }))).status).toBe(200);
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }))).status).toBe(400);
});
});