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:
12 files changed
+559
-26
No files matched your search
@@ -0,0 +1,87 @@
|
||||
// #105 on the real Bun runtime: the request-body limit is enforced while the body is read, both on
|
||||
// `app.fetch` directly and through `serveBun`. The counting stream is what proves the read stopped —
|
||||
// a 413 looks the same whether the body was buffered first or not.
|
||||
//
|
||||
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||
import 'reflect-metadata';
|
||||
import { test, expect } from 'bun:test';
|
||||
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
|
||||
import { serveBun } from '../../src/bun.ts';
|
||||
import { countingStream } from '../helpers/counting-stream.ts';
|
||||
|
||||
const LIMIT = 1_000_000; // the server default
|
||||
const SMALL = 1000;
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Post('/echo') echo(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
|
||||
// writing a large body when the 413 lands can see a reset instead — the transport racing the
|
||||
// answer, not a different answer.
|
||||
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
|
||||
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(source.pulled).toBe(0);
|
||||
expect(source.cancelled).toBe(true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(source.pulled).toBeLessThanOrEqual(5);
|
||||
expect(source.cancelled).toBe(true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
|
||||
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
|
||||
|
||||
expect(at.status).toBe(200);
|
||||
expect(await at.json()).toEqual({ length: LIMIT });
|
||||
expect(over.status).toBe(413);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
test('T11 serveBun: the same statuses over a real socket', async () => {
|
||||
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
|
||||
const base = `http://127.0.0.1:${server.port}`;
|
||||
// A fresh connection per request. Bun's *client* reuses a kept-alive socket after a response that
|
||||
// arrived before the server read the request body, and its next request on that socket comes back
|
||||
// 400 or 431. Node's fetch against the same Bun server does not (Bun 1.3.14), so it is the client
|
||||
// that misbehaves, not `serveBun`.
|
||||
const send = (body: BodyInit, headers?: Record<string, string>) =>
|
||||
fetch(post(`${base}/small`, body, headers), { keepalive: false } as RequestInit);
|
||||
|
||||
try {
|
||||
expect((await send(new Uint8Array(2 * SMALL))).status).toBe(413);
|
||||
expect((await send(countingStream(10, 300).stream)).status).toBe(413);
|
||||
expect((await send('x'.repeat(SMALL), { 'content-type': 'text/plain' })).status).toBe(200);
|
||||
expect((await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' })).status).toBe(413);
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// #105 on the real Deno runtime: the request-body limit is enforced while the body is read, both on
|
||||
// `app.fetch` directly and through `serveDeno`. The counting stream is what proves the read stopped —
|
||||
// a 413 looks the same whether the body was buffered first or not.
|
||||
//
|
||||
// Run with: npm run test:deno
|
||||
import 'reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.ts';
|
||||
import { countingStream } from '../helpers/counting-stream.ts';
|
||||
|
||||
const LIMIT = 1_000_000; // the server default
|
||||
const SMALL = 1000;
|
||||
|
||||
@Route('/')
|
||||
class Ctl {
|
||||
@Post('/echo') echo(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
|
||||
// writing a large body when the 413 lands can see a reset instead — the transport racing the
|
||||
// answer, not a different answer.
|
||||
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||
class M {}
|
||||
|
||||
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
|
||||
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
Deno.test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
|
||||
|
||||
assertEquals(res.status, 413);
|
||||
assertEquals(source.pulled, 0);
|
||||
assertEquals(source.cancelled, true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
const source = countingStream(10, 300_000);
|
||||
|
||||
const res = await app.fetch(post('http://x/echo', source.stream));
|
||||
|
||||
assertEquals(res.status, 413);
|
||||
if (source.pulled > 5) throw new Error(`pulled ${source.pulled} chunks — the read did not stop at the limit`);
|
||||
assertEquals(source.cancelled, true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
|
||||
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
|
||||
|
||||
assertEquals(at.status, 200);
|
||||
assertEquals(await at.json(), { length: LIMIT });
|
||||
assertEquals(over.status, 413);
|
||||
await over.body?.cancel();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
Deno.test('T11 serveDeno: the same statuses over a real socket', async () => {
|
||||
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
|
||||
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
|
||||
|
||||
try {
|
||||
const send = (body: BodyInit, headers?: Record<string, string>) => fetch(post(`${base}/small`, body, headers));
|
||||
|
||||
const declared = await send(new Uint8Array(2 * SMALL));
|
||||
assertEquals(declared.status, 413);
|
||||
await declared.body?.cancel();
|
||||
|
||||
const streamed = await send(countingStream(10, 300).stream);
|
||||
assertEquals(streamed.status, 413);
|
||||
await streamed.body?.cancel();
|
||||
|
||||
const at = await send('x'.repeat(SMALL), { 'content-type': 'text/plain' });
|
||||
assertEquals(at.status, 200);
|
||||
await at.body?.cancel();
|
||||
|
||||
const over = await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' });
|
||||
assertEquals(over.status, 413);
|
||||
await over.body?.cancel();
|
||||
} finally {
|
||||
await server.close({ timeoutMs: 1000 });
|
||||
}
|
||||
});
|
||||
+28
-1
@@ -66,6 +66,33 @@ async function main() {
|
||||
assert.equal(httpRes.status, 200);
|
||||
assert.deepEqual(await httpRes.json(), { ok: true });
|
||||
|
||||
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
|
||||
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
|
||||
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
|
||||
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
|
||||
const res = await mf.dispatchFetch('http://localhost/rt/body', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
body,
|
||||
duplex: 'half',
|
||||
} as Parameters<typeof mf.dispatchFetch>[1]);
|
||||
await res.arrayBuffer();
|
||||
return res.status;
|
||||
};
|
||||
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
|
||||
let sent = 0;
|
||||
return new ReadableStream({
|
||||
pull(controller) {
|
||||
if (sent++ === count) controller.close();
|
||||
else controller.enqueue(new Uint8Array(size).fill(0x61));
|
||||
},
|
||||
});
|
||||
};
|
||||
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
|
||||
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
|
||||
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
|
||||
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
|
||||
|
||||
// WebSocket
|
||||
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
|
||||
headers: { Upgrade: 'websocket' },
|
||||
@@ -109,7 +136,7 @@ async function main() {
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
|
||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
||||
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi + ws limits — PASS');
|
||||
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
|
||||
} finally {
|
||||
await mf.dispose();
|
||||
}
|
||||
|
||||
+9
-1
@@ -1,7 +1,7 @@
|
||||
// Worker entry for the real workerd (Miniflare) integration test.
|
||||
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
|
||||
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
|
||||
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index';
|
||||
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
|
||||
import { edgeHandler } from '../../src/edge';
|
||||
|
||||
@Route('/rt')
|
||||
@@ -11,6 +11,14 @@ class Rt {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
|
||||
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
|
||||
// instead, which is the transport racing the answer rather than a different answer.
|
||||
@Post('/body', { maxBodyBytes: 1000 })
|
||||
body(@body() b: unknown) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
|
||||
import { countingStream } from './helpers/counting-stream';
|
||||
|
||||
@Provider({ provides: 'store' })
|
||||
class Store {
|
||||
@@ -145,3 +146,104 @@ describe('app.fetch on a mesh app', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// #105: the limit is enforced while the body is read, not after it has been buffered. A status code
|
||||
// cannot tell the two apart — both answer 413 — so the counting stream is what these assert on.
|
||||
@Route('/limits')
|
||||
class LimitsCtl {
|
||||
@Post('/echo') echo(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
@Post('/small', { maxBodyBytes: 10 }) small(@body() b: any) {
|
||||
return { got: b };
|
||||
}
|
||||
@Post('/large', { maxBodyBytes: 2_000_000 }) large(@body() b: any) {
|
||||
return { length: String(b).length };
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [LimitsCtl] })
|
||||
class LimitsModule {}
|
||||
|
||||
const post = (path: string, body: RequestInit['body'], headers: Record<string, string> = {}) =>
|
||||
new Request(`http://x${path}`, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
|
||||
|
||||
describe('app.fetch bounded body reads (#105)', () => {
|
||||
const limitsApp = createApp({ modules: [LimitsModule] }); // server limit: the 1 MB default
|
||||
|
||||
it('T1: a declared content-length over the limit is refused without reading the body', async () => {
|
||||
const body = countingStream(10, 300_000);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream, { 'content-length': '2000000' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
expect(body.pulled).toBe(0);
|
||||
expect(body.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it('T3: a streamed body stops at the chunk that crosses the limit, and the reader is cancelled', async () => {
|
||||
const body = countingStream(10, 300_000); // 3 MB, no content-length
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
// 4 read, the 4th crossing 1 MB, plus at most one the stream queued ahead of the reader.
|
||||
expect(body.pulled).toBeLessThanOrEqual(5);
|
||||
expect(body.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it('T4: a body of exactly the limit is accepted', async () => {
|
||||
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 8) });
|
||||
expect(Buffer.byteLength(json)).toBe(1_000_000);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(((await res.json()) as any).got.s).toHaveLength(1_000_000 - 8);
|
||||
});
|
||||
|
||||
it('T5: one byte over the limit is refused', async () => {
|
||||
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 7) });
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T5: one byte over the limit is refused when streamed without a content-length', async () => {
|
||||
const body = countingStream(1, 1_000_001);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T8: a route limit below the server limit wins', async () => {
|
||||
const res = await limitsApp.fetch(post('/limits/small', 'x'.repeat(11), { 'content-type': 'text/plain' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T9: a route limit above the server limit wins', async () => {
|
||||
const res = await limitsApp.fetch(
|
||||
post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }),
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ length: 1_500_000 });
|
||||
});
|
||||
|
||||
it('a malformed content-length is ignored, and the stream count enforces the limit', async () => {
|
||||
const body = countingStream(1, 20);
|
||||
|
||||
const res = await limitsApp.fetch(post('/limits/small', body.stream, { 'content-length': 'nope' }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('T10: a bodiless request is answered without reading anything', async () => {
|
||||
const res = await limitsApp.fetch(new Request('http://x/limits/echo', { method: 'POST' }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// A request body that records how much of it was consumed. Web APIs only, so the Node, Deno and Bun
|
||||
// suites share it: the regression it guards (#105) is "read the whole body before checking the
|
||||
// limit", which no status code can show on its own — a 413 looks the same either way.
|
||||
|
||||
export interface CountingStream {
|
||||
stream: ReadableStream<Uint8Array>;
|
||||
/** Chunks the consumer has pulled so far. */
|
||||
readonly pulled: number;
|
||||
/** Whether the consumer cancelled the stream. */
|
||||
readonly cancelled: boolean;
|
||||
}
|
||||
|
||||
/** `count` chunks of `size` bytes each, handed out one per pull. */
|
||||
export function countingStream(count: number, size: number): CountingStream {
|
||||
let pulled = 0;
|
||||
let cancelled = false;
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
// Pull-based, and only on demand: with a high-water mark of 0 the stream does not pre-fill its
|
||||
// queue, so `pulled` counts what the consumer asked for. The default of 1 pulls a chunk at
|
||||
// construction, before anyone reads, and would make "nothing was read" unprovable.
|
||||
pull(controller) {
|
||||
if (pulled === count) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
pulled++;
|
||||
controller.enqueue(new Uint8Array(size).fill(0x61));
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
|
||||
return {
|
||||
stream,
|
||||
get pulled() {
|
||||
return pulled;
|
||||
},
|
||||
get cancelled() {
|
||||
return cancelled;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -123,6 +123,32 @@ describe('request hardening', () => {
|
||||
server.close();
|
||||
});
|
||||
|
||||
// #105: a declared length over the limit is answered before any of the body is sent. Without the
|
||||
// header check, the reader waits for a first chunk that this client never sends — and times out.
|
||||
it('T2: rejects a declared content-length over the limit before reading any body', async () => {
|
||||
let ran = false;
|
||||
const server = createHttpServer(
|
||||
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
|
||||
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
|
||||
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
|
||||
);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
const socket = net.connect((server.address() as any).port, '127.0.0.1');
|
||||
await once(socket, 'connect');
|
||||
socket.write('POST /echo HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\n\r\n'); // headers only
|
||||
|
||||
let raw = '';
|
||||
socket.setEncoding('utf8');
|
||||
socket.on('data', (chunk: string) => (raw += chunk));
|
||||
await once(socket, 'end');
|
||||
|
||||
expect(raw).toMatch(/^HTTP\/1\.1 413 /);
|
||||
expect(raw.toLowerCase()).toContain('connection: close');
|
||||
expect(ran).toBe(false);
|
||||
socket.destroy();
|
||||
server.close();
|
||||
}, 2000);
|
||||
|
||||
it('sets the configured server timeouts and connection limit', async () => {
|
||||
const server = createHttpServer([], [], undefined, undefined,
|
||||
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user