From 7846a327c5b6cf49a3321b9a583c17ef2e602110 Mon Sep 17 00:00:00 2001 From: Daniel Cavalcante Date: Tue, 1 Dec 2026 19:13:04 -0300 Subject: [PATCH] vfs: enforce trailing separators on mounted paths A path with a trailing separator must name a directory, but resolving a mounted path drops the separator, so VFS operations acted on the file: fs.readFileSync('/file/') returned its contents, fs.writeFileSync('/file/') overwrote it, and fs.unlinkSync() and fs.rmSync() deleted it, where a real file system fails with ENOTDIR or EISDIR. Enforce the separator where paths are resolved, the way each operation enforces it on a POSIX file system: lookups follow links and require a directory; lstat(), readlink() and the l*() functions act on the directory a final link names; unlink(), rmdir() and the source of rename() require the entry itself to be a directory; creating a file or a link there fails. rm() refuses a link to a directory rather than following it into its target. Paths given to an unmounted file system now lose a trailing separator as mounted ones already did, and the callback functions of a VirtualFileSystem report errors from resolving the path through the callback instead of throwing. As for a real path, fs.statSync() with throwIfNoEntry: false returns undefined on ENOTDIR as well as ENOENT. Signed-off-by: Daniel Cavalcante Assisted-by: Claude Opus 5.5 --- lib/fs.js | 4 +- lib/internal/vfs/file_system.js | 382 ++++++++++++++++--- lib/internal/vfs/setup.js | 14 +- test/parallel/test-vfs-trailing-separator.js | 347 +++++++++++++++++ 4 files changed, 683 insertions(+), 64 deletions(-) create mode 100644 test/parallel/test-vfs-trailing-separator.js diff --git a/lib/fs.js b/lib/fs.js index 5150801dc8c0..844fecba9112 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -2183,7 +2183,9 @@ function statSync(path, options = { __proto__: null, bigint: false, throwIfNoEnt const result = h.statSync(path, options); if (result !== undefined) return result; } catch (err) { - if (err?.code === 'ENOENT' && options?.throwIfNoEntry === false) return undefined; + // As in the binding, ENOTDIR also means there is no such entry. + if (options?.throwIfNoEntry === false && + (err?.code === 'ENOENT' || err?.code === 'ENOTDIR')) return undefined; throw err; } } diff --git a/lib/internal/vfs/file_system.js b/lib/internal/vfs/file_system.js index 4982542239ea..ec3f89004a30 100644 --- a/lib/internal/vfs/file_system.js +++ b/lib/internal/vfs/file_system.js @@ -31,11 +31,13 @@ const { } = require('internal/vfs/fd'); const { createENOENT, + createENOTDIR, createEBADF, createEBUSY, createEISDIR, } = require('internal/vfs/errors'); const { encodeRealpathResult, getOptions } = require('internal/fs/utils'); +const { decodeOpenFlags } = require('internal/vfs/file_handle'); const { VirtualReadStream, VirtualWriteStream } = require('internal/vfs/streams'); const { VirtualDir } = require('internal/vfs/dir'); const { emitExperimentalWarning, kEmptyObject } = require('internal/util'); @@ -87,6 +89,36 @@ function randomSuffix() { return suffix; } +// A trailing separator requires a path to name a directory. Resolving a path +// to a provider path drops the separator, so the requirement is enforced +// while resolving, as each operation enforces it on a real file system. +// The separator has no effect: mkdir(), realpath(), mkdtemp(), watch(). +const kTrailingIgnore = 0; +// The path, following links, must name a directory. +const kTrailingFollow = 1; +// As kTrailingFollow, and the operation then acts on the directory a final +// link names, not on the link: lstat(), readlink() and the l*() functions. +const kTrailingResolve = 2; +// The entry itself, not following a link, must be a directory: unlink(), +// rmdir() and the source of rename(). +const kTrailingEntry = 3; +// The operation creates a file there, which can never be a directory. +const kTrailingCreate = 4; +// The operation creates a link there, which can never be a directory: it +// fails because the entry exists or because it does not. +const kTrailingNewEntry = 5; + +function hasTrailingSeparator(inputPath) { + if (inputPath.length < 2) return false; + const last = inputPath[inputPath.length - 1]; + return last === '/' || last === sep; +} + +// Converts a call's flags to how a trailing separator on its path is treated. +function trailingForOpen(flags) { + return decodeOpenFlags(flags).create ? kTrailingCreate : kTrailingFollow; +} + // The root of a file system is its mount point, and like any mount point it // cannot be removed or renamed, nor replaced by a rename. function checkNotRoot(providerPath, syscall, path) { @@ -260,18 +292,145 @@ class VirtualFileSystem { * Converts an absolute mounted path to a provider-relative POSIX path. * If not mounted, treats the path as already provider-relative. * @param {string} inputPath The path to convert + * @param {string} [syscall] The syscall to report errors for + * @param {number} [trailing] How a trailing separator is treated, one of + * the kTrailing* constants * @returns {string} */ - #toProviderPath(inputPath) { + #toProviderPath(inputPath, syscall, trailing = kTrailingIgnore) { + let providerPath; const mountPoint = this[kNormalizedMountPoint]; if (mountPoint !== null) { const resolved = normalizeMountedPath(inputPath); if (!this.shouldHandleNormalized(resolved)) { throw createENOENT('open', inputPath); } - return getRelativePath(resolved, mountPoint); + providerPath = getRelativePath(resolved, mountPoint); + } else { + // Unlike path.resolve() for a mounted path, this keeps a trailing + // separator, which providers do not expect. + providerPath = pathPosix.normalize(inputPath); + if (providerPath.length > 1 && + providerPath[providerPath.length - 1] === '/') { + providerPath = StringPrototypeSlice(providerPath, 0, -1); + } + } + if (trailing !== kTrailingIgnore && providerPath !== '/' && + hasTrailingSeparator(inputPath)) { + return this.#checkTrailingSeparator(providerPath, inputPath, syscall, + trailing); + } + return providerPath; + } + + /** + * Enforces that a path written with a trailing separator names a + * directory, as `trailing` (a kTrailing* constant) asks for the operation. + * Where the path cannot be used for another reason, the operation is left + * to report it. + * @param {string} providerPath The provider path, without the separator + * @param {string} inputPath The path as given + * @param {string} syscall The syscall to report errors for + * @param {number} trailing How the trailing separator is treated + * @returns {string} The provider path the operation should use + */ + #checkTrailingSeparator(providerPath, inputPath, syscall, trailing) { + const provider = this[kProvider]; + switch (trailing) { + case kTrailingCreate: + // The parent is resolved first: where it is missing or not a + // directory, the operation reports that instead. + if (this.#isDirectory(pathPosix.dirname(providerPath))) { + throw createEISDIR(syscall, inputPath); + } + return providerPath; + case kTrailingNewEntry: + try { + provider.lstatSync(providerPath); + } catch (err) { + if (err?.code === 'ENOENT') throw createENOENT(syscall, inputPath); + } + // The entry exists, or cannot be looked up, which the operation + // reports. + return providerPath; + case kTrailingEntry: { + let stats; + try { + stats = provider.lstatSync(providerPath); + } catch { + return providerPath; + } + if (!stats.isDirectory()) throw createENOTDIR(syscall, inputPath); + return providerPath; + } + default: { + let stats; + try { + stats = provider.statSync(providerPath); + } catch { + // On a dangling link, an operation on the link itself would succeed. + if (trailing === kTrailingResolve && + this.#isSymbolicLink(providerPath)) { + throw createENOENT(syscall, inputPath); + } + return providerPath; + } + if (!stats.isDirectory()) throw createENOTDIR(syscall, inputPath); + if (trailing === kTrailingResolve && + this.#isSymbolicLink(providerPath)) { + return provider.realpathSync(providerPath); + } + return providerPath; + } + } + } + + #isDirectory(providerPath) { + try { + return this[kProvider].statSync(providerPath).isDirectory(); + } catch { + return false; + } + } + + #isSymbolicLink(providerPath) { + try { + return this[kProvider].lstatSync(providerPath).isSymbolicLink(); + } catch { + return false; + } + } + + /** + * rm() does not follow a link, and a trailing separator requires a + * directory, so a link to a directory is refused rather than its target + * emptied. Other paths that are not a directory are refused by lstat(). + * @param {string} filePath The path given to rm() + */ + #checkRmTrailingSeparator(filePath) { + if (!hasTrailingSeparator(filePath)) return; + const providerPath = this.#toProviderPath(filePath); + if (providerPath === '/' || !this.#isSymbolicLink(providerPath)) return; + // A dangling link is not a directory, and lstat() reports it. + if (this.#isDirectory(providerPath)) throw createENOTDIR('rm', filePath); + } + + /** + * Resolves the source of rename(). A trailing separator on either path + * requires the source itself to be a directory: a file or a link is not + * renamed from or to a path that names a directory. + * @param {string} oldPath The source path + * @param {string} newPath The destination path + * @returns {string} The source provider path + */ + #toRenameSource(oldPath, newPath) { + if (!hasTrailingSeparator(newPath)) { + return this.#toProviderPath(oldPath, 'rename', kTrailingEntry); } - return pathPosix.normalize(inputPath); + const providerPath = this.#toProviderPath(oldPath); + if (providerPath === '/') return providerPath; + return this.#checkTrailingSeparator(providerPath, oldPath, 'rename', + kTrailingEntry); } /** @@ -296,7 +455,8 @@ class VirtualFileSystem { */ existsSync(filePath) { try { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'access', kTrailingFollow); return this[kProvider].existsSync(providerPath); } catch { return false; @@ -310,7 +470,7 @@ class VirtualFileSystem { * @returns {Stats} */ statSync(filePath, options) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'stat', kTrailingFollow); return this[kProvider].statSync(providerPath, options); } @@ -321,7 +481,8 @@ class VirtualFileSystem { * @returns {Stats} */ lstatSync(filePath, options) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'lstat', kTrailingResolve); return this[kProvider].lstatSync(providerPath, options); } @@ -332,7 +493,8 @@ class VirtualFileSystem { * @returns {Buffer|string} */ readFileSync(filePath, options) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'r')); return this[kProvider].readFileSync(providerPath, options); } @@ -343,7 +505,8 @@ class VirtualFileSystem { * @param {object} [options] Options */ writeFileSync(filePath, data, options) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'w')); this[kProvider].writeFileSync(providerPath, data, options); } @@ -354,7 +517,8 @@ class VirtualFileSystem { * @param {object} [options] Options */ appendFileSync(filePath, data, options) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'a')); this[kProvider].appendFileSync(providerPath, data, options); } @@ -365,7 +529,8 @@ class VirtualFileSystem { * @returns {string[]|Dirent[]} */ readdirSync(dirPath, options) { - const providerPath = this.#toProviderPath(dirPath); + const providerPath = + this.#toProviderPath(dirPath, 'scandir', kTrailingFollow); const result = this[kProvider].readdirSync(providerPath, options); return this.#toMountedDirents(dirPath, result, options); } @@ -417,7 +582,7 @@ class VirtualFileSystem { * @param {string} dirPath The directory path */ rmdirSync(dirPath) { - const providerPath = this.#toProviderPath(dirPath); + const providerPath = this.#toProviderPath(dirPath, 'rmdir', kTrailingEntry); checkNotRoot(providerPath, 'rmdir', dirPath); this[kProvider].rmdirSync(providerPath); } @@ -427,7 +592,8 @@ class VirtualFileSystem { * @param {string} filePath The file path */ unlinkSync(filePath) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'unlink', kTrailingEntry); this[kProvider].unlinkSync(providerPath); } @@ -437,7 +603,7 @@ class VirtualFileSystem { * @param {string} newPath The new path */ renameSync(oldPath, newPath) { - const oldProviderPath = this.#toProviderPath(oldPath); + const oldProviderPath = this.#toRenameSource(oldPath, newPath); const newProviderPath = this.#toProviderPath(newPath); checkNotRoot(oldProviderPath, 'rename', oldPath); checkNotRoot(newProviderPath, 'rename', newPath); @@ -451,8 +617,10 @@ class VirtualFileSystem { * @param {number} [mode] Copy mode flags */ copyFileSync(src, dest, mode) { - const srcProviderPath = this.#toProviderPath(src); - const destProviderPath = this.#toProviderPath(dest); + const srcProviderPath = + this.#toProviderPath(src, 'copyfile', kTrailingFollow); + const destProviderPath = + this.#toProviderPath(dest, 'copyfile', kTrailingCreate); this[kProvider].copyFileSync(srcProviderPath, destProviderPath, mode); } @@ -477,7 +645,8 @@ class VirtualFileSystem { */ readlinkSync(linkPath, options) { options = getOptions(options); - const providerPath = this.#toProviderPath(linkPath); + const providerPath = + this.#toProviderPath(linkPath, 'readlink', kTrailingResolve); return encodeRealpathResult(this[kProvider].readlinkSync(providerPath), options); } @@ -488,7 +657,8 @@ class VirtualFileSystem { * @param {string} [type] The symlink type */ symlinkSync(target, path, type) { - const providerPath = this.#toProviderPath(path); + const providerPath = + this.#toProviderPath(path, 'symlink', kTrailingNewEntry); this[kProvider].symlinkSync(target, providerPath, type); } @@ -498,7 +668,8 @@ class VirtualFileSystem { * @param {number} [mode] Access mode */ accessSync(filePath, mode) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'access', kTrailingFollow); this[kProvider].accessSync(providerPath, mode); } @@ -515,6 +686,7 @@ class VirtualFileSystem { let stats; try { + this.#checkRmTrailingSeparator(filePath); stats = this.lstatSync(filePath); } catch (err) { if (force && err?.code === 'ENOENT') return; @@ -548,7 +720,7 @@ class VirtualFileSystem { */ truncateSync(filePath, len = 0) { if (len < 0) len = 0; - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'open', kTrailingFollow); const handle = this[kProvider].openSync(providerPath, 'r+'); try { handle.truncateSync(len); @@ -576,33 +748,37 @@ class VirtualFileSystem { * @param {string} newPath The new link path */ linkSync(existingPath, newPath) { - const existingProviderPath = this.#toProviderPath(existingPath); - const newProviderPath = this.#toProviderPath(newPath); + const existingProviderPath = + this.#toProviderPath(existingPath, 'link', kTrailingFollow); + const newProviderPath = + this.#toProviderPath(newPath, 'link', kTrailingNewEntry); this[kProvider].linkSync(existingProviderPath, newProviderPath); } chmodSync(filePath, mode) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'chmod', kTrailingFollow); this[kProvider].chmodSync(providerPath, mode); } chownSync(filePath, uid, gid) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'chown', kTrailingFollow); this[kProvider].chownSync(providerPath, uid, gid); } lchownSync(filePath, uid, gid) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'lchown', kTrailingResolve); this[kProvider].lchownSync(providerPath, uid, gid); } utimesSync(filePath, atime, mtime) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'utime', kTrailingFollow); this[kProvider].utimesSync(providerPath, atime, mtime); } lutimesSync(filePath, atime, mtime) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'lutime', kTrailingResolve); this[kProvider].lutimesSync(providerPath, atime, mtime); } @@ -664,7 +840,7 @@ class VirtualFileSystem { */ openAsBlob(filePath, options) { const { Blob } = require('buffer'); - const providerPath = this.#toProviderPath(filePath); + const providerPath = this.#toProviderPath(filePath, 'stat', kTrailingFollow); const content = this[kProvider].readFileSync(providerPath); const type = options?.type || ''; return new Blob([content], { type }); @@ -678,7 +854,8 @@ class VirtualFileSystem { * @returns {number} The file descriptor */ openSync(filePath, flags = 'r', mode) { - const providerPath = this.#toProviderPath(filePath); + const providerPath = + this.#toProviderPath(filePath, 'open', trailingForOpen(flags)); const handle = this[kProvider].openSync(providerPath, flags, mode); return openVirtualFd(handle); } @@ -756,7 +933,15 @@ class VirtualFileSystem { options = undefined; } - this[kProvider].readFile(this.#toProviderPath(filePath), options) + let providerPath; + try { + providerPath = this.#toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'r')); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].readFile(providerPath, options) .then((data) => callback(null, data), (err) => callback(err)); } @@ -773,7 +958,15 @@ class VirtualFileSystem { options = undefined; } - this[kProvider].writeFile(this.#toProviderPath(filePath), data, options) + let providerPath; + try { + providerPath = this.#toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'w')); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].writeFile(providerPath, data, options) .then(() => callback(null), (err) => callback(err)); } @@ -789,7 +982,14 @@ class VirtualFileSystem { options = undefined; } - this[kProvider].stat(this.#toProviderPath(filePath), options) + let providerPath; + try { + providerPath = this.#toProviderPath(filePath, 'stat', kTrailingFollow); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].stat(providerPath, options) .then((stats) => callback(null, stats), (err) => callback(err)); } @@ -805,7 +1005,14 @@ class VirtualFileSystem { options = undefined; } - this[kProvider].lstat(this.#toProviderPath(filePath), options) + let providerPath; + try { + providerPath = this.#toProviderPath(filePath, 'lstat', kTrailingResolve); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].lstat(providerPath, options) .then((stats) => callback(null, stats), (err) => callback(err)); } @@ -821,7 +1028,14 @@ class VirtualFileSystem { options = undefined; } - this[kProvider].readdir(this.#toProviderPath(dirPath), options) + let providerPath; + try { + providerPath = this.#toProviderPath(dirPath, 'scandir', kTrailingFollow); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].readdir(providerPath, options) .then((entries) => callback(null, this.#toMountedDirents(dirPath, entries, options)), (err) => callback(err)); } @@ -857,7 +1071,14 @@ class VirtualFileSystem { } options = getOptions(options); - this[kProvider].readlink(this.#toProviderPath(linkPath)) + let providerPath; + try { + providerPath = this.#toProviderPath(linkPath, 'readlink', kTrailingResolve); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].readlink(providerPath) .then((target) => callback(null, encodeRealpathResult(target, options)), (err) => callback(err)); } @@ -873,7 +1094,14 @@ class VirtualFileSystem { mode = undefined; } - this[kProvider].access(this.#toProviderPath(filePath), mode) + let providerPath; + try { + providerPath = this.#toProviderPath(filePath, 'access', kTrailingFollow); + } catch (err) { + process.nextTick(callback, err); + return; + } + this[kProvider].access(providerPath, mode) .then(() => callback(null), (err) => callback(err)); } @@ -894,7 +1122,13 @@ class VirtualFileSystem { mode = undefined; } - const providerPath = this.#toProviderPath(filePath); + let providerPath; + try { + providerPath = this.#toProviderPath(filePath, 'open', trailingForOpen(flags)); + } catch (err) { + process.nextTick(callback, err); + return; + } this[kProvider].open(providerPath, flags, mode) .then((handle) => { const fd = openVirtualFd(handle); @@ -1201,7 +1435,11 @@ class VirtualFileSystem { const provider = this[kProvider]; // Arrow functions capture `this` for private method access. - const toProviderPath = (p) => this.#toProviderPath(p); + const toProviderPath = (p, syscall, trailing) => + this.#toProviderPath(p, syscall, trailing); + const toRenameSource = (oldPath, newPath) => + this.#toRenameSource(oldPath, newPath); + const checkRmTrailingSeparator = (p) => this.#checkRmTrailingSeparator(p); const toProviderPrefix = (p) => this.#toProviderPrefix(p); const toMountedPath = (p) => this.#toMountedPath(p); const toMountedDirents = (p, result, options) => @@ -1209,32 +1447,37 @@ class VirtualFileSystem { return ObjectFreeze({ async readFile(filePath, options) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'r')); return provider.readFile(providerPath, options); }, async writeFile(filePath, data, options) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'w')); return provider.writeFile(providerPath, data, options); }, async appendFile(filePath, data, options) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath( + filePath, 'open', trailingForOpen(options?.flag ?? 'a')); return provider.appendFile(providerPath, data, options); }, async stat(filePath, options) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath(filePath, 'stat', kTrailingFollow); return provider.stat(providerPath, options); }, async lstat(filePath, options) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'lstat', kTrailingResolve); return provider.lstat(providerPath, options); }, async readdir(dirPath, options) { - const providerPath = toProviderPath(dirPath); + const providerPath = + toProviderPath(dirPath, 'scandir', kTrailingFollow); const result = await provider.readdir(providerPath, options); return toMountedDirents(dirPath, result, options); }, @@ -1246,18 +1489,19 @@ class VirtualFileSystem { }, async rmdir(dirPath) { - const providerPath = toProviderPath(dirPath); + const providerPath = toProviderPath(dirPath, 'rmdir', kTrailingEntry); checkNotRoot(providerPath, 'rmdir', dirPath); return provider.rmdir(providerPath); }, async unlink(filePath) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'unlink', kTrailingEntry); return provider.unlink(providerPath); }, async rename(oldPath, newPath) { - const oldProviderPath = toProviderPath(oldPath); + const oldProviderPath = toRenameSource(oldPath, newPath); const newProviderPath = toProviderPath(newPath); checkNotRoot(oldProviderPath, 'rename', oldPath); checkNotRoot(newProviderPath, 'rename', newPath); @@ -1265,8 +1509,10 @@ class VirtualFileSystem { }, async copyFile(src, dest, mode) { - const srcProviderPath = toProviderPath(src); - const destProviderPath = toProviderPath(dest); + const srcProviderPath = + toProviderPath(src, 'copyfile', kTrailingFollow); + const destProviderPath = + toProviderPath(dest, 'copyfile', kTrailingCreate); return provider.copyFile(srcProviderPath, destProviderPath, mode); }, @@ -1278,17 +1524,20 @@ class VirtualFileSystem { async readlink(linkPath, options) { options = getOptions(options); - const providerPath = toProviderPath(linkPath); + const providerPath = + toProviderPath(linkPath, 'readlink', kTrailingResolve); return encodeRealpathResult(await provider.readlink(providerPath), options); }, async symlink(target, path, type) { - const providerPath = toProviderPath(path); + const providerPath = + toProviderPath(path, 'symlink', kTrailingNewEntry); return provider.symlink(target, providerPath, type); }, async access(filePath, mode) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'access', kTrailingFollow); return provider.access(providerPath, mode); }, @@ -1298,7 +1547,9 @@ class VirtualFileSystem { let stats; try { - stats = await provider.lstat(toProviderPath(filePath)); + checkRmTrailingSeparator(filePath); + stats = await provider.lstat( + toProviderPath(filePath, 'lstat', kTrailingResolve)); } catch (err) { if (force && err?.code === 'ENOENT') return; throw err; @@ -1325,7 +1576,7 @@ class VirtualFileSystem { }, async truncate(filePath, len = 0) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath(filePath, 'open', kTrailingFollow); const handle = await provider.open(providerPath, 'r+'); try { await handle.truncate(len); @@ -1335,8 +1586,10 @@ class VirtualFileSystem { }, async link(existingPath, newPath) { - const existingProviderPath = toProviderPath(existingPath); - const newProviderPath = toProviderPath(newPath); + const existingProviderPath = + toProviderPath(existingPath, 'link', kTrailingFollow); + const newProviderPath = + toProviderPath(newPath, 'link', kTrailingNewEntry); return provider.link(existingProviderPath, newProviderPath); }, @@ -1357,38 +1610,42 @@ class VirtualFileSystem { }, async chmod(filePath, mode) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath(filePath, 'chmod', kTrailingFollow); provider.chmodSync(providerPath, mode); }, async chown(filePath, uid, gid) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath(filePath, 'chown', kTrailingFollow); provider.chownSync(providerPath, uid, gid); }, async lchown(filePath, uid, gid) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'lchown', kTrailingResolve); provider.lchownSync(providerPath, uid, gid); }, async utimes(filePath, atime, mtime) { - const providerPath = toProviderPath(filePath); + const providerPath = toProviderPath(filePath, 'utime', kTrailingFollow); provider.utimesSync(providerPath, atime, mtime); }, async lutimes(filePath, atime, mtime) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'lutime', kTrailingResolve); provider.lutimesSync(providerPath, atime, mtime); }, async open(filePath, flags, mode) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'open', trailingForOpen(flags)); const handle = provider.openSync(providerPath, flags, mode); return openVirtualFd(handle); }, async lchmod(filePath, mode) { - const providerPath = toProviderPath(filePath); + const providerPath = + toProviderPath(filePath, 'lchmod', kTrailingResolve); provider.lchmodSync(providerPath, mode); }, @@ -1402,6 +1659,7 @@ class VirtualFileSystem { module.exports = { VirtualFileSystem, + hasTrailingSeparator, kLayerId, kLoadLayer, kReservedRoot, diff --git a/lib/internal/vfs/setup.js b/lib/internal/vfs/setup.js index 2f4e9f31ab89..960559eb053a 100644 --- a/lib/internal/vfs/setup.js +++ b/lib/internal/vfs/setup.js @@ -28,6 +28,7 @@ const { const { createENOENT, createEROFS, createEXDEV } = require('internal/vfs/errors'); const { VirtualFileSystem, + hasTrailingSeparator, kLayerId, kReservedRoot, normalizeMountedPath, @@ -376,6 +377,17 @@ function findVFSWith(filename, syscall, fn) { if (fn === undefined) return true; return fn(r.vfs, filename); } + // A path with a trailing separator can name an entry that is not the + // directory the separator requires; the VFS reports which error applies. + if (fn !== undefined && hasTrailingSeparator(filename)) { + try { + return fn(r.vfs, filename); + } catch (err) { + // Nothing is there, which is reported for the path as given. + if (err?.code === 'ENOENT') throw createENOENT(syscall, filename); + throw err; + } + } throw createENOENT(syscall, filename); } @@ -787,7 +799,7 @@ function createVfsHandlers() { const promise = vfsOp(path, (vfs, n) => vfs.promises.stat(n, options)); if (promise !== undefined && options?.throwIfNoEntry === false) { return promise.catch((err) => { - if (err?.code === 'ENOENT') return undefined; + if (err?.code === 'ENOENT' || err?.code === 'ENOTDIR') return undefined; throw err; }); } diff --git a/test/parallel/test-vfs-trailing-separator.js b/test/parallel/test-vfs-trailing-separator.js new file mode 100644 index 000000000000..061d9d45f69b --- /dev/null +++ b/test/parallel/test-vfs-trailing-separator.js @@ -0,0 +1,347 @@ +// Flags: --disable-warning=ExperimentalWarning +'use strict'; + +// A trailing separator requires a path to name a directory. Resolving a +// mounted path drops the separator, so each operation must still enforce the +// requirement, as a real file system does. Each case states the outcome on a +// POSIX file system. + +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vfs = require('node:vfs'); +const { test } = require('node:test'); + +const targets = ['file', 'dir', 'missing', 'lfile', 'ldir', 'ldang']; + +// The outcome of each operation on `/`, in the order of `targets`: +// 'ok', 'ok:', or the error code. null: not covered here. +const cases = [ + ['stat', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ok', 'ENOENT'], + // The separator resolves a final link: lstat() reports the directory. + ['lstat', 'ENOTDIR', 'ok:true', 'ENOENT', 'ENOTDIR', 'ok:true', 'ENOENT'], + ['access', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ok', 'ENOENT'], + ['exists', 'ok:false', 'ok:true', 'ok:false', 'ok:false', 'ok:true', 'ok:false'], + ['readFile', 'ENOTDIR', 'EISDIR', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOENT'], + ['readdir', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ok', 'ENOENT'], + ['openR', 'ENOTDIR', null, 'ENOENT', 'ENOTDIR', null, 'ENOENT'], + ['openRplus', 'ENOTDIR', 'EISDIR', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOENT'], + // Creating a file at a path that must name a directory always fails. + ['openW', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR'], + ['writeFile', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR'], + ['appendFile', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR'], + ['truncate', 'ENOTDIR', 'EISDIR', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOENT'], + // The entry itself must be a directory, even a link to one is not. + ['unlink', 'ENOTDIR', 'EISDIR', 'ENOENT', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR'], + ['rmdir', 'ENOTDIR', 'ENOTEMPTY', 'ENOENT', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR'], + ['mkdir', 'EEXIST', 'EEXIST', 'ok', 'EEXIST', 'EEXIST', null], + // On a real file system, rmSync() empties the directory a link names before + // it fails, and fs.promises.rm() reports success. Neither is followed here: + // both refuse the link and remove nothing. + ['rm', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ENOTDIR', 'ENOENT'], + ['readlink', 'ENOTDIR', 'EINVAL', 'ENOENT', 'ENOTDIR', 'EINVAL', 'ENOENT'], + ['chmod', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ok', 'ENOENT'], + ['utimes', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ok', 'ENOENT'], + ['renameFrom', 'ENOTDIR', 'ok', 'ENOENT', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR'], + // Renaming a file to a path that must name a directory always fails. + ['renameFileTo', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR'], + ['renameDirTo', 'ENOTDIR', 'ok', 'ok', 'ENOTDIR', 'ENOTDIR', 'ENOTDIR'], + ['copyFrom', 'ENOTDIR', 'EISDIR', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOENT'], + ['copyTo', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR', 'EISDIR'], + ['linkFrom', 'ENOTDIR', null, 'ENOENT', 'ENOTDIR', null, 'ENOENT'], + ['linkTo', 'EEXIST', 'EEXIST', 'ENOENT', 'EEXIST', 'EEXIST', 'EEXIST'], + ['symlinkTo', 'EEXIST', 'EEXIST', 'ENOENT', 'EEXIST', 'EEXIST', 'EEXIST'], +]; + +const fsp = fs.promises; +const ops = { + stat: { + sync: (r, p) => fs.statSync(p), + promise: (r, p) => fsp.stat(p), + }, + lstat: { + sync: (r, p) => fs.lstatSync(p).isDirectory(), + promise: async (r, p) => (await fsp.lstat(p)).isDirectory(), + }, + access: { + sync: (r, p) => fs.accessSync(p), + promise: (r, p) => fsp.access(p), + }, + exists: { + sync: (r, p) => fs.existsSync(p), + }, + readFile: { + sync: (r, p) => fs.readFileSync(p), + promise: (r, p) => fsp.readFile(p), + }, + readdir: { + sync: (r, p) => fs.readdirSync(p), + promise: (r, p) => fsp.readdir(p), + }, + openR: { + sync: (r, p) => fs.closeSync(fs.openSync(p, 'r')), + promise: async (r, p) => (await fsp.open(p, 'r')).close(), + }, + openRplus: { + sync: (r, p) => fs.closeSync(fs.openSync(p, 'r+')), + }, + openW: { + sync: (r, p) => fs.closeSync(fs.openSync(p, 'w')), + promise: async (r, p) => (await fsp.open(p, 'w')).close(), + }, + writeFile: { + sync: (r, p) => fs.writeFileSync(p, 'z'), + promise: (r, p) => fsp.writeFile(p, 'z'), + }, + appendFile: { + sync: (r, p) => fs.appendFileSync(p, 'z'), + promise: (r, p) => fsp.appendFile(p, 'z'), + }, + truncate: { + sync: (r, p) => fs.truncateSync(p), + promise: (r, p) => fsp.truncate(p), + }, + unlink: { + sync: (r, p) => fs.unlinkSync(p), + promise: (r, p) => fsp.unlink(p), + }, + rmdir: { + sync: (r, p) => fs.rmdirSync(p), + promise: (r, p) => fsp.rmdir(p), + }, + mkdir: { + sync: (r, p) => fs.mkdirSync(p), + promise: (r, p) => fsp.mkdir(p), + }, + rm: { + sync: (r, p) => fs.rmSync(p, { recursive: true }), + promise: (r, p) => fsp.rm(p, { recursive: true }), + }, + readlink: { + sync: (r, p) => fs.readlinkSync(p), + promise: (r, p) => fsp.readlink(p), + }, + chmod: { + sync: (r, p) => fs.chmodSync(p, 0o755), + promise: (r, p) => fsp.chmod(p, 0o755), + }, + utimes: { + sync: (r, p) => fs.utimesSync(p, 1, 1), + promise: (r, p) => fsp.utimes(p, 1, 1), + }, + renameFrom: { + sync: (r, p) => fs.renameSync(p, path.join(r, 'moved')), + promise: (r, p) => fsp.rename(p, path.join(r, 'moved')), + }, + renameFileTo: { + sync: (r, p) => fs.renameSync(path.join(r, 'file'), p), + promise: (r, p) => fsp.rename(path.join(r, 'file'), p), + }, + renameDirTo: { + sync: (r, p) => fs.renameSync(path.join(r, 'dir'), p), + promise: (r, p) => fsp.rename(path.join(r, 'dir'), p), + }, + copyFrom: { + sync: (r, p) => fs.copyFileSync(p, path.join(r, 'copy')), + promise: (r, p) => fsp.copyFile(p, path.join(r, 'copy')), + }, + copyTo: { + sync: (r, p) => fs.copyFileSync(path.join(r, 'file'), p), + promise: (r, p) => fsp.copyFile(path.join(r, 'file'), p), + }, + linkFrom: { + sync: (r, p) => fs.linkSync(p, path.join(r, 'hardlink')), + promise: (r, p) => fsp.link(p, path.join(r, 'hardlink')), + }, + linkTo: { + sync: (r, p) => fs.linkSync(path.join(r, 'file'), p), + promise: (r, p) => fsp.link(path.join(r, 'file'), p), + }, + symlinkTo: { + sync: (r, p) => fs.symlinkSync('file', p), + promise: (r, p) => fsp.symlink('file', p), + }, +}; + +function populate(layer) { + layer.writeFileSync('/file', 'x'); + layer.mkdirSync('/dir'); + layer.writeFileSync('/dir/in', 'y'); + layer.symlinkSync('file', '/lfile'); + layer.symlinkSync('dir', '/ldir'); + layer.symlinkSync('nope', '/ldang'); +} + +// Mounts a populated layer until the test `t` ends, and returns it. +function mount(t) { + const layer = vfs.create(); + populate(layer); + layer.mount(); + t.after(() => layer.unmount()); + return layer; +} + +async function check(fn, expected, label) { + let result; + let error; + try { + result = await fn(); + } catch (err) { + error = err; + } + if (expected === 'ok' || expected.startsWith('ok:')) { + assert.strictEqual(error, undefined, `${label}: ${error}`); + if (expected !== 'ok') { + assert.strictEqual(String(result), expected.slice(3), label); + } + } else { + assert.strictEqual(error?.code, expected, `${label}: ${error ?? result}`); + } +} + +for (const [name, ...outcomes] of cases) { + for (const [api, run] of Object.entries(ops[name])) { + for (let i = 0; i < targets.length; i++) { + if (outcomes[i] === null) continue; + test(`${api} ${name} on ${targets[i]}/`, async (t) => { + const root = mount(t).mountPoint; + const target = path.join(root, targets[i]) + '/'; + await check(() => run(root, target), outcomes[i], `${targets[i]}/`); + }); + } + } +} + +test('refused operations leave the file system unchanged', async (t) => { + const root = mount(t).mountPoint; + const file = path.join(root, 'file'); + assert.throws(() => fs.writeFileSync(`${file}/`, 'z'), { code: 'EISDIR' }); + assert.throws(() => fs.unlinkSync(`${file}/`), { code: 'ENOTDIR' }); + assert.throws(() => fs.renameSync(`${file}/`, path.join(root, 'moved')), + { code: 'ENOTDIR' }); + assert.throws(() => fs.rmSync(`${file}/`), { code: 'ENOTDIR' }); + assert.strictEqual(fs.readFileSync(file, 'utf8'), 'x'); + + const ldir = path.join(root, 'ldir'); + for (const rm of [fs.rmSync, fsp.rm]) { + await assert.rejects(async () => rm(`${ldir}/`, { recursive: true }), + { code: 'ENOTDIR' }); + assert(fs.lstatSync(ldir).isSymbolicLink()); + assert.strictEqual(fs.readFileSync(path.join(root, 'dir', 'in'), 'utf8'), + 'y'); + } +}); + +test('creating a file reports a parent that is not a directory first', async (t) => { + const root = mount(t).mountPoint; + for (const [parent, code] of [['missing', 'ENOENT'], ['file', 'ENOTDIR']]) { + const target = `${path.join(root, parent, 'x')}/`; + assert.throws(() => fs.writeFileSync(target, 'z'), { code }); + assert.throws(() => fs.openSync(target, 'w'), { code }); + assert.throws(() => fs.copyFileSync(path.join(root, 'file'), target), + { code }); + await assert.rejects(fsp.appendFile(target, 'z'), { code }); + } +}); + +test('the open flag decides whether a file would be created', async (t) => { + const root = mount(t).mountPoint; + const file = path.join(root, 'file'); + const created = path.join(root, 'new'); + assert.throws(() => fs.readFileSync(`${created}/`, { flag: 'a+' }), + { code: 'EISDIR' }); + await assert.rejects(fsp.readFile(`${created}/`, { flag: 'w+' }), + { code: 'EISDIR' }); + assert.strictEqual(fs.existsSync(created), false); + assert.throws(() => fs.writeFileSync(`${file}/`, 'z', { flag: 'r+' }), + { code: 'ENOTDIR' }); + assert.strictEqual(fs.readFileSync(file, 'utf8'), 'x'); +}); + +test('errors and options treat the separator as for a real path', async (t) => { + const layer = mount(t); + const root = layer.mountPoint; + const file = path.join(root, 'file'); + const missing = `${path.join(root, 'missing')}/`; + // stat() treats ENOTDIR as no entry; lstat() does not. + assert.strictEqual(fs.statSync(`${file}/`, { throwIfNoEntry: false }), + undefined); + assert.throws(() => fs.lstatSync(`${file}/`, { throwIfNoEntry: false }), + { code: 'ENOTDIR' }); + + assert.throws(() => fs.statSync(missing), + { code: 'ENOENT', syscall: 'stat', path: missing }); + assert.throws(() => fs.readFileSync(missing), + { code: 'ENOENT', syscall: 'open', path: missing }); + + fs.rmSync(missing, { force: true }); + await fsp.rm(missing, { force: true }); + const outside = `${path.join(common.isWindows ? 'C:\\' : '/', 'outside')}/`; + layer.rmSync(outside, { force: true }); + await layer.promises.rm(outside, { force: true }); +}); + +test('the separator is enforced on provider paths too', async () => { + const layer = vfs.create(); + populate(layer); + assert.throws(() => layer.statSync('/file/'), { code: 'ENOTDIR' }); + assert.throws(() => layer.readFileSync('/file/'), { code: 'ENOTDIR' }); + assert.throws(() => layer.writeFileSync('/file/', 'z'), { code: 'EISDIR' }); + assert.strictEqual(layer.existsSync('/file/'), false); + assert.strictEqual(layer.statSync('/dir/').isDirectory(), true); + layer.mkdirSync('/new/'); + assert.strictEqual(layer.statSync('/new').isDirectory(), true); + await assert.rejects(layer.promises.stat('/file/'), { code: 'ENOTDIR' }); +}); + +test('callback functions report the error through the callback', () => { + const layer = vfs.create(); + populate(layer); + layer.stat('/file/', common.mustCall((err) => { + assert.strictEqual(err.code, 'ENOTDIR'); + })); + layer.readFile('/new/', { flag: 'a+' }, common.mustCall((err) => { + assert.strictEqual(err.code, 'EISDIR'); + })); + layer.open('/file/', 'w', common.mustCall((err) => { + assert.strictEqual(err.code, 'EISDIR'); + })); +}); + +test('fs.realpathSync() ignores the separator, as on a real file system', (t) => { + const root = mount(t).mountPoint; + const file = path.join(root, 'file'); + assert.strictEqual(fs.realpathSync(`${file}/`), file); +}); + +test('the root of the mount accepts the separator', (t) => { + const root = mount(t).mountPoint; + assert.strictEqual(fs.statSync(`${root}/`).isDirectory(), true); + assert.deepStrictEqual(fs.readdirSync(`${root}/`).sort(), + ['dir', 'file', 'ldang', 'ldir', 'lfile']); +}); + +test('a RealFSProvider enforces the separator', () => { + const tmpdir = require('../common/tmpdir'); + tmpdir.refresh(); + const dir = tmpdir.resolve('vfs-trailing-separator'); + fs.mkdirSync(path.join(dir, 'sub'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'file'), 'x'); + const layer = vfs.create(new vfs.RealFSProvider(dir)); + const root = layer.mount(); + try { + assert.throws(() => fs.statSync(path.join(root, 'file') + '/'), + { code: 'ENOTDIR' }); + // The platform separator counts as well: `\` on Windows. + assert.throws(() => fs.statSync(path.join(root, 'file') + path.sep), + { code: 'ENOTDIR' }); + assert.throws(() => fs.writeFileSync(path.join(root, 'file') + '/', 'z'), + { code: 'EISDIR' }); + assert.strictEqual(fs.statSync(path.join(root, 'sub') + '/').isDirectory(), + true); + } finally { + layer.unmount(); + } + assert.strictEqual(fs.readFileSync(path.join(dir, 'file'), 'utf8'), 'x'); +});