Skip to content
Myr

feat: introduce Body Limit Middleware using stream (#2103)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat: introduce Body Limit Middleware using stream * denoify * feat(body-limit): Replace c.req.raw with body limit middleware proxy (#2109) * fix(body-limit): fix typo * feat(body-limit): Replace `c.req.raw` with body limit middleware proxy * refactor(body-limit): we can trust content-length header * fix(body-limit): call controller.error instead of throwing an error * test(body-limit): add test for ReadableStream body * chore: denoify * refactor(middleware/body-limit): throw HTTPException instead of retuning c.text() * remove `Unit` untility * denoify * fixed example * denoify ---------

authored by Yusuke Wada · committed by GitHub · parent e8f81bf · Browse files · 4 files+343 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Ame_x <121654029+EdamAme-x@users.noreply.github.com>
  • Co-authored-by: Taku Amano <taku@taaas.jp>

Diff stats

4 files+343 added−0 removed

  • tests:+143 added−0 removed
  • other:+200 added−0 removed

4 files+343 added−0 removed

added:deno_dist/middleware/body-limit/index.ts+96 added
1import type { Context } from '../../context.ts'2import { HTTPException } from '../../http-exception.ts'3import type { MiddlewareHandler } from '../../types.ts'45const ERROR_MESSAGE = 'Payload Too Large'67type OnError = (c: Context) => Response | Promise<Response>8type BodyLimitOptions = {9 maxSize: number10 onError?: OnError11}1213class BodyLimitError extends Error {14 constructor(message: string) {15 super(message)16 this.name = 'BodyLimitError'17 }18}1920/**21 * Body Limit Middleware22 *23 * @example24 * ```ts25 * app.post(26 * '/hello',27 * bodyLimit({28 * maxSize: 100 * 1024, // 100kb29 * onError: (c) => {30 * return c.text('overflow :(', 413)31 * }32 * }),33 * (c) => {34 * return c.text('pass :)')35 * }36 * )37 * ```38 */39export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40 const onError: OnError =41 options.onError ||42 (() => {43 const res = new Response(ERROR_MESSAGE, {44 status: 413,45 })46 throw new HTTPException(413, { res })47 })48 const maxSize = options.maxSize4950 return async function bodyLimit(c, next) {51 if (!c.req.raw.body) {52 // maybe GET or HEAD request53 return next()54 }5556 if (c.req.raw.headers.has('content-length')) {57 // we can trust content-length header because it's already validated by server58 const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59 return contentLength > maxSize ? onError(c) : next()60 }6162 // maybe chunked transfer encoding6364 let size = 065 const rawReader = c.req.raw.body.getReader()66 const reader = new ReadableStream({67 async start(controller) {68 try {69 for (;;) {70 const { done, value } = await rawReader.read()71 if (done) {72 break73 }74 size += value.length75 if (size > maxSize) {76 controller.error(new BodyLimitError(ERROR_MESSAGE))77 break78 }7980 controller.enqueue(value)81 }82 } finally {83 controller.close()84 }85 },86 })8788 c.req.raw = new Request(c.req.raw, { body: reader })8990 await next()9192 if (c.error instanceof BodyLimitError) {93 c.res = await onError(c)94 }95 }96}
added:src/middleware/body-limit/index.test.ts+143 added
1import { Hono } from '../../hono'2import { bodyLimit } from '.'34const GlobalRequest = globalThis.Request5globalThis.Request = class Request extends GlobalRequest {6 constructor(input: Request | string, init: RequestInit) {7 if (init) {8 // eslint-disable-next-line @typescript-eslint/no-explicit-any9 ;(init as any).duplex ??= 'half'10 }11 super(input, init)12 }13} as typeof GlobalRequest1415const buildRequestInit = (init: RequestInit = {}): RequestInit => {16 const headers: Record<string, string> = {17 'Content-Type': 'text/plain',18 }19 if (typeof init.body === 'string') {20 headers['Content-Length'] = init.body.length.toString()21 }22 return {23 method: 'POST',24 headers,25 body: null,26 ...init,27 }28}2930describe('Body Limit Middleware', () => {31 let app: Hono3233 const exampleText = 'hono is so cool' // 15byte34 const exampleText2 = 'hono is so cool and cute' // 24byte3536 beforeEach(() => {37 app = new Hono()38 app.use('*', bodyLimit({ maxSize: 15 }))39 app.get('/', (c) => c.text('index'))40 app.post('/body-limit-15byte', async (c) => {41 return c.text(await c.req.raw.text())42 })43 })4445 describe('GET request', () => {46 it('should return 200 response', async () => {47 const res = await app.request('/')48 expect(res).not.toBeNull()49 expect(res.status).toBe(200)50 expect(await res.text()).toBe('index')51 })52 })5354 describe('POST request', () => {55 describe('string body', () => {56 it('should return 200 response', async () => {57 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: exampleText }))5859 expect(res).not.toBeNull()60 expect(res.status).toBe(200)61 expect(await res.text()).toBe(exampleText)62 })6364 it('should return 413 response', async () => {65 const res = await app.request(66 '/body-limit-15byte',67 buildRequestInit({ body: exampleText2 })68 )6970 expect(res).not.toBeNull()71 expect(res.status).toBe(413)72 expect(await res.text()).toBe('Payload Too Large')73 })74 })7576 describe('ReadableStream body', () => {77 it('should return 200 response', async () => {78 const contents = ['a', 'b', 'c']79 const stream = new ReadableStream({80 start(controller) {81 while (contents.length) {82 controller.enqueue(new TextEncoder().encode(contents.shift() as string))83 }84 controller.close()85 },86 })87 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))8889 expect(res).not.toBeNull()90 expect(res.status).toBe(200)91 expect(await res.text()).toBe('abc')92 })9394 it('should return 413 response', async () => {95 const readSpy = vi.fn().mockImplementation(() => {96 return {97 done: false,98 value: new TextEncoder().encode(exampleText),99 }100 })101 const stream = new ReadableStream()102 vi.spyOn(stream, 'getReader').mockReturnValue({103 read: readSpy,104 } as unknown as ReadableStreamDefaultReader)105 const res = await app.request('/body-limit-15byte', buildRequestInit({ body: stream }))106107 expect(res).not.toBeNull()108 expect(res.status).toBe(413)109 expect(readSpy).toHaveBeenCalledTimes(2)110 expect(await res.text()).toBe('Payload Too Large')111 })112 })113 })114115 describe('custom error handler', () => {116 beforeEach(() => {117 app = new Hono()118 app.post(119 '/text-limit-15byte-custom',120 bodyLimit({121 maxSize: 15,122 onError: (c) => {123 return c.text('no', 413)124 },125 }),126 (c) => {127 return c.text('yes')128 }129 )130 })131132 it('should return the custom error handler', async () => {133 const res = await app.request(134 '/text-limit-15byte-custom',135 buildRequestInit({ body: exampleText2 })136 )137138 expect(res).not.toBeNull()139 expect(res.status).toBe(413)140 expect(await res.text()).toBe('no')141 })142 })143})
added:src/middleware/body-limit/index.ts+96 added
1import type { Context } from '../../context'2import { HTTPException } from '../../http-exception'3import type { MiddlewareHandler } from '../../types'45const ERROR_MESSAGE = 'Payload Too Large'67type OnError = (c: Context) => Response | Promise<Response>8type BodyLimitOptions = {9 maxSize: number10 onError?: OnError11}1213class BodyLimitError extends Error {14 constructor(message: string) {15 super(message)16 this.name = 'BodyLimitError'17 }18}1920/**21 * Body Limit Middleware22 *23 * @example24 * ```ts25 * app.post(26 * '/hello',27 * bodyLimit({28 * maxSize: 100 * 1024, // 100kb29 * onError: (c) => {30 * return c.text('overflow :(', 413)31 * }32 * }),33 * (c) => {34 * return c.text('pass :)')35 * }36 * )37 * ```38 */39export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => {40 const onError: OnError =41 options.onError ||42 (() => {43 const res = new Response(ERROR_MESSAGE, {44 status: 413,45 })46 throw new HTTPException(413, { res })47 })48 const maxSize = options.maxSize4950 return async function bodyLimit(c, next) {51 if (!c.req.raw.body) {52 // maybe GET or HEAD request53 return next()54 }5556 if (c.req.raw.headers.has('content-length')) {57 // we can trust content-length header because it's already validated by server58 const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10)59 return contentLength > maxSize ? onError(c) : next()60 }6162 // maybe chunked transfer encoding6364 let size = 065 const rawReader = c.req.raw.body.getReader()66 const reader = new ReadableStream({67 async start(controller) {68 try {69 for (;;) {70 const { done, value } = await rawReader.read()71 if (done) {72 break73 }74 size += value.length75 if (size > maxSize) {76 controller.error(new BodyLimitError(ERROR_MESSAGE))77 break78 }7980 controller.enqueue(value)81 }82 } finally {83 controller.close()84 }85 },86 })8788 c.req.raw = new Request(c.req.raw, { body: reader })8990 await next()9192 if (c.error instanceof BodyLimitError) {93 c.res = await onError(c)94 }95 }96}
modified:package.json+8 added
72 unmodified lines
73 "types": "./dist/types/middleware/bearer-auth/index.d.ts",74 "import": "./dist/middleware/bearer-auth/index.js",75 "require": "./dist/cjs/middleware/bearer-auth/index.js"76 },77 "./body-limit": {78 "types": "./dist/types/middleware/body-limit/index.d.ts",79 "import": "./dist/middleware/body-limit/index.js",80 "require": "./dist/cjs/middleware/body-limit/index.js"81 },82 "./cache": {83 "types": "./dist/types/middleware/cache/index.d.ts",84 "import": "./dist/middleware/cache/index.js",85 "require": "./dist/cjs/middleware/cache/index.js"
256 unmodified lines
342 ],343 "bearer-auth": [344 "./dist/types/middleware/bearer-auth"345 ],346 "body-limit": [347 "./dist/types/middleware/body-limit"348 ],349 "cache": [350 "./dist/types/middleware/cache"351 ],352 "cookie": [
197 unmodified lines