Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,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);
Expand Down Expand Up @@ -2966,7 +2966,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);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/fs/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -2261,7 +2261,7 @@ function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
resolve();
}
};
const accessError = job.run(path);
const accessError = job.run();
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
Expand Down Expand Up @@ -2339,7 +2339,7 @@ function readFileInOneRoundTrip(path, flagsNumber) {
resolve([buffer, fd, size]);
}
};
const accessError = job.run(path);
const accessError = job.run();
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, readFileInOneRoundTrip);
reject(accessError);
Expand Down
47 changes: 30 additions & 17 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3589,10 +3589,12 @@ static void ReadFileUtf8(const FunctionCallbackInfo<Value>& args) {
// contention when many files are read at once. Files whose size exceeds
// `limit` 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 for large files); it then only saved the fstat() round trip.
// abortable for large files); it then only saved the fstat() round trip. A
// 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`: caller owns fd now (it is
Expand Down Expand Up @@ -3630,11 +3632,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;
}
Expand Down Expand Up @@ -3672,7 +3672,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
// (/dev/zero and friends have no EOF and this memory is not V8 heap).
size_t cap = size > 0 ? static_cast<size_t>(size) : kUnknownSizeChunk;
data_ = UncheckedMalloc<char>(cap);
if (data_ == nullptr) {
Expand All @@ -3684,8 +3685,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);
Expand Down Expand Up @@ -3780,6 +3793,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,
Expand All @@ -3803,9 +3817,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 {};
Expand All @@ -3814,7 +3831,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()) {
Expand Down Expand Up @@ -3868,7 +3884,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 {
Expand Down Expand Up @@ -3898,11 +3914,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;
Expand Down
89 changes: 89 additions & 0 deletions test/parallel/test-permission-fs-one-round-trip-path.js
Original file line number Diff line number Diff line change
@@ -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');
Loading