Skip to content

Commit

Permalink
fix: gracefully handle forbidden filesystem access (#10793)
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout committed Nov 13, 2022
1 parent 3b770a5 commit 92637a2
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 11 deletions.
27 changes: 27 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
@@ -1,10 +1,12 @@
import fs from 'node:fs'
import { describe, expect, test } from 'vitest'
import {
asyncFlatten,
getHash,
getLocalhostAddressIfDiffersFromDNS,
getPotentialTsSrcPaths,
injectQuery,
isFileReadable,
isWindows,
posToNumber,
resolveHostname
Expand Down Expand Up @@ -236,3 +238,28 @@ describe('asyncFlatten', () => {
expect(arr).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9])
})
})

describe('isFileReadable', () => {
test("file doesn't exist", async () => {
expect(isFileReadable('/does_not_exist')).toBe(false)
})

const testFile = require.resolve(
'./utils/isFileReadable/permission-test-file'
)
test('file with normal permission', async () => {
expect(isFileReadable(testFile)).toBe(true)
})

if (process.platform !== 'win32') {
test('file with read-only permission', async () => {
fs.chmodSync(testFile, '400')
expect(isFileReadable(testFile)).toBe(true)
})
test('file without read permission', async () => {
fs.chmodSync(testFile, '044')
expect(isFileReadable(testFile)).toBe(false)
fs.chmodSync(testFile, '644')
})
}
})
Empty file.
3 changes: 0 additions & 3 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -531,9 +531,6 @@ function tryResolveFile(
tryPrefix?: string,
skipPackageJson?: boolean
): string | undefined {
// #2051 if we don't have read permission on a directory, existsSync() still
// works and will result in massively slow subsequent checks (which are
// unnecessary in the first place)
if (isFileReadable(file)) {
if (!fs.statSync(file).isDirectory()) {
return getRealPath(file, options.preserveSymlinks) + postfix
Expand Down
10 changes: 2 additions & 8 deletions packages/vite/src/node/utils.ts
Expand Up @@ -535,16 +535,10 @@ export function writeFile(
fs.writeFileSync(filename, content)
}

/**
* Use fs.statSync(filename) instead of fs.existsSync(filename)
* #2051 if we don't have read permission on a directory, existsSync() still
* works and will result in massively slow subsequent checks (which are
* unnecessary in the first place)
*/
export function isFileReadable(filename: string): boolean {
try {
const stat = fs.statSync(filename, { throwIfNoEntry: false })
return !!stat
fs.accessSync(filename, fs.constants.R_OK)
return true
} catch {
return false
}
Expand Down

0 comments on commit 92637a2

Please sign in to comment.