From 8df2191aea0055f476f1cad5ae03cd38fee4b7b1 Mon Sep 17 00:00:00 2001 From: Paolo Insogna Date: Fri, 20 Nov 2026 10:58:52 +0100 Subject: [PATCH] src: resolve watched path once in FSEventWrap `FSEventWrap::Start()` checked the read scope on the path as it was passed in, then started the watch on the same string, and later used it again to check the entries reported by libuv. A relative path or a symbolic link could resolve differently at each of those steps, for example after `process.chdir()` or when the link was replaced. Resolve the path to its canonical form once, check the read scope on it, and use the same path to start the watch and to check the reported entries. A path whose canonical form is not granted now throws `ERR_ACCESS_DENIED` when the watch starts, including a `..` that follows a symbolic link. On macOS, a path below `/private/var`, `/private/tmp` or `/private/etc` is also accepted if the same path spelled with `/var`, `/tmp` or `/etc` is granted. No other symbolic link is followed outside of the granted paths, and the grants themselves are not changed. Assisted-By: OpenAI GPT-5.6 Sol Signed-off-by: Paolo Insogna --- doc/api/permissions.md | 8 + src/fs_event_wrap.cc | 104 +++++++- .../test-permission-fs-watch-resolved-path.js | 238 ++++++++++++++++++ 3 files changed, 345 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-permission-fs-watch-resolved-path.js diff --git a/doc/api/permissions.md b/doc/api/permissions.md index 2cf99bd167ab..af8a908ffb02 100644 --- a/doc/api/permissions.md +++ b/doc/api/permissions.md @@ -547,6 +547,13 @@ Developers relying on --permission to sandbox untrusted code should be aware tha permission model enabled, you must ensure that no paths to which access has been granted contain relative symbolic links. +* [`fs.watch()`][] resolves the path to its canonical form when the watch + starts, and throws `ERR_ACCESS_DENIED` if that path is not within the paths + that access has been granted to, for example when a symbolic link in a + granted directory points outside of it. On macOS, `/var`, `/tmp` and `/etc` + are treated as their `/private` counterparts; no other symbolic link is + followed outside of the granted paths. + [Security Policy]: https://github.com/nodejs/node/blob/main/SECURITY.md [`--allow-addons`]: cli.md#--allow-addons [`--allow-child-process`]: cli.md#--allow-child-process @@ -567,6 +574,7 @@ Developers relying on --permission to sandbox untrusted code should be aware tha [`--permission`]: cli.md#--permission [`--use-env-proxy`]: cli.md#--use-env-proxy [`crypto.createPrivateKey()`]: crypto.md#cryptocreateprivatekeykey +[`fs.watch()`]: fs.md#fswatchfilename-options-listener [`npx`]: https://docs.npmjs.com/cli/commands/npx [`permission.drop()`]: process.md#processpermissiondropscope-reference [`permission.has()`]: process.md#processpermissionhasscope-reference diff --git a/src/fs_event_wrap.cc b/src/fs_event_wrap.cc index ab2174bf8147..025aabc41ad5 100644 --- a/src/fs_event_wrap.cc +++ b/src/fs_event_wrap.cc @@ -24,6 +24,7 @@ #include "handle_wrap.h" #include "node.h" #include "node_external_reference.h" +#include "path.h" #include "permission/permission.h" #include "string_bytes.h" @@ -80,6 +81,14 @@ class FSEventWrap: public HandleWrap { // The path being watched, used to re-check read permission for the // descendants reported by libuv when the permission model is enabled. std::string watched_path_; + // Whether the watched path is a directory. The names reported for a watched + // file are the file itself, so they are not checked as descendants. + bool watched_is_dir_ = true; + // The path that read permission was checked on, and that the reported + // entries are checked against. It is the canonical path, or the equivalent + // form of it that goes through a system symbolic link (see + // SystemAliasForm()). + std::string check_path_; }; @@ -140,6 +149,64 @@ void FSEventWrap::New(const FunctionCallbackInfo& args) { new FSEventWrap(env, args.This()); } +namespace { + +// Returns the canonical absolute form of `path`, or just its absolute form if +// it cannot be resolved. +std::string ResolveWatchedPath(Environment* env, const char* path) { + uv_fs_t req; + int err = uv_fs_realpath(nullptr, &req, path, nullptr); + std::string resolved; + if (err == 0 && req.ptr != nullptr) { + resolved = static_cast(req.ptr); + } + uv_fs_req_cleanup(&req); + if (!resolved.empty()) return resolved; + return node::PathResolve(env, {std::string_view(path)}); +} + +#ifdef __APPLE__ +// On macOS, `/var`, `/tmp` and `/etc` are symbolic links to directories below +// `/private`. If `canonical` is below one of those directories, return the +// same path spelled with the link, which is the form a user normally grants. +// The link must really resolve to that directory. Any other symbolic link is +// not considered. +std::string SystemAliasForm(const std::string& canonical) { + static constexpr std::pair kAliases[] = { + {"/var", "/private/var"}, + {"/tmp", "/private/tmp"}, + {"/etc", "/private/etc"}, + }; + for (const auto& [alias, target] : kAliases) { + const std::string_view dir(target); + if (canonical.compare(0, dir.size(), dir) != 0) continue; + if (canonical.size() != dir.size() && canonical[dir.size()] != '/') { + continue; + } + uv_fs_t req; + bool matches = uv_fs_realpath(nullptr, &req, alias, nullptr) == 0 && + req.ptr != nullptr && + std::string_view(static_cast(req.ptr)) == dir; + uv_fs_req_cleanup(&req); + if (matches) return alias + canonical.substr(dir.size()); + } + return std::string(); +} +#endif + +bool IsDirectory(const std::string& path) { + uv_fs_t req; + int err = uv_fs_stat(nullptr, &req, path.c_str(), nullptr); + // If the path cannot be inspected, assume a directory so that the names of + // the reported entries are still checked. + bool is_dir = err != 0 || (static_cast(req.ptr)->st_mode & + S_IFMT) == S_IFDIR; + uv_fs_req_cleanup(&req); + return is_dir; +} + +} // namespace + // wrap.start(filename, persistent, recursive, encoding) void FSEventWrap::Start(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); @@ -155,7 +222,30 @@ void FSEventWrap::Start(const FunctionCallbackInfo& args) { CHECK_NOT_NULL(*path); THROW_IF_INSUFFICIENT_PERMISSIONS( env, permission::PermissionScope::kFileSystemRead, *path); - wrap->watched_path_ = *path; + // Resolve the path once. The permission check, the events and the watch + // itself all use this canonical path, so a relative path or a symbolic link + // that changes after this point has no effect. + std::string resolved = ResolveWatchedPath(env, *path); + std::string check_path = resolved; + if (env->permission()->enabled() && + !env->permission()->is_granted( + env, permission::PermissionScope::kFileSystemRead, resolved)) { +#ifdef __APPLE__ + std::string alias = SystemAliasForm(resolved); + if (!alias.empty() && + env->permission()->is_granted( + env, permission::PermissionScope::kFileSystemRead, alias)) { + check_path = std::move(alias); + } +#endif + if (check_path == resolved) { + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, permission::PermissionScope::kFileSystemRead, resolved); + } + } + wrap->check_path_ = check_path; + wrap->watched_path_ = resolved; + wrap->watched_is_dir_ = IsDirectory(resolved); unsigned int flags = 0; if (args[2]->IsTrue()) @@ -168,7 +258,8 @@ void FSEventWrap::Start(const FunctionCallbackInfo& args) { return args.GetReturnValue().Set(err); } - err = uv_fs_event_start(&wrap->handle_, OnEvent, *path, flags); + err = uv_fs_event_start( + &wrap->handle_, OnEvent, wrap->watched_path_.c_str(), flags); wrap->MarkAsInitialized(); if (err != 0) { @@ -227,9 +318,12 @@ void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, // descendants that fall outside the granted read scope (for example a nested // path under an exact, non-wildcard grant). Do not leak those names; report // the event without a filename instead. - if (filename != nullptr && env->permission()->enabled()) { - std::string full_path = wrap->watched_path_; - full_path += kPathSeparator; + if (filename != nullptr && wrap->watched_is_dir_ && + env->permission()->enabled()) { + std::string full_path = wrap->check_path_; + if (full_path.empty() || full_path.back() != kPathSeparator) { + full_path += kPathSeparator; + } full_path += filename; if (!env->permission()->is_granted( env, permission::PermissionScope::kFileSystemRead, full_path)) { diff --git a/test/parallel/test-permission-fs-watch-resolved-path.js b/test/parallel/test-permission-fs-watch-resolved-path.js new file mode 100644 index 000000000000..0b903512f44b --- /dev/null +++ b/test/parallel/test-permission-fs-watch-resolved-path.js @@ -0,0 +1,238 @@ +'use strict'; + +// fs.watch() resolves the watched path once, when the watch starts. The read +// scope is checked against that canonical path, and so are the entries that +// are reported afterwards. + +const common = require('../common'); + +if (!common.hasCrypto) + common.skip('no crypto'); + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const { spawn } = require('child_process'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +// Runs `script` in a child with the permission model enabled. The script +// prints `READY` when the parent has to trigger the change, and prints a +// final line starting with `RESULT:`. +function run({ grants, script, cwd, trigger }) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [ + '--permission', + ...grants, + '-e', + script, + ], { encoding: 'utf8', cwd }); + + let stdout = ''; + let stderr = ''; + let triggered = false; + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.stdout.on('data', (chunk) => { + stdout += chunk; + if (!triggered && trigger && stdout.includes('READY\n')) { + triggered = true; + trigger(); + } + }); + child.on('close', (code) => { + if (code !== 0) return reject(new Error(`${stderr}\n${stdout}`)); + const line = stdout.split('\n').find((l) => l.startsWith('RESULT:')); + if (line === undefined) return reject(new Error(stdout)); + resolve(JSON.parse(line.slice('RESULT:'.length))); + }); + }); +} + +// The names of the entries are checked against the watched directory, even if +// the working directory changes after the watch started. `watched` does not +// exist when the permissions are applied, so its grant is exact and the +// entries inside it are not readable. +async function testChdir() { + const base = tmpdir.resolve('cwd'); + const watched = path.join(base, 'watched'); + const other = path.join(base, 'other'); + fs.mkdirSync(other, { recursive: true }); + + const result = await run({ + cwd: base, + grants: [ + `--allow-fs-read=${watched}`, + `--allow-fs-write=${watched}`, + `--allow-fs-read=${other}`, + ], + script: ` + const fs = require('fs'); + fs.mkdirSync('watched'); + const w = fs.watch('watched', (event, filename) => { + w.close(); + process.stdout.write('RESULT:' + JSON.stringify(filename) + '\\n'); + }); + process.chdir(${JSON.stringify(other)}); + process.stdout.write('READY\\n'); + `, + trigger() { + fs.writeFileSync(path.join(watched, 'file.txt'), 'x'); + }, + }); + assert.strictEqual(result, null); +} + +// Watching a single file works, and reports the name of the file. +async function testFile() { + const base = tmpdir.resolve('file'); + const file = path.join(base, 'file.txt'); + fs.mkdirSync(base); + fs.writeFileSync(file, 'x'); + + const result = await run({ + grants: [`--allow-fs-read=${file}`], + script: ` + const fs = require('fs'); + const w = fs.watch(${JSON.stringify(file)}, (event, filename) => { + w.close(); + process.stdout.write('RESULT:' + JSON.stringify(filename) + '\\n'); + }); + process.stdout.write('READY\\n'); + `, + trigger() { + fs.writeFileSync(file, 'y'); + }, + }); + assert.strictEqual(result, 'file.txt'); +} + +// A symbolic link in a granted directory that points outside of it is denied +// when the watch starts, both for fs.watch() and fs.promises.watch(). +async function testOutsideLink() { + const base = tmpdir.resolve('link'); + const granted = path.join(base, 'granted'); + const outside = path.join(base, 'outside'); + const link = path.join(granted, 'link'); + fs.mkdirSync(granted, { recursive: true }); + fs.mkdirSync(outside); + // A junction is used so that this also works on Windows. + fs.symlinkSync(outside, link, 'junction'); + + const result = await run({ + grants: [`--allow-fs-read=${granted}`], + script: ` + const fs = require('fs'); + const codes = []; + try { + fs.watch(${JSON.stringify(link)}).close(); + } catch (e) { + codes.push(e.code); + } + (async () => { + const ac = new AbortController(); + const iterator = fs.promises.watch(${JSON.stringify(link)}, { + signal: ac.signal, + }); + const next = iterator.next(); + ac.abort(); + try { + await next; + } catch (e) { + codes.push(e.code); + } + process.stdout.write('RESULT:' + JSON.stringify(codes) + '\\n'); + })(); + `, + }); + assert.deepStrictEqual(result, ['ERR_ACCESS_DENIED', 'ERR_ACCESS_DENIED']); +} + +// A symbolic link that resolves inside the granted scope is accepted. +async function testInsideLink() { + const base = tmpdir.resolve('inside'); + const target = path.join(base, 'target'); + const link = path.join(base, 'link'); + fs.mkdirSync(target, { recursive: true }); + fs.symlinkSync(target, link, 'junction'); + + const result = await run({ + grants: [`--allow-fs-read=${base}`], + script: ` + const fs = require('fs'); + const w = fs.watch(${JSON.stringify(link)}, (event, filename) => { + w.close(); + process.stdout.write('RESULT:' + JSON.stringify(filename) + '\\n'); + }); + process.stdout.write('READY\\n'); + `, + trigger() { + fs.writeFileSync(path.join(target, 'file.txt'), 'x'); + }, + }); + assert.strictEqual(result, 'file.txt'); +} + +// A granted path that goes through a symbolic link chosen by the user is not +// followed outside of the granted scope. +async function testUserAliasDenied() { + const base = tmpdir.resolve('alias'); + const real = path.join(base, 'real'); + const alias = path.join(base, 'alias'); + const granted = path.join(alias, 'dir'); + fs.mkdirSync(path.join(real, 'dir'), { recursive: true }); + fs.symlinkSync(real, alias, 'junction'); + + const result = await run({ + grants: [`--allow-fs-read=${granted}`], + script: ` + const fs = require('fs'); + try { + fs.watch(${JSON.stringify(granted)}).close(); + process.stdout.write('RESULT:null\\n'); + } catch (e) { + process.stdout.write('RESULT:' + JSON.stringify(e.code) + '\\n'); + } + `, + }); + assert.strictEqual(result, 'ERR_ACCESS_DENIED'); +} + +// A `..` that follows a symbolic link is resolved by the operating system, so +// the path must be checked after the link is followed. +async function testDotDotThroughLink() { + const base = tmpdir.resolve('dotdot'); + const granted = path.join(base, 'granted'); + const outside = path.join(base, 'outside'); + const link = path.join(granted, 'link'); + fs.mkdirSync(granted, { recursive: true }); + fs.mkdirSync(path.join(outside, 'sub'), { recursive: true }); + fs.mkdirSync(path.join(outside, 'y')); + fs.mkdirSync(path.join(granted, 'y')); + fs.symlinkSync(path.join(outside, 'sub'), link, 'junction'); + + const result = await run({ + grants: [`--allow-fs-read=${granted}`], + script: ` + const fs = require('fs'); + try { + fs.watch(${JSON.stringify(link)} + '/../y').close(); + process.stdout.write('RESULT:null\\n'); + } catch (e) { + process.stdout.write('RESULT:' + JSON.stringify(e.code) + '\\n'); + } + `, + }); + assert.strictEqual(result, 'ERR_ACCESS_DENIED'); +} + +(async () => { + await testChdir(); + await testFile(); + await testOutsideLink(); + await testInsideLink(); + await testUserAliasDenied(); + await testDotDotThroughLink(); +})().then(common.mustCall());