Skip to content

Commit bd827d5

Browse files
committed
fix(service-storage, plugin-hono-server): the upload link's several-file form is bounded by its own limit, not the request-body limit
A route refused req.body for size that then reads rawBody() takes the read over under its own bound. The upload-link door reads its several-file form that way when the transport refuses it, judges the bytes against its own form limit, and parses the form itself. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibyNMYdfN5kzwSS28Rs
1 parent 4641ccc commit bd827d5

5 files changed

Lines changed: 307 additions & 3 deletions

File tree

‎.changeset/request-body-limit.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
'@objectstack/plugin-hono-server': patch
33
'@objectstack/hono': patch
4+
'@objectstack/service-storage': patch
45
---
56

67
fix(plugin-hono-server, hono): a request body over the server's limit is answered 413 PAYLOAD_TOO_LARGE and is not read past the limit
@@ -13,3 +14,5 @@ Both HTTP doors, the self-hosted server (`@objectstack/plugin-hono-server`) and
1314
To change the limit, set `maxRequestBodyBytes` (in bytes) on `HonoServerPlugin`, call `HonoHttpServer.setMaxRequestBodyBytes()` on an embedded adapter, or pass `maxRequestBodyBytes` to `createHonoApp`. Without an option, the `OS_HTTP_MAX_BODY_BYTES` environment variable sets it. A value that is not a positive whole number of bytes fails the boot instead of serving with no limit or the wrong one.
1415

1516
Upload doors keep their own limit. The storage byte doors (the presigned raw PUT, the chunk PUT and the upload-link PUT) read the raw bytes through `IHttpRequest.rawBody()`, which still serves the whole body, so a file is bounded by the storage `max_upload_mb` setting exactly as before, even when that is larger than the request-body limit.
17+
18+
The upload link's several-file form is bounded by that door's own form limit (each file within `max_upload_mb`, times the files the link takes, plus the form's framing), not by the request-body limit. A route that is refused `req.body` for size and then reads `rawBody()` takes the read over under its own bound, and its own answer stands.

‎packages/plugins/plugin-hono-server/src/adapter.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
requestBodyTooLargeAnswer,
4747
requestBodyTooLargeEnvelope,
4848
resolveMaxRequestBodyBytes,
49-
type RequestBodyTooLarge,
49+
RequestBodyTooLarge,
5050
} from './body-limit';
5151
import { compressResponse } from './response-compression';
5252
// The ADR-0112 wire vocabulary, read as DATA rather than restated: `ErrorCode`
@@ -904,8 +904,15 @@ export class HonoHttpServer implements IHttpServer {
904904
* request-body limit, because the door bounds it by its own
905905
* (`./body-limit.ts`). Hono's body cache once a pre-read of a body
906906
* within the limit went through it.
907+
*
908+
* A route that read `body`, was refused it for size, and then
909+
* reads `rawBody()` is a door taking over the read under its own
910+
* bound (an upload door's form larger than the request-body
911+
* limit), so that refusal no longer stands as the answer. Every
912+
* other refusal still does.
907913
*/
908914
rawBody: async () => {
915+
if (refusedBodyRead instanceof RequestBodyTooLarge) refusedBodyRead = undefined;
909916
const original = requestBodyGuardOf(c)?.readOriginal();
910917
if (original) {
911918
const bytes = await original;

‎packages/plugins/plugin-hono-server/src/body-limit.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,17 @@ describe('over a real listener, a body over the limit is refused unread and a by
7373
const bytes = await req.rawBody!();
7474
res.json({ success: true, data: { size: bytes.byteLength } });
7575
});
76+
// A door with its own bound beyond the request-body limit: it is refused
77+
// `req.body` for size, and takes the read over through `rawBody()`.
78+
server.put('/api/v1/forms/:id', async (req, res) => {
79+
try {
80+
res.json({ success: true, data: { parsed: Object.keys(req.body ?? {}).length } });
81+
} catch (err) {
82+
if ((err as { code?: unknown }).code !== 'PAYLOAD_TOO_LARGE') throw err;
83+
const bytes = await req.rawBody!();
84+
res.json({ success: true, data: { size: bytes.byteLength } });
85+
}
86+
});
7687
await server.listen(0);
7788
return server.getPort();
7889
}
@@ -126,6 +137,32 @@ describe('over a real listener, a body over the limit is refused unread and a by
126137
expect(((await res.json()) as any).data.size).toBe(LIMIT * 8);
127138
});
128139

140+
it.each([['declared', true], ['not declared', false]])(
141+
'a door refused req.body for size takes the read over through rawBody() and its own answer stands, length %s',
142+
async (_label, declare) => {
143+
const port = await start();
144+
const form = new FormData();
145+
form.append('file0', new Blob([new Uint8Array(LIMIT * 8).fill(0x62)]), 'f.bin');
146+
const encoded = new Response(form);
147+
const bytes = new Uint8Array(await encoded.arrayBuffer());
148+
const res = await fetch(`http://127.0.0.1:${port}/api/v1/forms/f_1`, {
149+
method: 'PUT',
150+
headers: { 'content-type': encoded.headers.get('content-type')! },
151+
body: declare
152+
? bytes
153+
: new ReadableStream({
154+
start(controller) {
155+
controller.enqueue(bytes);
156+
controller.close();
157+
},
158+
}),
159+
duplex: 'half',
160+
} as RequestInit);
161+
expect(res.status, await res.clone().text()).toBe(200);
162+
expect(((await res.json()) as any).data.size).toBe(bytes.byteLength);
163+
},
164+
);
165+
129166
it('CONTROL: a JSON body within the limit is read as before', async () => {
130167
const port = await start();
131168
const res = await fetch(`http://127.0.0.1:${port}/api/v1/data/task/query`, {

‎packages/qa/dogfood/test/request-body-limit-upload-doors.dogfood.test.ts‎

Lines changed: 200 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
// byte doors reads `rawBody()` and bounds the file by its own `max_upload_mb`.
77
// Over a REAL boot under the default limit, a body over 10 MiB still lands
88
// through the presigned raw PUT, the chunk PUT and the upload-link PUT, while
9-
// a JSON body of the same size to a data route is answered 413.
9+
// a JSON body of the same size to a data route is answered 413. The upload
10+
// link's several-file form is bounded by that door's own form limit (each file
11+
// within `max_upload_mb`, times the files the link takes, plus the form's
12+
// framing), not by the transport's.
1013
//
1114
// Not eligible for the shared showcase project: it boots its own storage root.
1215

@@ -20,6 +23,10 @@ import { MCPServerPlugin } from '@objectstack/mcp';
2023
import { attachmentsFixtureStack, attachmentsFixtureSecurity } from './fixtures/attachments-fixture.js';
2124

2225
const MIB = 1024 * 1024;
26+
/** `UPLOAD_LINK_MAX_FILES` in `@objectstack/service-storage`: what a multi-file field's link takes. */
27+
const LINK_MAX_FILES = 10;
28+
/** The form framing a several-file submit may add beyond its files (`storage-routes.ts`). */
29+
const FORM_OVERHEAD = 64 * 1024;
2330
/** Over the transport's 10 MiB default, and a whole chunk the chunked door accepts (its floor is 5 MiB). */
2431
const OVER_DEFAULT = 12 * MIB;
2532

@@ -133,3 +140,195 @@ describe('the request-body limit leaves each upload door its own bound, over a r
133140
expect(body.data.size).toBe(OVER_DEFAULT);
134141
});
135142
});
143+
144+
/** An object whose `scans` field takes several files, so its upload link takes the several-file form. */
145+
const SCAN_CLAIM = 'body_limit_scan_claim';
146+
const scanClaimApp = {
147+
name: 'com.dogfood.body-limit-scan-claim',
148+
type: 'standard' as const,
149+
version: '0.0.0',
150+
optionalDependencies: ['com.objectstack.engine.objectql'],
151+
async init(ctx: any) {
152+
ctx.getService('manifest').register({
153+
id: 'com.dogfood.body-limit-scan-claim',
154+
name: 'Scan claim',
155+
version: '0.0.0',
156+
type: 'plugin',
157+
scope: 'system',
158+
objects: [{
159+
name: SCAN_CLAIM,
160+
label: 'Scan Claim',
161+
fields: {
162+
name: { type: 'text', label: 'Name' },
163+
scans: { type: 'file', label: 'Scans', multiple: true },
164+
},
165+
}],
166+
});
167+
},
168+
async start() {},
169+
};
170+
171+
/** A request body that counts the bytes the server pulled from it. */
172+
function countedBody(bytes: Uint8Array, chunk = 256 * 1024) {
173+
const read = { bytes: 0 };
174+
let offset = 0;
175+
const stream = new ReadableStream<Uint8Array>({
176+
pull(controller) {
177+
if (offset >= bytes.byteLength) {
178+
controller.close();
179+
return;
180+
}
181+
const next = bytes.subarray(offset, offset + chunk);
182+
offset += next.byteLength;
183+
read.bytes += next.byteLength;
184+
controller.enqueue(next);
185+
},
186+
}, { highWaterMark: 0 });
187+
return { stream, read };
188+
}
189+
190+
describe('the upload link\'s several-file form is bounded by that door\'s own limit, not the request-body limit, over a real boot', () => {
191+
let stack: VerifyStack;
192+
let token: string;
193+
/** `max_upload_mb` saved for this boot: each file within 2 MiB. */
194+
const MAX_UPLOAD = 2 * MIB;
195+
const FORM_LIMIT = MAX_UPLOAD * LINK_MAX_FILES + FORM_OVERHEAD;
196+
197+
const json = { 'Content-Type': 'application/json' };
198+
const auth = () => ({ Authorization: `Bearer ${token}` });
199+
200+
beforeAll(async () => {
201+
const rootDir = mkdtempSync(join(tmpdir(), 'body-limit-link-form-'));
202+
stack = await bootStack(attachmentsFixtureStack as never, {
203+
security: attachmentsFixtureSecurity(),
204+
// Bound to the `storage` settings namespace, so `max_upload_mb` is saved below.
205+
extraPlugins: [new StorageServicePlugin({ adapter: 'local', local: { rootDir } }), new MCPServerPlugin(), scanClaimApp],
206+
});
207+
token = await stack.signIn();
208+
const save = await stack.raw('/api/settings/storage', {
209+
method: 'PUT',
210+
headers: { ...json, ...auth() },
211+
body: JSON.stringify({ max_upload_mb: MAX_UPLOAD / MIB }),
212+
});
213+
expect(save.status, await save.clone().text()).toBe(200);
214+
// The plugin re-reads the namespace on `settings:changed`, after the PUT's answer.
215+
const presign = (size: number) => stack.api('/storage/upload/presigned', {
216+
method: 'POST',
217+
headers: { ...json, ...auth() },
218+
body: JSON.stringify({ filename: 'probe.bin', mimeType: 'application/octet-stream', size, scope: 'user' }),
219+
});
220+
let probe = await presign(MAX_UPLOAD + 1);
221+
for (let i = 0; i < 40 && probe.status !== 413; i++) {
222+
await new Promise((resolve) => setTimeout(resolve, 100));
223+
probe = await presign(MAX_UPLOAD + 1);
224+
}
225+
expect(probe.status, 'the saved max_upload_mb is in force').toBe(413);
226+
}, 120_000);
227+
228+
afterAll(async () => {
229+
await stack?.stop();
230+
});
231+
232+
/** A link for a new claim's `scans`, as the path the page is served at. */
233+
async function linkPath(): Promise<{ path: string; claimId: string }> {
234+
const created = await stack.apiAs(token, 'POST', `/data/${SCAN_CLAIM}`, { name: 'scan claim' });
235+
expect(created.status, await created.clone().text()).toBeLessThan(300);
236+
const createdBody: any = await created.json();
237+
const claimId = String(createdBody?.id ?? createdBody?.record?.id ?? createdBody?.data?.id ?? '');
238+
expect(claimId).not.toBe('');
239+
const mcp = await stack.api('/mcp', {
240+
method: 'POST',
241+
headers: { ...json, Accept: 'application/json, text/event-stream', ...auth() },
242+
body: JSON.stringify({
243+
jsonrpc: '2.0', id: 1, method: 'tools/call',
244+
params: { name: 'create_upload_link', arguments: { objectName: SCAN_CLAIM, recordId: claimId, field: 'scans' } },
245+
}),
246+
});
247+
expect(mcp.status).toBe(200);
248+
const rpc: any = await mcp.json();
249+
const minted = JSON.parse(rpc.result?.content?.[0]?.text ?? 'null');
250+
expect(rpc.result?.isError, JSON.stringify(minted)).not.toBe(true);
251+
return { path: String(minted.url).replace(/^https?:\/\/[^/]+/, ''), claimId };
252+
}
253+
254+
/** The page's several-file form, as its bytes and the content type that frames them. */
255+
async function formOf(sizes: number[]): Promise<{ bytes: Uint8Array<ArrayBuffer>; contentType: string }> {
256+
const form = new FormData();
257+
form.append('count', String(sizes.length));
258+
sizes.forEach((size, i) => {
259+
form.append(`file${i}`, new Blob([new Uint8Array(size).fill(0x41 + i)], { type: 'application/octet-stream' }), `scan-${i}.bin`);
260+
});
261+
const encoded = new Response(form);
262+
return { bytes: new Uint8Array(await encoded.arrayBuffer()), contentType: encoded.headers.get('content-type')! };
263+
}
264+
265+
const putForm = (path: string, contentType: string, body: BodyInit, extra: Record<string, string> = {}) =>
266+
stack.raw(path, {
267+
method: 'PUT',
268+
headers: { ...auth(), 'content-type': contentType, 'x-upload-link-form': 'several', ...extra },
269+
body,
270+
duplex: 'half',
271+
} as RequestInit);
272+
273+
/** Six files of 1.9 MiB: each within `max_upload_mb`, the form over the 10 MiB request-body limit. */
274+
const OVER_TRANSPORT = Array.from({ length: 6 }, () => Math.floor(1.9 * MIB));
275+
276+
it.each([['declared', true], ['not declared', false]])(
277+
'a form over the request-body limit and within the door\'s own limit lands whole, its length %s',
278+
async (_label, declare) => {
279+
const { path } = await linkPath();
280+
const { bytes, contentType } = await formOf(OVER_TRANSPORT);
281+
expect(bytes.byteLength).toBeGreaterThan(10 * MIB);
282+
expect(bytes.byteLength).toBeLessThan(FORM_LIMIT);
283+
const res = declare
284+
? await putForm(path, contentType, bytes, { 'content-length': String(bytes.byteLength) })
285+
: await putForm(path, contentType, countedBody(bytes).stream);
286+
const body: any = await res.json();
287+
expect(res.status, JSON.stringify(body)).toBe(200);
288+
expect(body.data.fileIds).toHaveLength(OVER_TRANSPORT.length);
289+
expect(body.data.files.map((file: any) => file.size)).toEqual(OVER_TRANSPORT);
290+
},
291+
);
292+
293+
it('a form that declares more than the door\'s own limit is answered 413 and not read', async () => {
294+
const { path } = await linkPath();
295+
const declared = FORM_LIMIT + 1;
296+
const { stream, read } = countedBody(new Uint8Array(declared));
297+
const res = await putForm(path, 'multipart/form-data; boundary=x', stream, { 'content-length': String(declared) });
298+
const body: any = await res.json();
299+
expect(res.status, JSON.stringify(body)).toBe(413);
300+
expect(body.error.code).toBe('PAYLOAD_TOO_LARGE');
301+
expect(body.error.message).toContain(`over the ${FORM_LIMIT} bytes this link's upload can carry`);
302+
expect(read.bytes).toBe(0);
303+
});
304+
305+
it('a form with no declared length past the door\'s own limit is answered 413, and the link still takes a form that fits', async () => {
306+
const { path, claimId } = await linkPath();
307+
const { bytes, contentType } = await formOf(Array.from({ length: 11 }, () => MAX_UPLOAD));
308+
expect(bytes.byteLength).toBeGreaterThan(FORM_LIMIT);
309+
const res = await putForm(path, contentType, countedBody(bytes).stream);
310+
const body: any = await res.json();
311+
expect(res.status, JSON.stringify(body)).toBe(413);
312+
expect(body.error.code).toBe('PAYLOAD_TOO_LARGE');
313+
// Nothing was stored, and the link was not spent.
314+
const fits = await formOf([MIB]);
315+
const again = await putForm(path, fits.contentType, fits.bytes);
316+
expect(again.status, await again.clone().text()).toBe(200);
317+
const row: any = await stack.apiAs(token, 'GET', `/data/${SCAN_CLAIM}/${claimId}`).then((r) => r.json());
318+
const scans = row?.scans ?? row?.record?.scans ?? row?.data?.scans;
319+
expect(Array.isArray(scans) ? scans : [scans]).toHaveLength(1);
320+
});
321+
322+
it('a body that is not the form is still the one file on the same link, read through rawBody()', async () => {
323+
const { path } = await linkPath();
324+
// A one-file body is any body that is not the form; one file is bounded by `max_upload_mb`.
325+
const res = await stack.raw(path, {
326+
method: 'PUT',
327+
headers: { ...auth(), 'content-type': 'application/octet-stream', 'x-file-name': 'one.bin' },
328+
body: new Uint8Array(MAX_UPLOAD).fill(0x5a),
329+
});
330+
const body: any = await res.json();
331+
expect(res.status, JSON.stringify(body)).toBe(200);
332+
expect(body.data.size).toBe(MAX_UPLOAD);
333+
});
334+
});

‎packages/services/service-storage/src/storage-routes.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1920,7 +1920,12 @@ export function registerStorageFamily(
19201920
return;
19211921
}
19221922
if (linkFiles !== undefined) {
1923-
const uploads = await uploadLinkFormFiles(req.body, linkFiles);
1923+
const form = await uploadLinkFormBody(req, formLimit);
1924+
if (form.refused) {
1925+
sendError(res, UPLOAD_TOO_LARGE_STATUS, UPLOAD_TOO_LARGE_CODE, form.refused, { userMessage: copy.tooLarge });
1926+
return;
1927+
}
1928+
const uploads = await uploadLinkFormFiles(form.body, linkFiles);
19241929
if (!Array.isArray(uploads)) {
19251930
sendError(res, uploads.status, uploads.code, uploads.message, { userMessage: copy.refused(uploads.message) });
19261931
return;
@@ -2502,6 +2507,59 @@ function isUploadLinkForm(contentType: string | string[] | undefined, marker: st
25022507
);
25032508
}
25042509

2510+
/**
2511+
* Whether a read of `req.body` was refused by the transport's request-body
2512+
* limit (`PAYLOAD_TOO_LARGE`), a limit that bounds what the HTTP door reads, not
2513+
* what this door accepts.
2514+
*/
2515+
function isTransportBodyTooLarge(err: unknown): boolean {
2516+
return !!err && typeof err === 'object' && (err as { code?: unknown }).code === 'PAYLOAD_TOO_LARGE';
2517+
}
2518+
2519+
/**
2520+
* The several-file form, bounded by this door's own form limit rather than the
2521+
* transport's request-body limit. The form the transport parsed when it fits
2522+
* within that limit; when the transport refused it for size, the form's bytes
2523+
* read through `rawBody()` (a declared length over this door's limit was
2524+
* already refused unread), judged against this door's limit, and parsed here.
2525+
* `refused` names why the bytes read are over this door's limit.
2526+
*/
2527+
async function uploadLinkFormBody(
2528+
req: IHttpRequest,
2529+
formLimit: number | undefined,
2530+
): Promise<{ body: unknown; refused?: undefined } | { body?: undefined; refused: string }> {
2531+
try {
2532+
return { body: req.body };
2533+
} catch (err) {
2534+
if (!isTransportBodyTooLarge(err) || !req.rawBody) throw err;
2535+
}
2536+
const bytes = await req.rawBody();
2537+
if (formLimit !== undefined && bytes.byteLength > formLimit) {
2538+
return {
2539+
refused:
2540+
`The upload body is ${bytes.byteLength} bytes, over the ${formLimit} bytes this link's upload can carry ` +
2541+
'(its files, each within the "Max upload size (MB)" storage setting).',
2542+
};
2543+
}
2544+
const contentType = req.headers?.['content-type'];
2545+
let parsed: FormData;
2546+
try {
2547+
parsed = await new Response(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), {
2548+
headers: { 'content-type': String(Array.isArray(contentType) ? contentType[0] : contentType) },
2549+
}).formData();
2550+
} catch {
2551+
// Not a readable form: the form checks below refuse it as one that names no files.
2552+
return { body: {} };
2553+
}
2554+
// A name sent twice is kept as a list, which the form checks refuse.
2555+
const body: Record<string, unknown> = {};
2556+
for (const [key, value] of parsed.entries()) {
2557+
const held = body[key];
2558+
body[key] = held === undefined ? value : Array.isArray(held) ? [...held, value] : [held, value];
2559+
}
2560+
return { body };
2561+
}
2562+
25052563
/** [#32747] A form value that is a file: what a form parser hands for a file part. */
25062564
interface FormFilePart {
25072565
name?: unknown;

0 commit comments

Comments
 (0)