Merge commit from fork
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 614b834 · Browse files · 2 files·+99 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+99 added−41 removed
- tests:+72 added−0 removed
- other:+27 added−41 removed
Provenance
- Commit
db05b96- Tree
9814b51- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
614b834
2 files changed+99 added−41 removed
modified:src/middleware/body-limit/index.test.ts+72 added
196 unmodified lines197 expect(res.status).toBe(200)198 expect(await res.text()).toBe(content)199 })200 })201+202+ describe('chunked body bypass scenarios', () => {203+ const handler = vi.fn()204+205+ const buildOversizedRequestInit = (): RequestInit & { duplex: 'half' } => ({206+ method: 'POST',207+ headers: { 'Transfer-Encoding': 'chunked' },208+ body: new ReadableStream({209+ start(controller) {210+ controller.enqueue(new TextEncoder().encode('1234'))211+ controller.enqueue(new TextEncoder().encode('5678901234567890'))212+ controller.close()213+ },214+ }),215+ duplex: 'half',216+ })217+218+ beforeEach(() => {219+ handler.mockReset()220+ app = new Hono()221+ app.use('*', bodyLimit({ maxSize: 8 }))222+ app.post('/no-read', (c) => {223+ handler()224+ return c.text('NO-READ-OK')225+ })226+ app.post('/partial-read', async (c) => {227+ handler()228+ const reader = c.req.raw.body?.getReader()229+ const chunk = reader ? await reader.read() : { value: undefined }230+ return c.text(new TextDecoder().decode(chunk.value))231+ })232+ app.post('/swallow-error', async (c) => {233+ handler()234+ const body = c.req.raw.body235+ if (!body) {236+ return c.text('no body')237+ }238+ const reader = body.getReader()239+ let seen = ''240+ try {241+ for (;;) {242+ const { done, value } = await reader.read()243+ if (done) {244+ break245+ }246+ seen += new TextDecoder().decode(value)247+ }248+ } catch {249+ // intentionally swallow read errors250+ }251+ return c.text(`processed:${seen}`)252+ })253+ })254+255+ it('should reject when handler does not read the body', async () => {256+ const res = await app.request('/no-read', buildOversizedRequestInit())257+ expect(res.status).toBe(413)258+ expect(handler).not.toHaveBeenCalled()259+ })260+261+ it('should reject when handler reads only the first chunk', async () => {262+ const res = await app.request('/partial-read', buildOversizedRequestInit())263+ expect(res.status).toBe(413)264+ expect(handler).not.toHaveBeenCalled()265+ })266+267+ it('should reject when handler swallows body read errors', async () => {268+ const res = await app.request('/swallow-error', buildOversizedRequestInit())269+ expect(res.status).toBe(413)270+ expect(handler).not.toHaveBeenCalled()271+ })272+ })273 })modified:src/middleware/body-limit/index.ts+27 added-41 removed
13 unmodified lines14151617181920212223241819202144 unmodified lines6667686977787980818283707172737475909176777879808182839495969798991001011021031041051068485868788899091929394959697989910810010111010211211311411511610310410510610710811912012112212310911011113 unmodified lines maxSize: number onError?: OnError}
class BodyLimitError extends Error { constructor(message: string) { super(message) this.name = 'BodyLimitError' }}
/** * Body Limit Middleware for Hono. * * @see {@link https://hono.dev/docs/middleware/builtin/body-limit}44 unmodified lines
const hasTransferEncoding = c.req.raw.headers.has('transfer-encoding') const hasContentLength = c.req.raw.headers.has('content-length')
// RFC 7230: If both Transfer-Encoding and Content-Length are present, // Transfer-Encoding takes precedence and Content-Length should be ignored if (hasTransferEncoding && hasContentLength) { // Both headers present - follow RFC 7230 and ignore Content-Length // This might indicate request smuggling attempt }
if (hasContentLength && !hasTransferEncoding) { // Only Content-Length present - we can trust it const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10) return contentLength > maxSize ? onError(c) : next() }
// Transfer-Encoding present (chunked) or no length headers
// Transfer-Encoding present (chunked) or no length headers. // Per RFC 7230, when both are present Transfer-Encoding takes precedence // and Content-Length is ignored. Read the body up-front so the size check // is final before the handler runs, regardless of how (or whether) the // handler reads the body. let size = 0 const chunks: Uint8Array[] = [] const rawReader = c.req.raw.body.getReader() const reader = new ReadableStream({ async start(controller) { try { for (;;) { const { done, value } = await rawReader.read() if (done) { break } size += value.length if (size > maxSize) { controller.error(new BodyLimitError(ERROR_MESSAGE)) break } for (;;) { const { done, value } = await rawReader.read() if (done) { break } size += value.length if (size > maxSize) { return onError(c) } chunks.push(value) }
const requestInit: RequestInit & { duplex: 'half' } = { body: new ReadableStream({ start(controller) { for (const chunk of chunks) { controller.enqueue(value) controller.enqueue(chunk) } } finally { controller.close() } }, })
const requestInit: RequestInit & { duplex: 'half' } = { body: reader, duplex: 'half' } }, }), duplex: 'half', } c.req.raw = new Request(c.req.raw, requestInit as RequestInit)
await next()
if (c.error instanceof BodyLimitError) { c.res = await onError(c) } return next() }}