feat(serve-static): support absolute root (#3420)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(serve-static): support absolute root * add bun runtime test * don't use `Request` * add code for deno * remove unnecessay `console.log` * use `normalizeFilePath` instead of `URL` * use `URL` for `options.root` * don't allow directory traversal and fix the behavior when root including `../`
authored by Yusuke Wada · committed by GitHub · parent 7779fca · Browse files · 12 files·+137 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+137 added−12 removed
- tests:+85 added−4 removed
- other:+52 added−8 removed
Provenance
- Commit
246a06a- Tree
303e40e- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7779fca
12 files changed+137 added−12 removed
added:runtime-tests/bun/static-absolute-root/plain.txt+1 added
1+Bun!modified:runtime-tests/bun/index.test.tsx+12 added-4 removed
1 import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2+import fs from 'fs/promises'3+import path from 'path'4 import { stream, streamSSE } from '../..//src/helper/streaming'5 import { serveStatic, toSSG } from '../../src/adapter/bun'6 import { createBunWebSocket } from '../../src/adapter/bun/websocket'7 import type { BunWebSocketData } from '../../src/adapter/bun/websocket'4 unmodified lines12 // eslint-disable-next-line @typescript-eslint/no-unused-vars13 import { jsx } from '../../src/jsx'14 import { basicAuth } from '../../src/middleware/basic-auth'15 import { jwt } from '../../src/middleware/jwt'14-import { HonoRequest } from '../../src/request'16 17 // Test just only minimal patterns.18 // Because others are tested well in Cloudflare Workers environment already.19 22 unmodified lines42 })43 44 describe('Environment Variables', () => {45 it('Should return the environment variable', async () => {45- const c = new Context(new HonoRequest(new Request('http://localhost/')))46+ const c = new Context(new Request('http://localhost/'))47 const { NAME } = env<{ NAME: string }>(c)48 expect(NAME).toBe('Bun')49 })50 })56 unmodified lines107 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),108 })109 )110 111+ app.all('/static-absolute-root/*', serveStatic({ root: path.dirname(__filename) }))112+113 beforeEach(() => onNotFound.mockClear())114 115 it('Should return static file correctly', async () => {116 const res = await app.request(new Request('http://localhost/favicon.ico'))42 unmodified lines159 const res = await app.request('http://localhost/static/hello.world')160 expect(res.status).toBe(200)161 expect(await res.text()).toBe('Hi\n')162 })163+164+ it('Should return 200 response - /static-absolute-root/plain.txt', async () => {165+ const res = await app.request('http://localhost/static-absolute-root/plain.txt')166+ expect(res.status).toBe(200)167+ expect(await res.text()).toBe('Bun!')168+ expect(onNotFound).not.toHaveBeenCalled()169+ })170 })171 172 // Bun support WebCrypto since v0.2.2173 // So, JWT middleware works well.145 unmodified lines319 const receivedMessage = await receivedMessagePromise320 expect(receivedMessage).toBe(message)321 })322 })313-const fs = require('fs').promises314-const path = require('path')323 324 async function deleteDirectory(dirPath) {325 if (326 await fs114 unmodified linesmodified:runtime-tests/deno/.vscode/settings.json+1 added-1 removed
12344567{ "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"], "editor.codeActionsOnSave": { "source.fixAll.eslint": true "source.fixAll.eslint": "explicit" }, "deno.enable": true}added:runtime-tests/deno/static-absolute-root/plain.txt+1 added
1+Deno!modified:runtime-tests/deno/deno.json+2 added-1 removed
11 unmodified lines1213141516171819192011 unmodified lines "sloppy-imports" ], "imports": { "@std/assert": "jsr:@std/assert@^1.0.3", "@std/path": "jsr:@std/path@^1.0.3", "@std/testing": "jsr:@std/testing@^1.0.1", "hono/jsx/jsx-runtime": "../../src/jsx/jsx-runtime.ts" }}}No newline at end of filemodified:runtime-tests/deno/deno.lock+24 added-2 removed
1 {2 "version": "3",3 "packages": {4 "specifiers": {5- "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.3",5+ "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.5",6+ "jsr:@std/assert@^1.0.4": "jsr:@std/assert@1.0.5",7 "jsr:@std/internal@^1.0.2": "jsr:@std/internal@1.0.2",8+ "jsr:@std/internal@^1.0.3": "jsr:@std/internal@1.0.3",9+ "jsr:@std/path@^1.0.3": "jsr:@std/path@1.0.6",7- "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.1"10+ "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.2"11 },12 "jsr": {13 "@std/assert@1.0.3": {14 "integrity": "b0d03ce1ced880df67132eea140623010d415848df66f6aa5df76507ca7c26d8",15 "dependencies": [16 "jsr:@std/internal@^1.0.2"17 ]18 },19+ "@std/assert@1.0.5": {20+ "integrity": "e37da8e4033490ce613eec4ac1d78dba1faf5b02a3f6c573a28f15365b9b440f",21+ "dependencies": [22+ "jsr:@std/internal@^1.0.3"23+ ]24+ },25 "@std/internal@1.0.2": {26 "integrity": "f4cabe2021352e8bfc24e6569700df87bf070914fc38d4b23eddd20108ac4495"27 },28+ "@std/internal@1.0.3": {29+ "integrity": "208e9b94a3d5649bd880e9ca38b885ab7651ab5b5303a56ed25de4755fb7b11e"30+ },31+ "@std/path@1.0.6": {32+ "integrity": "ab2c55f902b380cf28e0eec501b4906e4c1960d13f00e11cfbcd21de15f18fed"33+ },34 "@std/testing@1.0.1": {35 "integrity": "9c25841137ee818933e1722091bb9ed5fdc251c35e84c97979a52196bdb6c5c3",36 "dependencies": [37 "jsr:@std/assert@^1.0.3"38 ]39+ },40+ "@std/testing@1.0.2": {41+ "integrity": "9e8a7f4e26c219addabe7942d09c3450fa0a74e9662341961bc0ef502274dec3",42+ "dependencies": [43+ "jsr:@std/assert@^1.0.4"44+ ]45 }46 }47 },48 "remote": {},49 "workspace": {50 "dependencies": [51 "jsr:@std/assert@^1.0.3",52+ "jsr:@std/path@^1.0.3",53 "jsr:@std/testing@^1.0.1"54 ]55 }56 }modified:runtime-tests/deno/middleware.test.tsx+15 added
12345687 unmodified lines94959697989910010110210310410510610710810911011130 unmodified lines14214314414514614714814915015115215325 unmodified linesimport { assertEquals, assertMatch } from '@std/assert'import { dirname, fromFileUrl } from '@std/path'import { assertSpyCall, assertSpyCalls, spy } from '@std/testing/mock'import { serveStatic } from '../../src/adapter/deno/index.ts'import { Hono } from '../../src/hono.ts'import { basicAuth } from '../../src/middleware/basic-auth/index.ts'87 unmodified lines rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'), }) )
app.get('/static-absolute-root/*', serveStatic({ root: dirname(fromFileUrl(import.meta.url)) }))
app.get( '/static/*', serveStatic({ root: './runtime-tests/deno', onNotFound, }) )
let res = await app.request('http://localhost/favicon.ico') assertEquals(res.status, 200) assertEquals(res.headers.get('Content-Type'), 'image/x-icon') await res.body?.cancel()30 unmodified lines
res = await app.request('http://localhost/static/hello.world') assertEquals(res.status, 200) assertEquals(await res.text(), 'Hi\n')
res = await app.request('http://localhost/static-absolute-root/plain.txt') assertEquals(res.status, 200) assertEquals(await res.text(), 'Deno!')})
Deno.test('JWT Authentication middleware', async () => { const app = new Hono<{ Variables: { 'x-foo': string } }>()25 unmodified linesmodified:src/adapter/bun/serve-static.ts+2 added-2 removed
7 unmodified lines8 options: ServeStaticOptions<E>9 ): MiddlewareHandler => {10 return async function serveStatic(c, next) {11 const getContent = async (path: string) => {12- path = `./${path}`12+ path = path.startsWith('/') ? path : `./${path}`13 // @ts-ignore14 const file = Bun.file(path)15 return (await file.exists()) ? file : null16 }17 const pathResolve = (path: string) => {18- return `./${path}`18+ return path.startsWith('/') ? path : `./${path}`19 }20 const isDir = async (path: string) => {21 let isDir22 try {13 unmodified linesmodified:src/adapter/deno/serve-static.ts+1 added-1 removed
18 unmodified lines19 console.warn(`${e}`)20 }21 }22 const pathResolve = (path: string) => {23- return `./${path}`23+ return path.startsWith('/') ? path : `./${path}`24 }25 const isDir = (path: string) => {26 let isDir27 try {13 unmodified linesmodified:src/middleware/serve-static/index.test.ts+58 added
224 unmodified lines225 } as Request)226 expect(res.status).toBe(200)227 expect(res.body).toBe(body)228 })229+230+ describe('Changing root path', () => {231+ const pathResolve = (path: string) => {232+ return path.startsWith('/') ? path : `./${path}`233+ }234+235+ it('Should return the content with absolute root path', async () => {236+ const app = new Hono()237+ const serveStatic = baseServeStatic({238+ getContent,239+ pathResolve,240+ root: '/home/hono/child',241+ })242+ app.get('/static/*', serveStatic)243+244+ const res = await app.request('/static/html/hello.html')245+ expect(await res.text()).toBe('Hello in /home/hono/child/static/html/hello.html')246+ })247+248+ it('Should traverse the directories with absolute root path', async () => {249+ const app = new Hono()250+ const serveStatic = baseServeStatic({251+ getContent,252+ pathResolve,253+ root: '/home/hono/../parent',254+ })255+ app.get('/static/*', serveStatic)256+257+ const res = await app.request('/static/html/hello.html')258+ expect(await res.text()).toBe('Hello in /home/parent/static/html/hello.html')259+ })260+261+ it('Should treat the root path includes .. as relative path', async () => {262+ const app = new Hono()263+ const serveStatic = baseServeStatic({264+ getContent,265+ pathResolve,266+ root: '../home/hono',267+ })268+ app.get('/static/*', serveStatic)269+270+ const res = await app.request('/static/html/hello.html')271+ expect(await res.text()).toBe('Hello in ./../home/hono/static/html/hello.html')272+ })273+274+ it('Should not allow directory traversal with . as relative path', async () => {275+ const app = new Hono()276+ const serveStatic = baseServeStatic({277+ getContent,278+ pathResolve,279+ root: '.',280+ })281+ app.get('*', serveStatic)282+283+ const res = await app.request('///etc/passwd')284+ expect(res.status).toBe(404)285+ })286+ })287 })modified:src/middleware/serve-static/index.ts+16 added-1 removed
37 unmodified lines38 pathResolve?: (path: string) => string39 isDir?: (path: string) => boolean | undefined | Promise<boolean | undefined>40 }41 ): MiddlewareHandler => {42+ let isAbsoluteRoot = false43+ let root: string44+45+ if (options.root) {46+ if (options.root.startsWith('/')) {47+ isAbsoluteRoot = true48+ root = new URL(`file://${options.root}`).pathname49+ } else {50+ root = options.root51+ }52+ }53+54 return async (c, next) => {55 // Do nothing if Response is already set56 if (c.finalized) {57 await next()1 unmodified line59 }60 61 let filename = options.path ?? decodeURI(c.req.path)62 filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename51- const root = options.root63 64 // If it was Directory, force `/` on the end.65 if (!filename.endsWith('/') && options.isDir) {66 const path = getFilePathWithoutDefaultDocument({14 unmodified lines81 if (!path) {82 return await next()83 }84 85+ if (isAbsoluteRoot) {86+ path = '/' + path87+ }88+89 const getContent = options.getContent90 const pathResolve = options.pathResolve ?? defaultPathResolve91 path = pathResolve(path)92 let content = await getContent(path, c)58 unmodified linesmodified:src/utils/filepath.ts+4 added
50 unmodified lines51 // ./assets/foo.html => assets/foo.html52 let path = root ? root + '/' + filename : filename53 path = path.replace(/^\.?\//, '')54 55+ if (root[0] !== '/' && path[0] === '/') {56+ return57+ }58+59 return path60 }