Merge commit from fork
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(ssg): prevent output path traversal * fix(ssg): distinguish Windows output path roots
authored by Taku Amano · committed by GitHub · parent 9c28d72 · Browse files · 4 files·+208 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
4 files+208 added−12 removed
- tests:+164 added−0 removed
- other:+44 added−12 removed
Provenance
- Commit
3a67f7f- Tree
7f017ad- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
9c28d72
4 files changed+208 added−12 removed
modified:src/helper/ssg/ssg.test.tsx+122 added
160 unmodified lines161 expect(result.error).toBeDefined()162 expect(result.files).toStrictEqual([])163 })164 165+ it('Should reject consecutive parent segments from ssgParams', async () => {166+ const app = new Hono()167+ app.get('/:id', ssgParams([{ id: 'a/b/../../../pwned' }]), (c) =>168+ c.text('attacker-controlled-body')169+ )170+ const fsMock: FileSystemModule = {171+ writeFile: vi.fn(() => Promise.resolve()),172+ mkdir: vi.fn(() => Promise.resolve()),173+ }174+175+ const result = await toSSG(app, fsMock, { dir: './static' })176+177+ expect(result.success).toBe(false)178+ expect(result.files).toStrictEqual([])179+ expect(result.error?.message).toContain('Path traversal detected')180+ expect(fsMock.mkdir).not.toHaveBeenCalled()181+ expect(fsMock.writeFile).not.toHaveBeenCalled()182+ })183+184+ it('Should generate files when dir is the current directory', async () => {185+ const app = new Hono()186+ app.get('/', (c) => c.html('Hello, World!'))187+ app.get('/about/some', (c) => c.text('About Page 2tier'))188+ const fsMock: FileSystemModule = {189+ writeFile: vi.fn(() => Promise.resolve()),190+ mkdir: vi.fn(() => Promise.resolve()),191+ }192+193+ const result = await toSSG(app, fsMock, { dir: '.' })194+195+ expect(result.success).toBe(true)196+ expect(result.files).toHaveLength(2)197+ expect(fsMock.writeFile).toHaveBeenCalledWith('index.html', expect.any(String))198+ expect(fsMock.writeFile).toHaveBeenCalledWith('about/some.txt', expect.any(String))199+ expect(fsMock.mkdir).not.toHaveBeenCalledWith('', expect.anything())200+ })201+202+ it('Should reject absolute Windows paths when dir is the current directory', async () => {203+ const app = new Hono()204+ app.get(205+ '/:drive/:dir/:file',206+ ssgParams([{ drive: 'C:', dir: 'Windows', file: 'pwned' }]),207+ (c) => c.text('pwned')208+ )209+ const fsMock: FileSystemModule = {210+ writeFile: vi.fn(() => Promise.resolve()),211+ mkdir: vi.fn(() => Promise.resolve()),212+ }213+214+ const result = await toSSG(app, fsMock, { dir: '.' })215+216+ expect(result.success).toBe(false)217+ expect(result.error?.message).toContain('Path traversal detected')218+ expect(fsMock.mkdir).not.toHaveBeenCalled()219+ expect(fsMock.writeFile).not.toHaveBeenCalled()220+ })221+222+ it('Should reject drive-relative Windows paths when dir is the current directory', async () => {223+ const app = new Hono()224+ app.get('/:id', ssgParams([{ id: 'C:pwned' }]), (c) => c.text('pwned'))225+ const fsMock: FileSystemModule = {226+ writeFile: vi.fn(() => Promise.resolve()),227+ mkdir: vi.fn(() => Promise.resolve()),228+ }229+230+ const result = await toSSG(app, fsMock, { dir: '.' })231+232+ expect(result.success).toBe(false)233+ expect(result.error?.message).toContain('Path traversal detected')234+ expect(fsMock.mkdir).not.toHaveBeenCalled()235+ expect(fsMock.writeFile).not.toHaveBeenCalled()236+ })237+238+ it('Should reject a drive-relative Windows output root', async () => {239+ const app = new Hono()240+ app.get('/', (c) => c.text('Hello, World!'))241+ const fsMock: FileSystemModule = {242+ writeFile: vi.fn(() => Promise.resolve()),243+ mkdir: vi.fn(() => Promise.resolve()),244+ }245+246+ const result = await toSSG(app, fsMock, { dir: 'C:' })247+248+ expect(result.success).toBe(false)249+ expect(result.error?.message).toContain('Path traversal detected')250+ expect(fsMock.mkdir).not.toHaveBeenCalled()251+ expect(fsMock.writeFile).not.toHaveBeenCalled()252+ })253+254+ it('Should preserve a UNC output directory', async () => {255+ const app = new Hono()256+ app.get('/', (c) => c.html('Hello, World!'))257+ const fsMock: FileSystemModule = {258+ writeFile: vi.fn(() => Promise.resolve()),259+ mkdir: vi.fn(() => Promise.resolve()),260+ }261+262+ const result = await toSSG(app, fsMock, { dir: '\\\\server\\share\\out' })263+264+ expect(result.success).toBe(true)265+ expect(fsMock.mkdir).toHaveBeenCalledWith('//server/share/out', { recursive: true })266+ expect(fsMock.writeFile).toHaveBeenCalledWith(267+ '//server/share/out/index.html',268+ expect.any(String)269+ )270+ })271+272+ it('Should normalize redundant leading separators in a POSIX output directory', async () => {273+ const app = new Hono()274+ app.get('/', (c) => c.html('Hello, World!'))275+ const fsMock: FileSystemModule = {276+ writeFile: vi.fn(() => Promise.resolve()),277+ mkdir: vi.fn(() => Promise.resolve()),278+ }279+280+ const result = await toSSG(app, fsMock, { dir: '///tmp/out' })281+282+ expect(result.success).toBe(true)283+ expect(fsMock.mkdir).toHaveBeenCalledWith('/tmp/out', { recursive: true })284+ expect(fsMock.writeFile).toHaveBeenCalledWith('/tmp/out/index.html', expect.any(String))285+ })286+287 it('Should correctly generate files with the expected paths', async () => {288 app.get('/data', (c) =>289 c.text(JSON.stringify({ title: 'hono' }), 200, {290 'Content-Type': 'text/x-foo',906 unmodified linesmodified:src/helper/ssg/ssg.ts+2 added-1 removed
319 unmodified lines320 const { routePath, content, mimeType } = awaitedData321 const filePath = generateFilePath(routePath, outDir, mimeType, extensionMap)322 const dirPath = dirname(filePath)323 324+ // `dirPath` is empty when outDir itself is the current directory324- if (!createdDirs.has(dirPath)) {325+ if (dirPath !== '' && !createdDirs.has(dirPath)) {326 await fsModule.mkdir(dirPath, { recursive: true })327 createdDirs.add(dirPath)328 }329 if (typeof content === 'string') {142 unmodified linesmodified:src/helper/ssg/utils.test.ts+42 added
20 unmodified lines2122232425262728293031323334358 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110220 unmodified lines expect(joinPaths('..', '..', 'test')).toBe('../../test') // parent and parent and single expect(joinPaths('..', '..')).toBe('../..') // parent and parent expect(joinPaths('.test../test2/../')).toBe('.test..') //shuffle expect(joinPaths('.test./.test2/../')).toBe('.test.') //shuffle2 expect(joinPaths('static/a/b/../../../pwned')).toBe('pwned') // consecutive parents expect(joinPaths('///tmp/out', 'index.html')).toBe('/tmp/out/index.html') expect(joinPaths('//tmp', 'index.html')).toBe('/tmp/index.html') }) it('Should windows path is valid.', () => { expect(joinPaths('a\\b\\c', 'd\\e')).toBe('a/b/c/d/e') expect(joinPaths('\\\\server\\share\\out', 'index.html')).toBe('//server/share/out/index.html') })})
describe('dirname', () => {8 unmodified lines expect(() => ensureWithinOutDir('./static', 'static/index.html')).not.toThrow() expect(() => ensureWithinOutDir('./static', 'static/sub/page.html')).not.toThrow() expect(() => ensureWithinOutDir('/out', '/out/index.html')).not.toThrow() expect(() => ensureWithinOutDir('./static', 'static/a/../b.html')).not.toThrow() expect(() => ensureWithinOutDir('./static', 'static/a/b/../../c.html')).not.toThrow() expect(() => ensureWithinOutDir('\\\\server\\share\\out', '//server/share/out/index.html') ).not.toThrow() expect(() => ensureWithinOutDir('///tmp/out', '/tmp/out/index.html')).not.toThrow() expect(() => ensureWithinOutDir('//tmp', '/tmp/index.html')).not.toThrow() })
it('Should throw for paths outside outDir via traversal', () => { expect(() => ensureWithinOutDir('./static', 'pwned.txt')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('./static', '../pwned.txt')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('./out', 'pwned.txt')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('./static', 'static/../../pwned.txt')).toThrow( 'Path traversal detected' ) expect(() => ensureWithinOutDir('./static', 'static/a/../../pwned.txt')).toThrow( 'Path traversal detected' ) })
it('Should throw for paths that partially match outDir name', () => { expect(() => ensureWithinOutDir('./static', 'static-evil/pwned.html')).toThrow( 'Path traversal detected' ) })
it('Should accept the current directory as outDir', () => { expect(() => ensureWithinOutDir('.', 'index.html')).not.toThrow() expect(() => ensureWithinOutDir('./', 'index.html')).not.toThrow() expect(() => ensureWithinOutDir('', 'index.html')).not.toThrow() expect(() => ensureWithinOutDir('.', '../pwned.html')).toThrow('Path traversal detected') })
it('Should throw for paths that climb above a parent outDir', () => { expect(() => ensureWithinOutDir('..', '../out/index.html')).not.toThrow() expect(() => ensureWithinOutDir('..', '../../pwned.txt')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('../..', '../../../pwned.txt')).toThrow( 'Path traversal detected' ) })
it('Should throw when outDir and filePath differ in absoluteness', () => { expect(() => ensureWithinOutDir('/out', 'out/index.html')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('./out', '/out/index.html')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('.', '/etc/pwned.html')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('.', 'C:\\Windows\\pwned.html')).toThrow( 'Path traversal detected' ) expect(() => ensureWithinOutDir('.', 'C:pwned.html')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('C:', 'C:/pwned.html')).toThrow('Path traversal detected') expect(() => ensureWithinOutDir('\\\\server\\share\\out', '/server/share/out/pwned.html') ).toThrow('Path traversal detected') })})modified:src/helper/ssg/utils.ts+42 added-11 removed
15 unmodified lines161718192021202122232425262728293031326 unmodified lines39404142364344454041464748494550515253545556575854596061626314 unmodified lines787980818283848586878889909192939495969798991007879101102103104105106107108109110828311111211311411511611711815 unmodified linesconst normalizePath = (path: string): string => { return path.replace(/(\\)/g, '/').replace(/\/$/g, '')}
const handleParent = (resultPaths: string[], beforeParentFlag: boolean): void => { if (resultPaths.length === 0 || beforeParentFlag) {const getUncRoot = (path: string): string | undefined => { const uncRoot = path.replace(/\\/g, '/').match(/^\/\/([^/]+)\/([^/]+)/) if (uncRoot) { return `${uncRoot[1].toLowerCase()}/${uncRoot[2].toLowerCase()}` }}
const handleParent = (resultPaths: string[]): void => { if (resultPaths.length === 0 || resultPaths[resultPaths.length - 1] === '..') { resultPaths.push('..') } else { resultPaths.pop() }6 unmodified lines }}
const handleSegments = (paths: string[], resultPaths: string[]): void => { let beforeParentFlag = false for (const path of paths) { // Handle `..` if (path === '..') { handleParent(resultPaths, beforeParentFlag) beforeParentFlag = true handleParent(resultPaths) } else { // Handle `.` or `abc` handleNonDot(path, resultPaths) beforeParentFlag = false } }}
export const joinPaths = (...paths: string[]): string => { const hasUncPrefix = getUncRoot(paths[0]) !== undefined paths = paths.map(normalizePath) const resultPaths: string[] = [] handleSegments(paths.join('/').split('/'), resultPaths) return (paths[0][0] === '/' ? '/' : '') + resultPaths.join('/') return (hasUncPrefix ? '//' : paths[0][0] === '/' ? '/' : '') + resultPaths.join('/')}
interface FilterStaticGenerateRouteData { path: string14 unmodified linesexport const isDynamicRoute = (path: string): boolean => { return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))}
const toSegments = (path: string): string[] => (path === '' ? [] : path.split('/'))
const getPathRoot = (path: string): string => { const normalizedPath = path.replace(/\\/g, '/') const uncRoot = getUncRoot(normalizedPath) if (uncRoot) { return `unc:${uncRoot}` }
const driveRoot = normalizedPath.match(/^([A-Za-z]):/) if (driveRoot) { const kind = normalizedPath[2] === '/' ? 'drive-absolute' : 'drive-relative' return `${kind}:${driveRoot[1].toLowerCase()}` }
return normalizedPath.startsWith('/') ? 'absolute' : 'relative'}
export const ensureWithinOutDir = (outDir: string, filePath: string): void => { const normalizedOutDir = joinPaths('/', outDir) const normalizedFilePath = joinPaths('/', filePath) const outDirSegments = toSegments(joinPaths(outDir)) const filePathSegments = toSegments(joinPaths(filePath))
const hasMismatchedPathRoot = getPathRoot(outDir) !== getPathRoot(filePath)
// `joinPaths` collects every remaining `..` at the head, so a `..` right after // the outDir segments means the file path climbs above outDir const climbsAboveOutDir = filePathSegments[outDirSegments.length] === '..'
if ( normalizedFilePath !== normalizedOutDir && !normalizedFilePath.startsWith(`${normalizedOutDir}/`) hasMismatchedPathRoot || filePathSegments.length <= outDirSegments.length || !outDirSegments.every((segment, i) => segment === filePathSegments[i]) || climbsAboveOutDir ) { throw new Error(`Path traversal detected: "${filePath}" is outside the output directory`) }}