Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: gracefully handle forbidden filesystem access #10793

Merged
merged 7 commits into from Nov 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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')
})
}
})
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