Skip to content

Commit bb70828

Browse files
committed
fix(plugin-hono-server): rawBody() is repeatable, and a held body refused past the limit releases its source
A second rawBody() call answers the same bytes as the first. A body read up to the limit and refused, that no byte door went on to read whole, has its source cancelled at the end of the request. The changeset names @objectstack/spec, whose error-code ledger gains a row, and that row's comment names what createHonoApp imports. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibyNMYdfN5kzwSS28Rs
1 parent e85a506 commit bb70828

5 files changed

Lines changed: 111 additions & 10 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
'@objectstack/plugin-hono-server': patch
33
'@objectstack/hono': patch
44
'@objectstack/service-storage': patch
5+
'@objectstack/spec': patch
56
---
67

78
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

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,7 @@ export class HonoHttpServer implements IHttpServer {
861861
// media type answers and why the refusal waits for `req.body` to be read.
862862
let bodyReading: RequestBodyReading = await readRequestBody(c);
863863
let refusedBodyRead: RequestBodyRefusal | RequestBodyTooLarge | undefined;
864+
let rawBodyRead: Promise<Buffer> | undefined;
864865

865866
_endParse?.();
866867

@@ -911,15 +912,18 @@ export class HonoHttpServer implements IHttpServer {
911912
* limit), so that refusal no longer stands as the answer. Every
912913
* other refusal still does.
913914
*/
914-
rawBody: async () => {
915+
rawBody: () => {
915916
if (refusedBodyRead instanceof RequestBodyTooLarge) refusedBodyRead = undefined;
916-
const original = requestBodyGuardOf(c)?.readOriginal();
917-
if (original) {
918-
const bytes = await original;
919-
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
920-
}
921-
const ab = await c.req.arrayBuffer();
922-
return Buffer.from(ab);
917+
// Repeatable: a second call answers the same bytes as the first.
918+
rawBodyRead ??= (async () => {
919+
const original = requestBodyGuardOf(c)?.readOriginal();
920+
if (original) {
921+
const bytes = await original;
922+
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
923+
}
924+
return Buffer.from(await c.req.arrayBuffer());
925+
})();
926+
return rawBodyRead;
923927
},
924928
/**
925929
* The transport's own peer address (`IHttpRequest.remoteAddress`)

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,74 @@ describe('over a real listener, a body over the limit is refused unread and a by
172172
expect(await res.json()).toEqual({ success: true, data: { where: { status: 'open' } } });
173173
});
174174
});
175+
176+
describe('a body refused past the limit releases its source, and a byte door reads the same bytes twice', () => {
177+
const LIMIT = 1024;
178+
const CHUNK = 256;
179+
180+
/** An endless body that records what was pulled from it and whether it was cancelled. */
181+
function endlessBody() {
182+
const state = { pulled: 0, cancelled: false };
183+
const stream = new ReadableStream<Uint8Array>({
184+
pull(controller) {
185+
state.pulled += CHUNK;
186+
controller.enqueue(new TextEncoder().encode('x'.repeat(CHUNK)));
187+
},
188+
cancel() {
189+
state.cancelled = true;
190+
},
191+
}, { highWaterMark: 0 });
192+
return { stream, state };
193+
}
194+
195+
function serverWithRoutes() {
196+
const server = new HonoHttpServer(0);
197+
server.setMaxRequestBodyBytes(LIMIT);
198+
server.post('/api/v1/data/:object/query', (req, res) => { res.json({ success: true, data: req.body }); });
199+
server.put('/api/v1/bytes/:id', async (req, res) => {
200+
const first = await req.rawBody!();
201+
const second = await req.rawBody!();
202+
res.json({ success: true, data: { first: first.byteLength, second: second.byteLength, same: first.equals(second) } });
203+
});
204+
return server;
205+
}
206+
207+
it.each([['application/json'], ['application/x-www-form-urlencoded']])(
208+
'a %s body with no declared length is answered 413 and its source is cancelled after the refusal',
209+
async (contentType) => {
210+
const { stream, state } = endlessBody();
211+
const res = await serverWithRoutes().getRawApp().request('http://localhost/api/v1/data/task/query', {
212+
method: 'POST',
213+
headers: { 'content-type': contentType },
214+
body: stream,
215+
duplex: 'half',
216+
} as RequestInit);
217+
expect(res.status).toBe(413);
218+
expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE');
219+
expect(state.cancelled).toBe(true);
220+
expect(state.pulled).toBeLessThanOrEqual(LIMIT + 2 * CHUNK);
221+
},
222+
);
223+
224+
it.each([['declared', true], ['not declared', false]])(
225+
'rawBody() called twice answers the same bytes both times, length %s',
226+
async (_label, declare) => {
227+
const bytes = new Uint8Array(LIMIT * 4).fill(0x63);
228+
const res = await serverWithRoutes().getRawApp().request('http://localhost/api/v1/bytes/f_1', {
229+
method: 'PUT',
230+
headers: { 'content-type': 'application/json', ...(declare ? { 'content-length': String(bytes.byteLength) } : {}) },
231+
body: declare
232+
? bytes
233+
: new ReadableStream({
234+
start(controller) {
235+
controller.enqueue(bytes);
236+
controller.close();
237+
},
238+
}),
239+
duplex: 'half',
240+
} as RequestInit);
241+
expect(res.status, await res.clone().text()).toBe(200);
242+
expect(((await res.json()) as any).data).toEqual({ first: bytes.byteLength, second: bytes.byteLength, same: true });
243+
},
244+
);
245+
});

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,12 @@ export interface RequestBodyGuard {
185185
* original can no longer be read here (something read through the guard).
186186
*/
187187
readOriginal(): Promise<Uint8Array> | undefined;
188+
/**
189+
* At the end of the request: a held body that passed the limit and that no
190+
* byte door went on to read whole has its source cancelled, as a read
191+
* refused through the guard has, so the rest of it is never read.
192+
*/
193+
release(): Promise<void>;
188194
}
189195

190196
const guards = new WeakMap<Request, RequestBodyGuard>();
@@ -200,6 +206,8 @@ function guardRequest(original: Request, limit: number): { guard: RequestBodyGua
200206
let tripped = false;
201207
let pulled = false;
202208
let held: Promise<HeldRequestBody> | undefined;
209+
let heldReader: ReadableStreamDefaultReader<Uint8Array> | undefined;
210+
let heldOpen = false;
203211
let sourceReader: ReadableStreamDefaultReader<Uint8Array> | undefined;
204212

205213
const guard: RequestBodyGuard = {
@@ -212,6 +220,7 @@ function guardRequest(original: Request, limit: number): { guard: RequestBodyGua
212220
hold() {
213221
held ??= (async (): Promise<HeldRequestBody> => {
214222
const reader = original.body!.getReader();
223+
heldReader = reader;
215224
const chunks: Uint8Array[] = [];
216225
let total = 0;
217226
let done = false;
@@ -225,10 +234,13 @@ function guardRequest(original: Request, limit: number): { guard: RequestBodyGua
225234
total += next.value.byteLength;
226235
}
227236
const overLimit = !done && total > limit;
237+
heldOpen = !done;
228238
return {
229239
bytes: overLimit ? undefined : concat(chunks),
230240
overLimit,
231241
async readAll() {
242+
// A byte door claimed the rest: `release` leaves it to this read.
243+
heldOpen = false;
232244
if (!done) {
233245
for (;;) {
234246
const next = await reader.read();
@@ -248,6 +260,14 @@ function guardRequest(original: Request, limit: number): { guard: RequestBodyGua
248260
if (pulled || original.bodyUsed || original.body?.locked) return undefined;
249261
return original.arrayBuffer().then((buffer) => new Uint8Array(buffer));
250262
},
263+
async release() {
264+
if (!held) return;
265+
const reading = await held.catch(() => undefined);
266+
if (reading?.overLimit && heldOpen && heldReader) {
267+
heldOpen = false;
268+
await heldReader.cancel().catch(() => undefined);
269+
}
270+
},
251271
};
252272

253273
// No body, or one something upstream of this app already consumed (a host
@@ -306,7 +326,11 @@ export function installRequestBodyLimit(app: Hono<any, any, any>, limit: () => n
306326
c.req.raw = guarded;
307327
guards.set(guarded, guard);
308328
}
309-
await next();
329+
try {
330+
await next();
331+
} finally {
332+
await guard.release();
333+
}
310334
if (guard.tripped()) {
311335
const envelope = requestBodyTooLargeEnvelope(guard.limit);
312336
c.res = c.json(envelope.body, envelope.status);

‎packages/spec/src/api/error-code-ledger.zod.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1287,7 +1287,8 @@ export const ERROR_CODE_LEDGER = {
12871287
// over the limit (10 MiB by default, `maxRequestBodyBytes` /
12881288
// `OS_HTTP_MAX_BODY_BYTES`) is not read past it, on the self-hosted server
12891289
// and on `@objectstack/hono`'s `createHonoApp`, which imports the
1290-
// constant. Third EMITTER of the code `@objectstack/rest` registers; one
1290+
// refusal (`RequestBodyTooLarge`) and its answer
1291+
// (`requestBodyTooLargeAnswer`) from here. Third EMITTER of the code `@objectstack/rest` registers; one
12911292
// condition, the request carries more than the door accepts. Provenance,
12921293
// not identity (see above).
12931294
'PAYLOAD_TOO_LARGE',

0 commit comments

Comments
 (0)