index.test.ts
This file
Path
src/middleware/serve-static/index.test.ts
431 lines · 13.9 KiB · TypeScript
Last changed by
History of this fileTake it
1import { serveStatic as baseServeStatic } from '.'2import { Hono } from '../../hono'34describe('Serve Static Middleware with a Blob body', () => {5 it('Should serve content returned as a Blob', async () => {6 const app = new Hono()7 app.use(8 '/static/*',9 baseServeStatic({10 getContent: async (path) => new Blob([`Hello in ${path}`]),11 })12 )13 const res = await app.request('http://localhost/static/hello.txt')14 expect(res.status).toBe(200)15 expect(await res.text()).toBe('Hello in static/hello.txt')16 })17})1819describe('Serve Static Middleware', () => {20 const app = new Hono()21 const getContent = vi.fn(async (path) => {22 if (path.endsWith('not-found.txt')) {23 return null24 }25 return `Hello in ${path}`26 })2728 const serveStatic = baseServeStatic({29 getContent,30 isDir: (path) => {31 if (path === 'static/sub' || path === 'static/hello.world') {32 return true33 }34 },35 onFound: (path, c) => {36 if (path.endsWith('hello.html')) {37 c.header('X-Custom', `Found the file at ${path}`)38 }39 },40 })4142 app.get('/static/*', serveStatic)4344 beforeEach(() => {45 getContent.mockClear()46 })4748 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)5253 const res = await app.request('/static/hello.html', { method })5455 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 )6162 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))7475 const res = await app.request('/static/hello.html', { method })7677 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 )8687 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)9192 const res = await app.request(path, { method: 'POST' })9394 expect(res.status).toBe(404)95 expect(await res.text()).toBe('404 Not Found')96 expect(getContent).not.toBeCalled()97 }98 )99100 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()104 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)105 expect(await res.text()).toBe('Hello in static/hello.html')106 expect(res.headers.get('X-Custom')).toBe('Found the file at static/hello.html')107 })108109 it('Should return 200 response - /static/sub', async () => {110 const res = await app.request('/static/sub')111 expect(res.status).toBe(200)112 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)113 expect(await res.text()).toBe('Hello in static/sub/index.html')114 })115116 it('Should return 200 response - /static/hello.world', async () => {117 const res = await app.request('/static/hello.world')118 expect(res.status).toBe(200)119 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)120 expect(await res.text()).toBe('Hello in static/hello.world/index.html')121 })122123 it.each([124 ['/static/%E7%82%8E.txt', 'static/炎.txt'],125 ['/static/hello%20world.txt', 'static/hello world.txt'],126 ])('Should decode URI strings - %s', async (url, path) => {127 const res = await app.request(url)128 expect(res.status).toBe(200)129 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)130 expect(await res.text()).toBe(`Hello in ${path}`)131 })132133 it.each(['/static/100%25.txt', '/static/100%25/hello.txt', '/static/%2Fadmin/secret.txt'])(134 'Should skip paths containing percent signs by default - %s',135 async (path) => {136 const onNotFound = vi.fn()137 const app = new Hono().use('*', baseServeStatic({ getContent, onNotFound }))138139 const res = await app.request(path)140141 expect(res.status).toBe(404)142 expect(getContent).not.toBeCalled()143 expect(onNotFound).toHaveBeenCalledWith(path, expect.anything())144 }145 )146147 it.each([148 ['/static/100%25.txt', 'static/100%.txt'],149 ['/static/100%25/hello.txt', 'static/100%/hello.txt'],150 ['/static/%2Fadmin/secret.txt', 'static/%2Fadmin/secret.txt'],151 ])('Should allow percent signs when opted in - %s', async (url, path) => {152 const app = new Hono().use('*', baseServeStatic({ getContent, allowPercentInPath: true }))153154 const res = await app.request(url)155156 expect(res.status).toBe(200)157 expect(await res.text()).toBe(`Hello in ${path}`)158 })159160 it('Should not bypass authentication through a second decode', async () => {161 const app = new Hono()162 app.get('/static/admin/*', (c) => c.text('Unauthorized', 401))163 app.use('/static/*', baseServeStatic({ getContent }))164165 const protectedRes = await app.request('/static/admin/secret.txt')166 expect(protectedRes.status).toBe(401)167168 const res = await app.request('/static/%%36%31dmin/secret.txt')169 expect(res.status).toBe(404)170 expect(getContent).not.toBeCalled()171 })172173 it('Should return 404 response - /static/not-found.txt', async () => {174 const res = await app.request('/static/not-found.txt')175 expect(res.status).toBe(404)176 expect(res.headers.get('Content-Encoding')).toBeNull()177 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)178 expect(await res.text()).toBe('404 Not Found')179 expect(getContent).toBeCalledTimes(1)180 })181182 it('Should return 200 response for empty string content - /static/empty.txt', async () => {183 const onNotFound = vi.fn()184 const app = new Hono().use(185 '*',186 baseServeStatic({187 getContent: async () => '',188 onNotFound,189 })190 )191 const res = await app.request('/static/empty.txt')192 expect(res.status).toBe(200)193 expect(await res.text()).toBe('')194 expect(onNotFound).not.toBeCalled()195 })196197 it('Should not allow a directory traversal - /static/%2e%2e/static/hello.html', async () => {198 const res = await app.fetch({199 method: 'GET',200 url: 'http://localhost/static/%2e%2e/static/hello.html',201 } as Request)202 expect(res.status).toBe(404)203 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)204 expect(await res.text()).toBe('404 Not Found')205 })206207 it('Should not allow a backslash separator injection - /static/admin%5Csecret.txt', async () => {208 const res = await app.fetch({209 method: 'GET',210 url: 'http://localhost/static/admin%5Csecret.txt',211 } as Request)212 expect(res.status).toBe(404)213 expect(await res.text()).toBe('404 Not Found')214 })215216 it('Should return a pre-compressed zstd response - /static/hello.html', async () => {217 const app = new Hono().use(218 '*',219 baseServeStatic({220 getContent,221 precompressed: true,222 })223 )224225 const res = await app.request('/static/hello.html', {226 headers: { 'Accept-Encoding': 'zstd' },227 })228229 expect(res.status).toBe(200)230 expect(res.headers.get('Content-Encoding')).toBe('zstd')231 expect(res.headers.get('Vary')).toBe('Accept-Encoding')232 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)233 expect(await res.text()).toBe('Hello in static/hello.html.zst')234 })235236 it('Should return a pre-compressed brotli response - /static/hello.html', async () => {237 const app = new Hono().use(238 '*',239 baseServeStatic({240 getContent,241 precompressed: true,242 })243 )244245 const res = await app.request('/static/hello.html', {246 headers: { 'Accept-Encoding': 'wompwomp, gzip, br, deflate, zstd' },247 })248249 expect(res.status).toBe(200)250 expect(res.headers.get('Content-Encoding')).toBe('br')251 expect(res.headers.get('Vary')).toBe('Accept-Encoding')252 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)253 expect(await res.text()).toBe('Hello in static/hello.html.br')254 })255256 it('Should return a pre-compressed brotli response - /static/hello.unknown', async () => {257 const app = new Hono().use(258 '*',259 baseServeStatic({260 getContent,261 precompressed: true,262 })263 )264265 const res = await app.request('/static/hello.unknown', {266 headers: { 'Accept-Encoding': 'wompwomp, gzip, br, deflate, zstd' },267 })268269 expect(res.status).toBe(200)270 expect(res.headers.get('Content-Encoding')).toBe('br')271 expect(res.headers.get('Vary')).toBe('Accept-Encoding')272 expect(res.headers.get('Content-Type')).toBe('application/octet-stream')273 expect(await res.text()).toBe('Hello in static/hello.unknown.br')274 })275276 it('Should not return a pre-compressed response - /static/not-found.txt', async () => {277 const app = new Hono().use(278 '*',279 baseServeStatic({280 getContent,281 precompressed: true,282 })283 )284285 const res = await app.request('/static/not-found.txt', {286 headers: { 'Accept-Encoding': 'gzip, zstd, br' },287 })288289 expect(res.status).toBe(404)290 expect(res.headers.get('Content-Encoding')).toBeNull()291 expect(res.headers.get('Vary')).toBeNull()292 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)293 expect(await res.text()).toBe('404 Not Found')294 })295296 it('Should not return a pre-compressed response - /static/hello.html', async () => {297 const app = new Hono().use(298 '*',299 baseServeStatic({300 getContent,301 precompressed: true,302 })303 )304305 const res = await app.request('/static/hello.html', {306 headers: { 'Accept-Encoding': 'wompwomp, unknown' },307 })308309 expect(res.status).toBe(200)310 expect(res.headers.get('Content-Encoding')).toBeNull()311 expect(res.headers.get('Vary')).toBeNull()312 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)313 expect(await res.text()).toBe('Hello in static/hello.html')314 })315316 it('Should not find pre-compressed files - /static/hello.jpg', async () => {317 const app = new Hono().use(318 '*',319 baseServeStatic({320 getContent,321 precompressed: true,322 })323 )324325 const res = await app.request('/static/hello.jpg', {326 headers: { 'Accept-Encoding': 'gzip, br, deflate, zstd' },327 })328329 expect(res.status).toBe(200)330 expect(res.headers.get('Content-Encoding')).toBeNull()331 expect(res.headers.get('Vary')).toBeNull()332 expect(res.headers.get('Content-Type')).toMatch(/^image\/jpeg/)333 expect(await res.text()).toBe('Hello in static/hello.jpg')334 })335336 it('Should return response object content as-is', async () => {337 const body = new ReadableStream()338 const response = new Response(body)339 const app = new Hono().use(340 '*',341 baseServeStatic({342 getContent: async () => {343 return response344 },345 })346 )347348 const res = await app.fetch({349 method: 'GET',350 url: 'http://localhost',351 } as Request)352 expect(res.status).toBe(200)353 expect(res.body).toBe(body)354 })355356 describe('Changing root path', () => {357 it('Should return the content with absolute root path', async () => {358 const app = new Hono()359 const serveStatic = baseServeStatic({360 getContent,361 root: '/home/hono/child',362 })363 app.get('/static/*', serveStatic)364365 const res = await app.request('/static/html/hello.html')366 expect(await res.text()).toBe('Hello in /home/hono/child/static/html/hello.html')367 })368369 it('Should traverse the directories with absolute root path', async () => {370 const app = new Hono()371 const serveStatic = baseServeStatic({372 getContent,373 root: '/home/hono/../parent',374 })375 app.get('/static/*', serveStatic)376377 const res = await app.request('/static/html/hello.html')378 expect(await res.text()).toBe('Hello in /home/parent/static/html/hello.html')379 })380381 it('Should treat the root path includes .. as relative path', async () => {382 const app = new Hono()383 const serveStatic = baseServeStatic({384 getContent,385 root: '../home/hono',386 })387 app.get('/static/*', serveStatic)388389 const res = await app.request('/static/html/hello.html')390 expect(await res.text()).toBe('Hello in ../home/hono/static/html/hello.html')391 })392393 it('Should not allow directory traversal with . as relative path', async () => {394 const app = new Hono()395 const serveStatic = baseServeStatic({396 getContent,397 root: '.',398 })399 app.get('*', serveStatic)400401 const res = await app.request('/etc/passwd')402 expect(await res.text()).toBe('Hello in etc/passwd')403 })404405 it('Should not allow bypass via path mismatch between middleware and serveStatic', async () => {406 const app = new Hono()407408 app.use('/admin/*', async (c, next) => {409 c.header('X-Authorized', 'true')410 await next()411 })412413 const serveStatic = baseServeStatic({414 getContent,415 root: '.',416 })417 app.use('/*', serveStatic)418419 const res = await app.request('/admin/secret.txt')420 expect(res.headers.get('X-Authorized')).toBe('true')421 expect(await res.text()).toBe('Hello in admin/secret.txt')422423 const res2 = await app.request('/admin%2Fsecret.txt')424 expect(res2.headers.get('X-Authorized')).toBeNull()425 expect(res2.status).toBe(404)426427 const res3 = await app.request('//admin/secret.txt')428 expect(res3.status).toBe(404)429 })430 })431})