Skip to content

Commit dd291b8

Browse files
fix(storage, plugin-hono-server): every byte-reading upload door holds a body with no declared length to its own bound (#33323)
Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - **改了什么**:每个按字节读取上传内容的入口(分片上传、本地直传、上传链接)现在对"未声明长度"的请求体也按自己的上限计数,超限即停读并拒绝;`IHttpRequest.rawBody` 新增可选参数 `{ maxBytes }`。 - **为什么改**:此前只有声明了长度的请求体会被这些入口的上限挡住,未声明长度的会先读完再判断;规则应当一致。 - **风险与回滚**:契约是加宽(参数可选,旧实现照样通过类型检查);`max_upload_mb` 未设置时行为不变。回滚即还原本 PR。 - **先看**:`packages/plugins/plugin-hono-server/src/body-limit.ts`(有界读取)、`packages/services/service-storage/src/storage-routes.ts`(各入口传入上限、上传链接先判链接再读)、`packages/spec/src/contracts/http-server.ts`(契约文字)。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-hono-server exec vitest run src/body-limit.test.ts -t "own bound"` ,预期 8 个用例全部通过。 - **需要你做的**:无,席位落地。 ## What changes **The rule:** every byte-reading upload door holds a body with no declared length to its own bound, exactly as it holds a declared one, and refuses past the bound before the body is buffered further. ### The contract change (rule level) — for the contract-tier review `IHttpRequest.rawBody` (`packages/spec/src/contracts/http-server.ts`) widens from an accessor that takes no argument to one that takes an optional `{ maxBytes?: number }`, still answering a promise of the body's bytes: - The reading door states its own bound as `maxBytes`. An implementation MUST then hold the body to it whether or not a length is declared: a declared `Content-Length` over it is refused unread; a body with no declared length is refused once it passes it, and read no further; exactly `maxBytes` is read whole. - A refusal rejects with an error carrying `status` 413 and `code` `PAYLOAD_TOO_LARGE`. The door answers it with its own refusal; one it lets escape is answered `413 PAYLOAD_TOO_LARGE`. - Without `maxBytes` the whole body is read, as before. Repeated calls answer what the first read: the same bytes (judged against each call's bound) or the first refusal. - The `body` member's text now names the transport's `413` refusal and its one way out: a door that then reads `rawBody` takes the read over under its own bound, which it owes to `rawBody`. Widening: an implementation that takes no argument still type-checks, and every call that passes nothing behaves as before. ### What each consumer does with it | Consumer | Role | What it does | |:--|:--|:--| | `@objectstack/plugin-hono-server` (`adapter.ts`, `body-limit.ts`) | implementation | Holds `maxBytes` on every read path a byte door reaches: the original body, and a body a JSON or form pre-read already held. Past the bound the source is cancelled. An escaped refusal with no answer written is answered `413 PAYLOAD_TOO_LARGE`. | | `@objectstack/http-conformance` (`adapter.ts`, private, QA) | reference implementation | Mirrors the rule: declared length over the bound refused unread; undeclared body refused past it with the stream paused; escaped refusal answered the same bytes as the standard transport. | | `@objectstack/service-storage` chunk `PUT` | caller | States what `max_upload_mb` leaves this chunk (the limit minus the bytes the upload already holds). | | `@objectstack/service-storage` presigned local raw `PUT` | caller | States `max_upload_mb`. | | `@objectstack/service-storage` upload-link `PUT`, one file | caller | States `max_upload_mb`; also judges the link (open, unexpired, the caller's) **before** reading a byte of the body. A body declaring more than the door takes is still refused first, as before. | | `@objectstack/service-storage` upload-link several-file form, taken over past the transport limit | caller | States its form limit. | | Every caller, `max_upload_mb` unset | — | States no bound; reads the whole body, as before (see Acceptance notes). | Each storage door also still judges the bytes it read after the read, so a host whose `rawBody` ignores `maxBytes` keeps the answers it had. ## Tests All named by the rule, each with CONTROLS for the unchanged paths: - `plugin-hono-server` `body-limit.test.ts` — *a byte door's own bound holds a body whether or not it declares a length*: undeclared body past the bound refused with the source cancelled and bytes pulled at most the bound plus two chunks (`application/octet-stream`, `application/json`); a form taken over after the transport refusal held the same way; declared length over the bound refused with zero bytes pulled; escaped refusal answered 413 naming the bound. CONTROLS: exactly the bound read whole (declared and not); a body already read through `req.body` judged against the bound once read. - `http-conformance` `request-body.conformance.test.ts` — on both adapters over a real socket: body past the bound refused 413 (declared and not); escaped refusal answered 413; parity of the escaped answer's bytes. CONTROLS: exactly the bound read whole. - `service-storage` `storage-limits.test.ts` — local raw `PUT` and chunk `PUT` state their bound and answer 413 with nothing stored and progress unchanged. CONTROLS: exactly the bound stored; no `max_upload_mb` states no bound. - `service-storage` `record-file-access.integration.test.ts` — the upload-link door: bound held for one file with the link left unspent; the link judged before a byte is read (another user's link, a spent link: the body is never read); the several-file form held to the form limit. CONTROLS: a body within the bound lands; no `max_upload_mb` states no bound. **Ablation** (fix committed first, each mutation through `scripts/ablation-replace.mjs`, restored to the HEAD blob with `git diff HEAD` empty): 1. Storage doors state no bound to `rawBody`: 4 of the new storage cases red; restored. 2. Upload-link door reads before judging the link: 1 case red (the link-judged-first case); restored. 3. Transport ignores `maxBytes` on the original body: the new transport describe red (the run did not complete); restored. Not ablated: the reference adapter's in-read stop (its answer is the same either way, since the post-read judgement also refuses; only the transport case measures bytes read). ## Acceptance notes - **Open product choice, not decided here:** with `max_upload_mb` unset a byte door has no bound of its own, so it states none and reads the whole body, as before. What a door's bound should be then is a maintainer decision, reported to the seat as a fork. - The upload-link form's take-over still holds the form's bytes, the parsed form and one buffer per file at once; each is bounded by the form limit. Unchanged here. - A route outside this repository that reads `rawBody` and has a bound should pass it (rule stated in the contract). ## Verification Final head `36ce94c0` (after merging `origin/main` 47a3b95): <details><summary>Touched packages: tests</summary> - `@objectstack/plugin-hono-server` — Test Files 42 passed · Tests 555 passed - `@objectstack/service-storage` — Test Files 84 passed · Tests 1640 passed, 1 skipped - `@objectstack/hono` — Test Files 14 passed · Tests 258 passed - `@objectstack/http-conformance` — Test Files 20 passed · Tests 286 passed </details> <details><summary>Typecheck and generated artifacts</summary> - `typecheck` for `spec`, `plugin-hono-server`, `service-storage`, `http-conformance`, `hono`, `rest`: exit 0, every `check:test-typecheck` OK. - `pnpm --filter @objectstack/spec check:generated`: all 14 generated artifacts up to date. </details> <details><summary>Derived gate families (dispatch-gates --commands, 93)</summary> On `36ce94c0`: 93 derived, 92 exit 0, 1 NOT MEASURED — `node scripts/check-plugin-teardown-shape.mjs --self-test` exit 3 (PREREQUISITE NOT MET: its fixture commit is outside this shallow clone). `dispatch-gates --ran` with exit codes recorded: 93 accounted for, 0 UNRUN. Every other family CI runs is read from this PR's check-runs, not re-run locally. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_017xRBcTHcckwGChckTwu6Lp)_ <!-- signed: security#1 · sunhaolin · session_017xRBcT1w3zpekijraHJE4f --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 89defde commit dd291b8

10 files changed

Lines changed: 928 additions & 95 deletions

File tree

‎.changeset/byte-door-own-bound.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/plugin-hono-server': patch
4+
'@objectstack/service-storage': patch
5+
---
6+
7+
fix(storage, plugin-hono-server): every byte-reading upload door holds a body with no declared length to its own bound, exactly as it holds a declared one
8+
9+
Clause-②: yes (widening) — `IHttpRequest.rawBody` takes an optional `{ maxBytes }`: the bound the reading door states, which an implementation holds whether or not the request declares a length (a declared length over it is refused unread, a body with no declared length is refused once it passes it and read no further, exactly the bound is read whole), refusing with `413` `PAYLOAD_TOO_LARGE`. A call without it reads the whole body, as before, and an implementation that takes no argument still type-checks.
10+
Metadata-protocol: none
11+
12+
- **The contract.** `IHttpRequest.rawBody(options?: { maxBytes?: number })`. A refusal rejects with an error carrying `status` 413 and `code` `PAYLOAD_TOO_LARGE`; the door answers it with its own refusal, and one that lets it escape is answered `413` `PAYLOAD_TOO_LARGE`. Repeated calls answer what the first read: the same bytes, judged against each call's bound, or the first refusal. The `body` contract now also names the transport's `413` refusal and the one way out of it: a door that then reads `rawBody` takes the read over under its own bound, which it owes to `rawBody`.
13+
- **`@objectstack/plugin-hono-server`** holds `maxBytes` on every path a byte door reads through, a body a JSON or form pre-read already held included, and stops reading where the bound is passed.
14+
- **`@objectstack/service-storage`.** The chunk `PUT` states what `max_upload_mb` leaves the chunk, the presigned local raw `PUT` and the upload-link `PUT` state `max_upload_mb`, and the upload link's several-file form, taken over past the transport's limit, states its form limit. Each answers its own `413` `PAYLOAD_TOO_LARGE` when the read is refused. The upload-link `PUT` also judges the link (open, unexpired and the caller's) before it reads a byte of the body; a body that declares more than the door takes is still refused first, as before.
15+
- **Unchanged:** with `max_upload_mb` unset a byte door states no bound and reads the whole body, as before.
16+
17+
**Who moves:** a host that implements `IHttpRequest` itself and serves `rawBody` should honour `maxBytes`; until it does, the storage doors still judge the bytes they read after the read, as before. A route of your own that reads `rawBody` and has a bound should pass it.

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

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,10 @@ import { matchesRoutePattern } from './route-pattern';
4141
import { readRequestBody, type RequestBodyReading, type RequestBodyRefusal } from './request-body';
4242
import {
4343
assertMaxRequestBodyBytes,
44+
declaredLength,
4445
installRequestBodyLimit,
46+
RawBodyTooLarge,
47+
rawBodyMaxBytes,
4548
requestBodyGuardOf,
4649
requestBodyTooLargeAnswer,
4750
requestBodyTooLargeEnvelope,
@@ -868,6 +871,8 @@ export class HonoHttpServer implements IHttpServer {
868871
let bodyReading: RequestBodyReading = await readRequestBody(c);
869872
let refusedBodyRead: RequestBodyRefusal | RequestBodyTooLarge | undefined;
870873
let rawBodyRead: Promise<Buffer> | undefined;
874+
/** Set once a `rawBody({ maxBytes })` read was refused past the door's own bound. */
875+
let refusedRawBodyRead: RawBodyTooLarge | undefined;
871876

872877
_endParse?.();
873878

@@ -912,24 +917,50 @@ export class HonoHttpServer implements IHttpServer {
912917
* (`./body-limit.ts`). Hono's body cache once a pre-read of a body
913918
* within the limit went through it.
914919
*
920+
* The door states its bound as `maxBytes`, and it is held whether
921+
* or not a length is declared: a declared length over it is
922+
* refused unread, a body with no declared length is refused once
923+
* it passes the bound, read no further (`RawBodyTooLarge`). A
924+
* refusal the door lets escape is answered 413 below.
925+
*
915926
* A route that read `body`, was refused it for size, and then
916927
* reads `rawBody()` is a door taking over the read under its own
917928
* bound (an upload door's form larger than the request-body
918929
* limit), so that refusal no longer stands as the answer. Every
919930
* other refusal still does.
920931
*/
921-
rawBody: () => {
932+
rawBody: (options?: { maxBytes?: number }) => {
933+
const maxBytes = rawBodyMaxBytes(options);
922934
if (refusedBodyRead instanceof RequestBodyTooLarge) refusedBodyRead = undefined;
923-
// Repeatable: a second call answers the same bytes as the first.
935+
// Repeatable: a later call answers the bytes the first read,
936+
// judged against its own bound, or the first call's refusal.
924937
rawBodyRead ??= (async () => {
925-
const original = requestBodyGuardOf(c)?.readOriginal();
938+
const declared = declaredLength(c.req.raw);
939+
if (maxBytes !== undefined && declared !== undefined && declared > maxBytes) {
940+
throw new RawBodyTooLarge(maxBytes);
941+
}
942+
const original = requestBodyGuardOf(c)?.readOriginal(maxBytes);
926943
if (original) {
927944
const bytes = await original;
928945
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
929946
}
947+
// Already read by a pre-read within the request-body
948+
// limit (Hono's body cache), so judged once read.
930949
return Buffer.from(await c.req.arrayBuffer());
931950
})();
932-
return rawBodyRead;
951+
return rawBodyRead.then(
952+
(bytes) => {
953+
if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
954+
refusedRawBodyRead = new RawBodyTooLarge(maxBytes);
955+
throw refusedRawBodyRead;
956+
}
957+
return bytes;
958+
},
959+
(err: unknown) => {
960+
if (err instanceof RawBodyTooLarge) refusedRawBodyRead = err;
961+
throw err;
962+
},
963+
);
933964
},
934965
/**
935966
* The transport's own peer address (`IHttpRequest.remoteAddress`)
@@ -1093,6 +1124,15 @@ export class HonoHttpServer implements IHttpServer {
10931124
let response = outcome.response ?? capturedResponse ?? null;
10941125
let rendered: { status: number; code: unknown } | undefined;
10951126

1127+
// A door whose `rawBody({ maxBytes })` read was refused and that
1128+
// answered nothing itself: the refusal is the caller's 413, not this
1129+
// handler's failure to report. A door that answered keeps its answer.
1130+
if (response === null && refusedRawBodyRead) {
1131+
const envelope = requestBodyTooLargeAnswer(refusedRawBodyRead)!;
1132+
closeStream();
1133+
return { response: c.json(envelope.body, envelope.status), failed: false };
1134+
}
1135+
10961136
if (outcome.failed && response === null && opts.renderDeclaredEnvelope) {
10971137
const envelope = declaredEnvelopeForThrow(outcome.thrown);
10981138
if (envelope) {

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

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,3 +243,136 @@ describe('a body refused past the limit releases its source, and a byte door rea
243243
},
244244
);
245245
});
246+
247+
describe('a byte door\'s own bound holds a body whether or not it declares a length', () => {
248+
const LIMIT = 1024;
249+
const BOUND = LIMIT * 4;
250+
const CHUNK = 256;
251+
252+
/** A body of `total` bytes (endless when undefined) that records what was pulled from it and whether it was cancelled. */
253+
function countedBody(total?: number) {
254+
const state = { pulled: 0, cancelled: false };
255+
const stream = new ReadableStream<Uint8Array>({
256+
pull(controller) {
257+
if (total !== undefined && state.pulled >= total) {
258+
controller.close();
259+
return;
260+
}
261+
const size = total === undefined ? CHUNK : Math.min(CHUNK, total - state.pulled);
262+
state.pulled += size;
263+
controller.enqueue(new Uint8Array(size).fill(0x64));
264+
},
265+
cancel() {
266+
state.cancelled = true;
267+
},
268+
}, { highWaterMark: 0 });
269+
return { stream, state };
270+
}
271+
272+
/** Routes that read through `rawBody({ maxBytes: BOUND })`: one answers its own refusal, one lets it escape. */
273+
function serverWithDoors() {
274+
const server = new HonoHttpServer(0);
275+
server.setMaxRequestBodyBytes(LIMIT);
276+
server.put('/api/v1/door/:id', async (req, res) => {
277+
try {
278+
const bytes = await req.rawBody!({ maxBytes: BOUND });
279+
res.json({ success: true, data: { size: bytes.byteLength } });
280+
} catch (err) {
281+
const e = err as { status?: unknown; code?: unknown };
282+
res.status(413).json({ success: false, error: { code: e.code, message: `door refused at ${e.status}` } });
283+
}
284+
});
285+
server.put('/api/v1/escape/:id', async (req, res) => {
286+
const bytes = await req.rawBody!({ maxBytes: BOUND });
287+
res.json({ success: true, data: { size: bytes.byteLength } });
288+
});
289+
// A form door: refused `req.body` for size, it takes the read over under its own bound.
290+
server.put('/api/v1/form/:id', async (req, res) => {
291+
try {
292+
res.json({ success: true, data: { parsed: Object.keys(req.body ?? {}).length } });
293+
} catch (err) {
294+
if ((err as { code?: unknown }).code !== 'PAYLOAD_TOO_LARGE') throw err;
295+
const bytes = await req.rawBody!({ maxBytes: BOUND });
296+
res.json({ success: true, data: { size: bytes.byteLength } });
297+
}
298+
});
299+
return server;
300+
}
301+
302+
function send(path: string, body: ReadableStream<Uint8Array> | Uint8Array, headers: Record<string, string> = {}) {
303+
return serverWithDoors().getRawApp().request(`http://localhost${path}`, {
304+
method: 'PUT',
305+
headers: { 'content-type': 'application/octet-stream', ...headers },
306+
body,
307+
duplex: 'half',
308+
} as RequestInit);
309+
}
310+
311+
it.each([['application/octet-stream'], ['application/json']])(
312+
'a %s body with no declared length is refused past the bound, read no further, its source cancelled',
313+
async (contentType) => {
314+
const { stream, state } = countedBody();
315+
const res = await send('/api/v1/door/f_1', stream, { 'content-type': contentType });
316+
expect(res.status).toBe(413);
317+
expect(((await res.json()) as any).error).toEqual({ code: 'PAYLOAD_TOO_LARGE', message: 'door refused at 413' });
318+
expect(state.cancelled).toBe(true);
319+
expect(state.pulled).toBeLessThanOrEqual(BOUND + 2 * CHUNK);
320+
},
321+
);
322+
323+
it('a form refused req.body for size and taken over is held to the door\'s bound, its source cancelled', async () => {
324+
const { stream, state } = countedBody();
325+
const res = await send('/api/v1/form/f_1', stream, { 'content-type': 'multipart/form-data; boundary=x' });
326+
expect(res.status).toBe(413);
327+
expect(((await res.json()) as any).error.message).toContain(`(${BOUND} bytes)`);
328+
expect(state.cancelled).toBe(true);
329+
expect(state.pulled).toBeLessThanOrEqual(BOUND + 2 * CHUNK);
330+
});
331+
332+
it('a declared length over the bound is refused without reading the body', async () => {
333+
const { stream, state } = countedBody(BOUND + 1);
334+
const res = await send('/api/v1/door/f_1', stream, { 'content-length': String(BOUND + 1) });
335+
expect(res.status).toBe(413);
336+
expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE');
337+
expect(state.pulled).toBe(0);
338+
});
339+
340+
it('a refusal the door lets escape is answered 413 PAYLOAD_TOO_LARGE, naming the door\'s bound', async () => {
341+
const { stream } = countedBody();
342+
const res = await send('/api/v1/escape/f_1', stream);
343+
expect(res.status).toBe(413);
344+
const body = (await res.json()) as any;
345+
expect(body.success).toBe(false);
346+
expect(body.error.code).toBe('PAYLOAD_TOO_LARGE');
347+
expect(body.error.message).toContain(`(${BOUND} bytes)`);
348+
});
349+
350+
it.each([['declared', true], ['not declared', false]])(
351+
'CONTROL: exactly the bound is read whole, length %s',
352+
async (_label, declare) => {
353+
const { stream } = countedBody(BOUND);
354+
const res = await send('/api/v1/door/f_1', stream, declare ? { 'content-length': String(BOUND) } : {});
355+
expect(res.status, await res.clone().text()).toBe(200);
356+
expect(((await res.json()) as any).data.size).toBe(BOUND);
357+
},
358+
);
359+
360+
it('CONTROL: a JSON body within the transport limit, read through req.body first, is judged against the bound once read', async () => {
361+
const server = new HonoHttpServer(0);
362+
server.setMaxRequestBodyBytes(LIMIT);
363+
server.put('/api/v1/both/:id', async (req, res) => {
364+
void req.body;
365+
try {
366+
await req.rawBody!({ maxBytes: 8 });
367+
res.json({ success: true });
368+
} catch (err) {
369+
res.status(413).json({ success: false, error: { code: (err as { code?: unknown }).code } });
370+
}
371+
});
372+
const res = await server.getRawApp().request('http://localhost/api/v1/both/f_1', {
373+
method: 'PUT', headers: { 'content-type': 'application/json' }, body: '{"a":"0123456789"}',
374+
});
375+
expect(res.status).toBe(413);
376+
expect(((await res.json()) as any).error.code).toBe('PAYLOAD_TOO_LARGE');
377+
});
378+
});

0 commit comments

Comments
 (0)