Skip to content

Commit c554efa

Browse files
committed
fs: check every path in recursive operations
When the permission model is enabled, fs.cpSync() now uses the per-entry JavaScript copy path instead of the native recursive copy, so every source and destination path is checked, matching fs.cp(). Recursive fs.rmSync() now checks every descendant before removing the tree, and denies the removal if the tree cannot be fully walked. Recursive fs.mkdir(), fs.mkdirSync() and fs.promises.mkdir() check each missing parent directory before creating it. Assisted-By: OpenAI GPT-6 Sol <openai/gpt-6-sol> Signed-off-by: Paolo Insogna <paolo@cowtech.it>
1 parent d4318d9 commit c554efa

5 files changed

Lines changed: 346 additions & 3 deletions

File tree

‎lib/internal/fs/cp/cp-sync.js‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ const {
3737
resolve,
3838
} = require('path');
3939
const { isPromise } = require('util/types');
40+
const permission = require('internal/process/permission');
4041

4142
function cpSyncFn(src, dest, opts) {
4243
// Warn about using preserveTimestamps on 32-bit node
@@ -147,9 +148,8 @@ function onDir(srcStat, destStat, src, dest, opts) {
147148
}
148149

149150
function copyDir(src, dest, opts, mkDir, srcMode) {
150-
if (!opts.filter) {
151-
// The caller didn't provide a js filter function, in this case
152-
// we can run the whole function faster in C++
151+
if (!opts.filter && !permission.isEnabled()) {
152+
// Without a filter or per-entry permission checks, copy in C++.
153153
// TODO(dario-piotrowicz): look into making cpSyncCopyDir also accept the potential filter function
154154
return fsBinding.cpSyncCopyDir(src, dest,
155155
opts.force,

‎src/node_file.cc‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1834,6 +1834,33 @@ static void ClearReadOnlyAttributeW(const std::filesystem::path& path,
18341834
}
18351835
#endif
18361836

1837+
static std::optional<std::string> DeniedRmPath(
1838+
Environment* env, const std::filesystem::path& path) {
1839+
std::error_code error;
1840+
std::filesystem::recursive_directory_iterator it(path, error), end;
1841+
if (error == std::errc::no_such_file_or_directory) {
1842+
return std::nullopt;
1843+
}
1844+
if (error) {
1845+
return ConvertPathToUTF8(path);
1846+
}
1847+
1848+
while (it != end) {
1849+
std::string entry = ConvertPathToUTF8(it->path());
1850+
if (!env->permission()->is_granted(
1851+
env, permission::PermissionScope::kFileSystemWrite, entry) &&
1852+
!env->permission()->warning_only()) {
1853+
return entry;
1854+
}
1855+
it.increment(error);
1856+
if (error) {
1857+
// Do not remove entries when traversal did not reach the end.
1858+
return ConvertPathToUTF8(path);
1859+
}
1860+
}
1861+
return std::nullopt;
1862+
}
1863+
18371864
static void RmSync(const FunctionCallbackInfo<Value>& args) {
18381865
Environment* env = Environment::GetCurrent(args);
18391866
Isolate* isolate = env->isolate();
@@ -1857,6 +1884,17 @@ static void RmSync(const FunctionCallbackInfo<Value>& args) {
18571884
int recursive = args[2]->IsTrue();
18581885
int retryDelay = args[3].As<Int32>()->Value();
18591886

1887+
if (recursive &&
1888+
file_status.type() == std::filesystem::file_type::directory &&
1889+
env->permission()->enabled()) {
1890+
// Check the whole tree before remove_all can remove any of its entries.
1891+
if (auto denied = DeniedRmPath(env, file_path)) {
1892+
permission::Permission::ThrowAccessDenied(
1893+
env, permission::PermissionScope::kFileSystemWrite, *denied);
1894+
return;
1895+
}
1896+
}
1897+
18601898
// File is a directory and recursive is false
18611899
if (file_status.type() == std::filesystem::file_type::directory &&
18621900
!recursive) {
@@ -1965,6 +2003,31 @@ static void RmSync(const FunctionCallbackInfo<Value>& args) {
19652003
UV_UNKNOWN, "rm", message.c_str(), path_c_str);
19662004
}
19672005

2006+
static std::optional<std::string> DeniedMkdirpPath(Environment* env,
2007+
std::filesystem::path path) {
2008+
path = path.parent_path();
2009+
while (!path.empty()) {
2010+
std::error_code error;
2011+
if (std::filesystem::symlink_status(path, error).type() !=
2012+
std::filesystem::file_type::not_found) {
2013+
break;
2014+
}
2015+
2016+
std::string component = ConvertPathToUTF8(path);
2017+
if (!env->permission()->is_granted(
2018+
env, permission::PermissionScope::kFileSystemWrite, component) &&
2019+
!env->permission()->warning_only()) {
2020+
return component;
2021+
}
2022+
auto parent = path.parent_path();
2023+
if (parent == path) {
2024+
break;
2025+
}
2026+
path = std::move(parent);
2027+
}
2028+
return std::nullopt;
2029+
}
2030+
19682031
int MKDirpSync(uv_loop_t* loop,
19692032
uv_fs_t* req,
19702033
const std::string& path,
@@ -2168,6 +2231,16 @@ static void MKDir(const FunctionCallbackInfo<Value>& args) {
21682231
req_wrap_async,
21692232
permission::PermissionScope::kFileSystemWrite,
21702233
path.ToStringView());
2234+
if (mkdirp && env->permission()->enabled()) {
2235+
if (auto denied = DeniedMkdirpPath(env, path.ToPath())) {
2236+
permission::Permission::AsyncThrowAccessDenied(
2237+
env,
2238+
req_wrap_async,
2239+
permission::PermissionScope::kFileSystemWrite,
2240+
*denied);
2241+
return;
2242+
}
2243+
}
21712244
FS_ASYNC_TRACE_BEGIN1(
21722245
UV_FS_UNLINK, req_wrap_async, "path", TRACE_STR_COPY(*path))
21732246
AsyncCall(env,
@@ -2184,6 +2257,13 @@ static void MKDir(const FunctionCallbackInfo<Value>& args) {
21842257
env,
21852258
permission::PermissionScope::kFileSystemWrite,
21862259
path.ToStringView());
2260+
if (mkdirp && env->permission()->enabled()) {
2261+
if (auto denied = DeniedMkdirpPath(env, path.ToPath())) {
2262+
permission::Permission::ThrowAccessDenied(
2263+
env, permission::PermissionScope::kFileSystemWrite, *denied);
2264+
return;
2265+
}
2266+
}
21872267
FSReqWrapSync req_wrap_sync("mkdir", *path);
21882268
FS_SYNC_TRACE_BEGIN(mkdir);
21892269
if (mkdirp) {
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('node:assert');
5+
const fs = require('node:fs');
6+
const path = require('node:path');
7+
const { spawnSyncAndExitWithoutError } = require('../common/child_process');
8+
const tmpdir = require('../common/tmpdir');
9+
10+
tmpdir.refresh();
11+
12+
const source = tmpdir.resolve('source');
13+
fs.mkdirSync(source);
14+
fs.writeFileSync(path.join(source, 'file'), 'content');
15+
16+
function run(src, dest, read, write, script, late = false) {
17+
spawnSyncAndExitWithoutError(process.execPath, [
18+
'--permission',
19+
`--allow-fs-read=${read}`,
20+
`--allow-fs-read=${dest}/*`,
21+
...write.split(',').map((grant) => `--allow-fs-write=${grant}`),
22+
'-e', script,
23+
JSON.stringify([src, dest]),
24+
String(late),
25+
]);
26+
}
27+
28+
const copy = `
29+
const assert = require('node:assert');
30+
const fs = require('node:fs');
31+
const path = require('node:path');
32+
const [src, dest] = JSON.parse(process.argv[1]);
33+
if (process.argv[2] === 'true') {
34+
fs.mkdirSync(src);
35+
fs.writeFileSync(path.join(src, 'file'), 'content');
36+
}
37+
assert.throws(() => fs.cpSync(src, dest, { recursive: true }), {
38+
code: 'ERR_ACCESS_DENIED',
39+
});
40+
`;
41+
42+
const exactDest = tmpdir.resolve('exact-dest');
43+
run(source, exactDest, `${source}/*`, exactDest, copy);
44+
assert.strictEqual(fs.existsSync(path.join(exactDest, 'file')), false);
45+
46+
const lateSource = tmpdir.resolve('late-source');
47+
const lateDest = tmpdir.resolve('late-dest');
48+
run(lateSource, lateDest, lateSource, `${lateSource}/*,${lateDest}/*`, copy, true);
49+
assert.strictEqual(fs.existsSync(path.join(lateDest, 'file')), false);
50+
51+
const allowedDest = tmpdir.resolve('allowed-dest');
52+
run(source, allowedDest, `${source}/*`, `${allowedDest}/*`, `
53+
const assert = require('node:assert');
54+
const fs = require('node:fs');
55+
const path = require('node:path');
56+
const [src, dest] = JSON.parse(process.argv[1]);
57+
fs.cpSync(src, dest, { recursive: true });
58+
assert.strictEqual(fs.readFileSync(path.join(dest, 'file'), 'utf8'), 'content');
59+
`);
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('node:assert');
5+
const fs = require('node:fs');
6+
const path = require('node:path');
7+
const { spawnSyncAndExitWithoutError } = require('../common/child_process');
8+
const tmpdir = require('../common/tmpdir');
9+
10+
tmpdir.refresh();
11+
12+
for (const method of ['sync', 'callback', 'promises']) {
13+
const ancestor = tmpdir.resolve(method);
14+
const leaf = path.join(ancestor, 'nested', 'leaf');
15+
const script = `
16+
const assert = require('node:assert');
17+
const fs = require('node:fs');
18+
const path = require('node:path');
19+
const [leaf, allowed] = JSON.parse(process.argv[1]);
20+
const ancestor = path.dirname(path.dirname(leaf));
21+
async function create() {
22+
if (${JSON.stringify(method)} === 'sync') {
23+
return fs.mkdirSync(leaf, { recursive: true });
24+
}
25+
if (${JSON.stringify(method)} === 'callback') {
26+
return new Promise((resolve, reject) => {
27+
fs.mkdir(leaf, { recursive: true }, (err) => err ? reject(err) : resolve());
28+
});
29+
}
30+
return fs.promises.mkdir(leaf, { recursive: true });
31+
}
32+
(async () => {
33+
if (allowed) {
34+
await create();
35+
assert.strictEqual(fs.statSync(leaf).isDirectory(), true);
36+
} else {
37+
await assert.rejects(create, { code: 'ERR_ACCESS_DENIED' });
38+
assert.strictEqual(fs.existsSync(ancestor), false);
39+
}
40+
})().then(() => process.exitCode ??= 0);
41+
`;
42+
43+
spawnSyncAndExitWithoutError(process.execPath, [
44+
'--permission', '--allow-fs-read=*', `--allow-fs-write=${leaf}`,
45+
'-e', script, JSON.stringify([leaf, false]),
46+
]);
47+
assert.strictEqual(fs.existsSync(ancestor), false);
48+
49+
spawnSyncAndExitWithoutError(process.execPath, [
50+
'--permission', '--allow-fs-read=*', `--allow-fs-write=${ancestor}/*`,
51+
'-e', script, JSON.stringify([leaf, true]),
52+
]);
53+
assert.strictEqual(fs.statSync(leaf).isDirectory(), true);
54+
}
55+
56+
const granted = tmpdir.resolve('relative');
57+
fs.mkdirSync(granted);
58+
spawnSyncAndExitWithoutError(process.execPath, [
59+
'--permission', '--allow-fs-read=*', `--allow-fs-write=${granted}/*`,
60+
'-e', `
61+
const fs = require('node:fs');
62+
process.chdir(process.argv[1]);
63+
fs.mkdirSync('a/b', { recursive: true });
64+
fs.promises.mkdir('c/d/e', { recursive: true });
65+
`, granted,
66+
]);
67+
assert.strictEqual(fs.statSync(path.join(granted, 'a/b')).isDirectory(), true);
68+
assert.strictEqual(fs.statSync(path.join(granted, 'c/d/e')).isDirectory(), true);
69+
70+
const exact = tmpdir.resolve('relative-exact');
71+
fs.mkdirSync(exact);
72+
spawnSyncAndExitWithoutError(process.execPath, [
73+
'--permission', '--allow-fs-read=*',
74+
`--allow-fs-write=${path.join(exact, 'a/b')}`,
75+
'-e', `
76+
const assert = require('node:assert');
77+
const fs = require('node:fs');
78+
process.chdir(process.argv[1]);
79+
assert.throws(() => fs.mkdirSync('a/b', { recursive: true }), {
80+
code: 'ERR_ACCESS_DENIED',
81+
});
82+
`, exact,
83+
]);
84+
assert.strictEqual(fs.existsSync(path.join(exact, 'a')), false);

0 commit comments

Comments
 (0)