Commit ec0dbaab8f5 for nodejs
commit ec0dbaab8f57e87d5e0500d7a96d729ca50dc0cf
Author: Mohamed Sayed <k@3zrv.com>
Date: Thu Oct 29 19:07:27 2026 +0300
fs: harden the one-round-trip read and write jobs
Signed-off-by: Mohamed Sayed <k@3zrv.com>
Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/67112
diff --git a/lib/fs.js b/lib/fs.js
index 71ccb1d2cec..5150801dc8c 100644
--- a/lib/fs.js
+++ b/lib/fs.js
@@ -455,7 +455,7 @@ function readFile(path, options, callback) {
const job = new ReadFileJob(path, flagsNumber, kReadFileBufferLength, true);
job.context = context;
job.ondone = readFileAfterOneShot;
- const accessError = job.run(path);
+ const accessError = job.run();
if (accessError !== undefined) {
// Not scheduled: report it the way the request-based open() did.
callback(accessError);
@@ -2969,7 +2969,7 @@ function writeFile(path, data, options, callback) {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
- const accessError = job.run(path);
+ const accessError = job.run();
if (accessError !== undefined) {
callback(accessError);
}
diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js
index 53eb2f4938d..a5fa59e557b 100644
--- a/lib/internal/fs/promises.js
+++ b/lib/internal/fs/promises.js
@@ -2282,7 +2282,7 @@ function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
}
};
});
- const accessError = job.run(path);
+ const accessError = job.run();
if (accessError !== undefined) {
throw accessError;
}
@@ -2371,7 +2371,7 @@ function readFileInOneRoundTrip(path, flagsNumber) {
}
};
});
- const accessError = job.run(path);
+ const accessError = job.run();
if (accessError !== undefined) {
throw accessError;
}
diff --git a/src/node_file.cc b/src/node_file.cc
index 048d106227c..4354ecc677c 100644
--- a/src/node_file.cc
+++ b/src/node_file.cc
@@ -3600,10 +3600,12 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
// `limit`, and files that are not regular files (a FIFO or a device may never
// reach EOF), are not read here: the job hands the open fd and the size back
// so that the caller continues with the chunked reader (which stays fair and
-// abortable between chunks); it then only saved the fstat() round trip.
+// abortable between chunks); it then only saved the fstat() round trip. A
+// regular file that reports size 0 but yields more than 2 GiB is handed back
+// the same way, with size = the bytes read so far (the data is dropped).
//
// JS: const job = new ReadFileJob(path, flags, limit, trackFd);
-// job.ondone = (err, buffer, fd, size, closeErr) => {...}; job.run(path);
+// job.ondone = (err, buffer, fd, size, closeErr) => {...}; job.run();
// Exactly one of these outcomes is reported:
// err -- open/fstat/read failed (any fd opened here was closed);
// fd >= 0, size -- file is larger than `limit`, or not a regular file and
@@ -3641,11 +3643,9 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
- BufferValue path(env->isolate(), args[0]);
- CHECK_NOT_NULL(*path);
- ToNamespacedPath(env, &path);
Local<Value> access_error;
- if (OpenPermissionError(env, path, job->flags_).ToLocal(&access_error)) {
+ if (OpenPermissionError(env, job->path_, job->flags_)
+ .ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
@@ -3684,7 +3684,8 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
// Known size: read exactly that much (like the chunked reader, stop when
// it has been read or at EOF, whichever comes first). Unknown size (0,
- // e.g. procfs): grow until EOF.
+ // e.g. procfs): grow until EOF, but never past kMaxUnknownSizeRead bytes
+ // (this memory is not V8 heap).
size_t cap = size > 0 ? static_cast<size_t>(size) : kUnknownSizeChunk;
data_ = UncheckedMalloc<char>(cap);
if (data_ == nullptr) {
@@ -3696,8 +3697,20 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
if (len_ == cap) {
if (size > 0) break; // Read all of the announced size.
// A file that claims size 0 keeps growing until EOF (or ENOMEM),
- // like the chunked reader's buffer list did.
- size_t new_cap = cap * 2;
+ // like the chunked reader's buffer list did, up to the 2 GiB that
+ // fs.readFile() accepts for any file (kIoMaxLength in
+ // lib/internal/fs/utils.js). Past that, give the fd back with a size
+ // above that limit so the caller fails with ERR_FS_FILE_TOO_LARGE and
+ // closes it, exactly as for a regular file that large.
+ if (cap > kMaxUnknownSizeRead) {
+ free(data_);
+ data_ = nullptr;
+ fd_ = fd;
+ size_ = len_;
+ len_ = 0;
+ return;
+ }
+ size_t new_cap = std::min(cap * 2, kMaxUnknownSizeRead + 1);
char* grown = UncheckedRealloc<char>(data_, new_cap);
if (grown == nullptr) {
Fail("read", UV_ENOMEM);
@@ -3792,6 +3805,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
+ static constexpr size_t kMaxUnknownSizeRead = 0x7fffffff;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;
ReadFileJob(Environment* env,
@@ -3815,9 +3829,12 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
}
// The permission checks AsyncCheckOpenPermissions() performs for open(),
- // producing the error object instead of rejecting a request wrap.
+ // producing the error object instead of rejecting a request wrap. The path
+ // is the one the job stored at construction, not a value re-read from JS at
+ // schedule time, so the check cannot be steered to a different path than the
+ // one the thread pool opens.
static MaybeLocal<Value> OpenPermissionError(Environment* env,
- const BufferValue& path,
+ std::string_view path_view,
int flags) {
if (!env->permission()->enabled()) [[likely]]
return {};
@@ -3826,7 +3843,6 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
const int write_as_side_effect =
flags &
(UV_FS_O_APPEND | UV_FS_O_CREAT | UV_FS_O_TRUNC | UV_FS_O_TEMPORARY);
- const auto path_view = path.ToStringView();
auto denied = [&](permission::PermissionScope scope) -> MaybeLocal<Value> {
if (env->permission()->is_granted(env, scope, path_view) ||
env->permission()->warning_only()) {
@@ -3880,7 +3896,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
-// job.ondone = (err) => {...}; job.run(path);
+// job.ondone = (err) => {...}; job.run();
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
@@ -3910,11 +3926,8 @@ class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
- BufferValue path(env->isolate(), args[0]);
- CHECK_NOT_NULL(*path);
- ToNamespacedPath(env, &path);
Local<Value> access_error;
- if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
+ if (ReadFileJob::OpenPermissionError(env, job->path_, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
diff --git a/test/parallel/test-permission-fs-one-round-trip-path.js b/test/parallel/test-permission-fs-one-round-trip-path.js
new file mode 100644
index 00000000000..6dc73b956c7
--- /dev/null
+++ b/test/parallel/test-permission-fs-one-round-trip-path.js
@@ -0,0 +1,89 @@
+'use strict';
+
+// fs.readFile() and fs.writeFile() with a path open the file in a single
+// thread pool job. The permission check must apply to the path the job opens,
+// even when a Buffer path is changed after the job has been created.
+
+require('../common');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const { spawnSyncAndExitWithoutError } = require('../common/child_process');
+const tmpdir = require('../common/tmpdir');
+
+tmpdir.refresh();
+const allowedRead = tmpdir.resolve('public-read');
+const deniedRead = tmpdir.resolve('secret-read');
+const allowedWrite = tmpdir.resolve('public-write');
+const deniedWrite = tmpdir.resolve('secret-write');
+fs.writeFileSync(allowedRead, 'public');
+fs.writeFileSync(deniedRead, 'secret');
+fs.writeFileSync(allowedWrite, 'public');
+// The swapped path must fit into the Buffer that held the denied path.
+assert.strictEqual(Buffer.byteLength(allowedRead), Buffer.byteLength(deniedRead));
+assert.strictEqual(Buffer.byteLength(allowedWrite), Buffer.byteLength(deniedWrite));
+
+const script = `
+const assert = require('node:assert');
+const fs = require('node:fs');
+
+// Starts an operation on a denied Buffer path. A setter on Object.prototype
+// runs when the operation assigns its completion callback, and rewrites the
+// path to an allowed one.
+function startWithSwappedPath(denied, allowed, start) {
+ const path = Buffer.from(denied);
+ let swaps = 0;
+ Object.defineProperty(Object.prototype, 'ondone', {
+ __proto__: null,
+ configurable: true,
+ set(value) {
+ swaps++;
+ Buffer.from(allowed).copy(path);
+ Object.defineProperty(this, 'ondone', {
+ __proto__: null, value, writable: true, configurable: true,
+ });
+ },
+ });
+ try {
+ return start(path);
+ } finally {
+ delete Object.prototype.ondone;
+ assert.strictEqual(swaps, 1);
+ }
+}
+
+function callbackResult(fn, path, ...args) {
+ return new Promise((resolve, reject) => {
+ fn(path, ...args, (err, result) => (err ? reject(err) : resolve(result)));
+ });
+}
+
+const read = { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemRead' };
+const write = { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite' };
+const data = Buffer.from('written');
+const [allowedRead, deniedRead, allowedWrite, deniedWrite] = ${
+ JSON.stringify([allowedRead, deniedRead, allowedWrite, deniedWrite])};
+
+(async () => {
+ await assert.rejects(startWithSwappedPath(
+ deniedRead, allowedRead, (path) => callbackResult(fs.readFile, path)), read);
+ await assert.rejects(startWithSwappedPath(
+ deniedRead, allowedRead, (path) => fs.promises.readFile(path)), read);
+ await assert.rejects(startWithSwappedPath(
+ deniedWrite, allowedWrite, (path) => callbackResult(fs.writeFile, path, data)), write);
+ await assert.rejects(startWithSwappedPath(
+ deniedWrite, allowedWrite, (path) => fs.promises.writeFile(path, data)), write);
+ // The allowed paths still work.
+ assert.strictEqual(await fs.promises.readFile(allowedRead, 'utf8'), 'public');
+ await fs.promises.writeFile(allowedWrite, data);
+})().then(() => process.exitCode ??= 0);
+`;
+
+spawnSyncAndExitWithoutError(process.execPath, [
+ '--permission',
+ `--allow-fs-read=${allowedRead}`,
+ `--allow-fs-write=${allowedWrite}`,
+ '-e', script,
+]);
+
+assert.strictEqual(fs.existsSync(deniedWrite), false);
+assert.strictEqual(fs.readFileSync(allowedWrite, 'utf8'), 'written');