FPRD-001a: core safety and adapter correctness (#104 #105 #106 #107 #108 #116) #117

Merged
chrnx merged 8 commits from feature/fprd-001a into develop 2026-10-10 16:49:36 +00:00
12 changed files with 559 additions and 26 deletions
Showing only changes of commit ae60cd68a2 - Show all commits

No files matched your search

+15
View File
@@ -70,6 +70,21 @@ npm treats versions as semver and semver forbids leading zeros.
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
the socket finished opening now reaches the client instead of leaving it hanging.
### Fixed
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
is refused before any of the body is read, on Node too, where the request used to wait for its
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
the count rather than up front. The status is the same; only how early it comes differs.
## [26.9.0-beta.2] - 2026-09-22
### Breaking
+14 -6
View File
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
/**
* Reads the raw request body, enforcing `limit`.
*
* The adapter owns this and nothing else about the body, because enforcement is the one place the
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
* without bound first.
* The adapter owns this and nothing else about the body, because getting the bytes is the one place
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
* possible — measuring afterwards would force the reader to buffer without bound first.
*
* The failure branch is opaque on purpose: Node answers an over-limit request with
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
@@ -41,6 +40,15 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
*/
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/**
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
* and the running total still enforces the limit on whatever actually arrives.
*/
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
+5
View File
@@ -1,8 +1,13 @@
import type http from 'http';
import { HttpError } from '../signals';
import { declaresOverLimit } from './body';
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
// A declared length over the limit is refused without waiting for the first chunk, which could
// otherwise sit until the request timeout. The fetch adapter makes the same check.
if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large');
const chunks: Buffer[] = [];
let total = 0;
+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) };
}
/**
+87
View File
@@ -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 });
}
});
+95
View File
@@ -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
View File
@@ -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
View File
@@ -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* () {
+102
View File
@@ -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({});
});
});
+44
View File
@@ -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;
},
};
}
+26
View File
@@ -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 } });
+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);
});
});