Landed
fix(serve-static): only serve GET and HEAD requests (#5514)
Landed as 588ec13
authored by Taku Amano · committed by the platform · parent 552ea02 · Browse files · 2 files·+56 added−0 removed
2 files changed+56 added−0 removed
modified:src/middleware/serve-static/index.test.ts+52 added
43 unmodified lines44 beforeEach(() => {45 getContent.mockClear()46 })47 48+ it.each(['GET', 'HEAD'])(49+ 'Should serve files for %s requests registered with use()',50+ async (method) => {51+ const app = new Hono().use('/static/*', serveStatic)52+53+ const res = await app.request('/static/hello.html', { method })54+55+ expect(res.status).toBe(200)56+ expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)57+ expect(await res.text()).toBe(method === 'HEAD' ? '' : 'Hello in static/hello.html')58+ expect(getContent).toBeCalledTimes(1)59+ }60+ )61+62+ it.each(['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'PROPFIND'])(63+ 'Should pass %s requests to the next handler without accessing files',64+ async (method) => {65+ const isDir = vi.fn(() => false)66+ const rewriteRequestPath = vi.fn((path: string) => path)67+ const onFound = vi.fn()68+ const onNotFound = vi.fn()69+ const app = new Hono().use(70+ '/static/*',71+ baseServeStatic({ getContent, isDir, rewriteRequestPath, onFound, onNotFound })72+ )73+ app.on(method, '/static/hello.html', (c) => c.text('Handled downstream', 202))74+75+ const res = await app.request('/static/hello.html', { method })76+77+ expect(res.status).toBe(202)78+ expect(await res.text()).toBe('Handled downstream')79+ expect(rewriteRequestPath).not.toBeCalled()80+ expect(isDir).not.toBeCalled()81+ expect(getContent).not.toBeCalled()82+ expect(onFound).not.toBeCalled()83+ expect(onNotFound).not.toBeCalled()84+ }85+ )86+87+ it.each(['/static/hello.html', '/static/not-found.txt'])(88+ 'Should return 404 for an unhandled POST request regardless of file existence - %s',89+ async (path) => {90+ const app = new Hono().use('/static/*', serveStatic)91+92+ const res = await app.request(path, { method: 'POST' })93+94+ expect(res.status).toBe(404)95+ expect(await res.text()).toBe('404 Not Found')96+ expect(getContent).not.toBeCalled()97+ }98+ )99+100 it('Should return 200 response - /static/hello.html', async () => {101 const res = await app.request('/static/hello.html')102 expect(res.status).toBe(200)103 expect(res.headers.get('Content-Encoding')).toBeNull()328 unmodified linesmodified:src/middleware/serve-static/index.ts+4 added
57 unmodified lines58596061626364656667686966 unmodified lines57 unmodified lines if (c.finalized) { return next() }
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') { return next() }
let filename: string
if (options.path) { filename = options.path66 unmodified lines