Skip to content

Commit 6882f6d

Browse files
committed
fix(body-limit): serve _request over the size-limited body
1 parent 2f5ff20 commit 6882f6d

4 files changed

Lines changed: 176 additions & 1 deletion

File tree

‎docs/1.guide/11.body-limit.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ Returns a request whose body is size-limited. A request without a body is return
3131

3232
Because it wraps rather than rebuilds, the returned value is the **same type** as the input and keeps its identity: a [`ServerRequest`](/guide/handler#extended-request-serverrequest) stays a `ServerRequest`, with its augmentation (`runtime`, `waitUntil`, `ip`, `context`, …) intact.
3333

34+
On the Node adapter the [`req._request`](/guide/node#noderequest) escape hatch is served over the same size-limited stream, so unwrapping the request — `req._request`, or `new Request(req)` after `patchGlobalRequest()` — cannot reach the raw body and bypass the limit.
35+
3436
```js
3537
import { limitRequestBody } from "srvx/body-limit";
3638

‎src/body-limit.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
* original request. Used for runtimes that have no native body-size option (e.g.
1515
* Deno) and exported so downstream layers can apply per-handler limits.
1616
*
17+
* srvx's `ServerRequest._request` escape hatch is served over the same limited
18+
* stream, so unwrapping the request (`req._request`, or `new Request(req)` under
19+
* `patchGlobalRequest()`, which rewrites the input to `_request`) cannot reach
20+
* the raw body and bypass the limit.
21+
*
1722
* Proxy-wrapping (rather than rebuilding via `new Request(request, …)`) is
1823
* deliberate: it preserves the exact object handed in — including srvx's
1924
* `ServerRequest` augmentation (`runtime`, `waitUntil`, `ip`, `context`, …) —
@@ -78,6 +83,9 @@ export function limitRequestBody<T extends Request>(
7883
// so an unconsumed limited request stays allocation-light, and cached so
7984
// repeated `body` / read-method access observes one consistent body.
8085
let limited: Response | undefined;
86+
// Native Request served for `_request` (see the trap below), cached alongside
87+
// `limited` so the size-limited body is only ever handed out once.
88+
let nativeRequest: globalThis.Request | undefined;
8189
const limitedBody = (): Response =>
8290
(limited ??= new Response(
8391
overLimit
@@ -99,6 +107,24 @@ export function limitRequestBody<T extends Request>(
99107
if (typeof prop === "string" && bodyReadMethods.has(prop)) {
100108
return () => (limitedBody() as any)[prop]();
101109
}
110+
if (prop === "_request" && "_request" in target) {
111+
// srvx's `ServerRequest._request` materializes a native Request over the
112+
// *raw* body stream, so passing it through would hand out the unlimited
113+
// body to every consumer that unwraps a `ServerRequest` — `req._request`
114+
// itself, `new Request(req)` under `patchGlobalRequest()` (it rewrites
115+
// the input to `_request`), and anything forwarding `_request.body`.
116+
// Serve an equivalent request built over the size-limited body instead,
117+
// cached so repeated access observes one request. Mirrors the adapter's
118+
// own init; header mutations after this point are not shared with it.
119+
return (nativeRequest ??= new Request(target.url, {
120+
method: target.method,
121+
headers: target.headers,
122+
signal: target.signal,
123+
body: limitedBody().body,
124+
// @ts-expect-error Undici specific
125+
duplex: "half",
126+
}));
127+
}
102128
if (prop === "clone") {
103129
// Re-apply the limit to the clone so it can't be used to read an
104130
// unbounded body (the pre-proxy rebuild tee'd the limited stream, so

‎test/body-limit.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,82 @@ describe("limitRequestBody", () => {
325325
expect(limited.bodyUsed).toBe(true);
326326
});
327327

328+
// srvx's `ServerRequest` exposes the underlying native Request as `_request`
329+
// (and `patchGlobalRequest()` rewrites `new Request(req)` to it), so the
330+
// proxy has to serve that escape hatch over the size-limited body too.
331+
describe("_request escape hatch", () => {
332+
function serverRequestLike(body: BodyInit, headers?: HeadersInit): Request {
333+
const request = new Request("http://localhost/", {
334+
method: "POST",
335+
headers,
336+
body,
337+
// @ts-expect-error duplex required for a streaming body
338+
duplex: "half",
339+
});
340+
// Stand in for the adapter's getter: a native Request over the raw body.
341+
Object.defineProperty(request, "_request", {
342+
configurable: true,
343+
get: () => raw,
344+
});
345+
const raw = new Request("http://localhost/", {
346+
method: "POST",
347+
body: request.body,
348+
// @ts-expect-error duplex required for a streaming body
349+
duplex: "half",
350+
});
351+
return request;
352+
}
353+
354+
test("serves `_request` over the size-limited body", async () => {
355+
const limited = limitRequestBody(serverRequestLike("0123456789"), 8);
356+
expect("_request" in limited).toBe(true);
357+
await expect((limited as any)._request.text()).rejects.toMatchObject({
358+
code: "ERR_BODY_TOO_LARGE",
359+
});
360+
});
361+
362+
test("passes a `_request` body within the limit through", async () => {
363+
const limited = limitRequestBody(serverRequestLike("hi"), 8);
364+
expect(await (limited as any)._request.text()).toBe("hi");
365+
});
366+
367+
test("rejects `_request` on the over-limit content-length fast path", async () => {
368+
const limited = limitRequestBody(
369+
serverRequestLike("0123456789", { "content-length": "100" }),
370+
8,
371+
);
372+
await expect((limited as any)._request.text()).rejects.toMatchObject({
373+
code: "ERR_BODY_TOO_LARGE",
374+
});
375+
});
376+
377+
test("caches `_request` so repeated access observes one request", () => {
378+
const limited = limitRequestBody(serverRequestLike("hi"), 8);
379+
expect((limited as any)._request).toBe((limited as any)._request);
380+
});
381+
382+
test("marks the body used once `_request` is consumed", async () => {
383+
const limited = limitRequestBody(serverRequestLike("hi"), 8);
384+
expect(limited.bodyUsed).toBe(false);
385+
await (limited as any)._request.text();
386+
expect(limited.bodyUsed).toBe(true);
387+
});
388+
389+
test("does not fabricate `_request` for a plain Request", () => {
390+
const limited = limitRequestBody(
391+
new Request("http://localhost/", {
392+
method: "POST",
393+
body: "hi",
394+
// @ts-expect-error duplex required for a streaming body
395+
duplex: "half",
396+
}),
397+
8,
398+
);
399+
expect("_request" in limited).toBe(false);
400+
expect((limited as any)._request).toBeUndefined();
401+
});
402+
});
403+
328404
describe("createError injection", () => {
329405
class CustomError extends Error {
330406
status = 413;

‎test/node-max-body-size.test.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, test } from "vitest";
22
import { fetch, FormData } from "undici";
3-
import { serve } from "../src/adapters/node.ts";
3+
import { patchGlobalRequest, serve } from "../src/adapters/node.ts";
4+
import { limitRequestBody } from "../src/body-limit.ts";
45

56
describe("node maxRequestBodySize", () => {
67
test("rejects a buffered body larger than the limit with a 413-style error", async () => {
@@ -117,3 +118,73 @@ describe("node maxRequestBodySize", () => {
117118
await server.close(true);
118119
});
119120
});
121+
122+
// A per-handler `limitRequestBody()` must hold even when the handler unwraps the
123+
// `ServerRequest` — `req._request` and `new Request(req)` (which `patchGlobalRequest()`
124+
// rewrites to `_request`) both used to hand back the raw, unlimited body stream.
125+
describe("node limitRequestBody _request escape hatch", () => {
126+
// Chunked: no `content-length`, so the eager over-limit fast path cannot fire
127+
// and the streaming limit is the only thing standing between the client and
128+
// an unbounded read.
129+
const chunkedBody = (): ReadableStream<Uint8Array> =>
130+
new ReadableStream<Uint8Array>({
131+
start(controller) {
132+
controller.enqueue(new TextEncoder().encode("0123456789"));
133+
controller.close();
134+
},
135+
});
136+
137+
const readers = {
138+
"_request.text()": (req: Request) => (req as any)._request.text(),
139+
"new Request(req).text()": (req: Request) => {
140+
patchGlobalRequest();
141+
return new globalThis.Request(req as any).text();
142+
},
143+
"_request.body stream": async (req: Request) => {
144+
let out = "";
145+
for await (const chunk of (req as any)._request.body) out += new TextDecoder().decode(chunk);
146+
return out;
147+
},
148+
} as const;
149+
150+
for (const [name, read] of Object.entries(readers)) {
151+
test(`rejects an oversized chunked body read via ${name}`, async () => {
152+
const server = serve({
153+
port: 0,
154+
fetch: async (req) => {
155+
const limited = limitRequestBody(req, 4);
156+
try {
157+
return new Response(await read(limited));
158+
} catch (error: any) {
159+
return new Response(error.code ?? error.message, { status: error.statusCode ?? 500 });
160+
}
161+
},
162+
});
163+
await server.ready();
164+
const res = await fetch(server.url!, {
165+
method: "POST",
166+
body: chunkedBody(),
167+
duplex: "half",
168+
} as any);
169+
expect(res.status).toBe(413);
170+
expect(await res.text()).toBe("ERR_BODY_TOO_LARGE");
171+
await server.close(true);
172+
});
173+
174+
test(`passes a chunked body within the limit through ${name}`, async () => {
175+
const server = serve({
176+
port: 0,
177+
fetch: async (req) => new Response(await read(limitRequestBody(req, 1024))),
178+
});
179+
await server.ready();
180+
const res = await fetch(server.url!, {
181+
method: "POST",
182+
body: chunkedBody(),
183+
duplex: "half",
184+
} as any);
185+
expect(res.status).toBe(200);
186+
expect(await res.text()).toBe("0123456789");
187+
await server.close(true);
188+
});
189+
}
190+
});

0 commit comments

Comments
 (0)