Upstream commits
Node.js®
nodejs/node
Fixes for crashes, overflows and missing input validation in fs, vfs, QUIC and FFI, 32-bit Blob size truncation, and test suite deflaking.
35 commits
-
fs: use correct position when retrying writevwritevAll() tracks the position for the next attempt in its `pos` argument, but calls fs.writev() with `this.pos`. WriteStream._writev() advances `this.pos` by the whole batch right after starting the write, so a retry from the asynchronous callback resumes at the end of the batch instead of after the bytes that reached the file. A partial write leaves a hole and puts the remainder past its place; an EAGAIN retry moves forward even though nothing was written. Use the local `pos`, as writeAll() already does.
-
test: deflake test-tls-resume-servernameThe PSK server's pskCallback answered every identity, but OpenSSL also asks it about the resumption ticket, cut at its first NUL byte. When that prefix is valid UTF-8, about 1% of the time, the ticket was taken for an external PSK and the handshake failed with decrypt_error. Only answer for the identity the client sends.
-
test: deflake test-fs-stat-cancel-inflight under FIPSThe pbkdf2() call that keeps the only threadpool worker busy used a 6-byte password and a 4-byte salt. OpenSSL 4 FIPS rejects those, so the derivation failed at once and freed the worker. The queued stat could then start before req.cancel() ran, and it completed without ECANCELED. Use inputs that meet the FIPS minimums and check that the derivation succeeds.
-
stream: close Utf8Stream fd after pending writedestroy() fsynced and closed the fd right away, even while an fs.write() on it was still running on the thread pool. The write then failed with EBADF, emitted as an 'error' that crashed the process when nothing listened for it, or landed in whatever file reused the fd number. Close the fd once the in-flight write completes, as fs.WriteStream does. Data buffered behind it is still dropped, so 'finish' is not emitted in that case.
-
fs: keep readFile abortable on non-regular files`ReadFileJob` treats a file that is not a regular file as size 0 and reads it to EOF inside one thread pool job, so the `AbortSignal` is only checked once the job ends. `fs.readFile()` and `fs.promises.readFile()` on a FIFO whose writer stays open therefore do not settle until the writer closes, and on `/dev/zero` they keep growing the buffer until the process runs out of memory. Hand the fd back to the chunked reader for non-regular files, the path files larger than one chunk already take. It checks the signal before each read. Regular files that report size 0, such as procfs files, are still read in one job.
-
watch: track all dependencies of an ownerfilterFile() reads #ownerDependencies with the dependency path, but writes the set back keyed by the owner, so each call starts a fresh set and overwrites the previous one. An owner keeps only the last dependency registered for it. unfilterFilesOwnedBy() walks that set to release an owner's dependencies, so every other one stays in #filteredFiles and #dependencyOwners. Under `node --test --watch` a restart re-reports the modules the test still loads, which hides it for those, but a dependency it stopped requiring is never reported again and keeps re-running the test. Read #ownerDependencies with the key it is written with, and collapse the repeated #dependencyOwners lookup in the loop, which now runs once per dependency rather than once per owner.
-
test: deflake test-worker-message-port-transfer-filehandle-fd0The child closed stdin and expected the next open() to return fd 0, but another thread can open a descriptor in between and take it. Pass the file to the child as stdin and wrap fd 0 in a FileHandle, so it is open from the start. After the transfer is discarded, accept an fd 0 that was reused for another file.
-
test: add test for concurrent first use of OpenSSLOpenSSL 3 builds its table of algorithm names on first use. When 43d3fe95581 moved that first use after other threads had started, an RSA-PSS key decoded while the table was being built could fail with `ERR_OSSL_EVP_DECODE_ERROR`, and every later RSA-PSS decode in the process failed too. #66903 reverted that change. The new test fails if it comes back: Workers decode an RSA-PSS certificate while the root certificate loader or a thread pool crypto job uses OpenSSL for the first time. It is based on a reproduction by Filip Skokan in #66903.
-
fs: fix readFileSync utf8 overflow on short reads`ReadFileUtf8()` appends reads shorter than 8 KiB to a string and only moves to a heap buffer at the first full 8 KiB read. That buffer always started at 64 KiB, but a pipe can deliver more than that in short reads first, so copying the string into it overflowed the heap. With `big_len` past `big_cap`, the next read size also underflowed. Size the heap buffer to at least what was already read. When that is more than 64 KiB, the buffer is full and the existing growth step enlarges it before the next read.
-
vfs: fix readlink, realpath and mkdtemp encodingOn a mounted VFS, `readlink()`, `realpath()` and `mkdtemp()` only returned a Buffer for `{ encoding: 'buffer' }`. The string form `'buffer'`, any other encoding, and a Buffer `mkdtemp()` prefix were ignored. The `VirtualFileSystem` `readlink` and `realpath` methods ignored the encoding with `MemoryProvider` and passed it on to `RealFSProvider`, which threw `ERR_INVALID_ARG_TYPE` for `'buffer'`, while for other encodings `realpath()` failed and `readlink()` returned the host path of absolute targets. Get these paths from the provider as strings and apply the encoding to the result, normalizing the options with `getOptions()` and converting with `encodeRealpathResult()` as `fs` does. The latter moves to `internal/fs/utils` so the VFS can use it.
-
src: avoid truncating Blob sizes to 32 bitsBlob sizes cross between C++ and JavaScript as uint32 values, while the underlying DataQueue tracks them as uint64. openAsBlob() on a 5 GiB file therefore returned a Blob of size 1073741824. Reporting the real size is not enough on its own. The inbound direction assumes a uint32 as well, so a correct size reaches CHECK(IsUint32()) in ToSlice() and StoreDataObject() and aborts blob.slice() and URL.createObjectURL(). Pass the sizes as doubles and keep them as uint64_t in C++. Everything below this boundary is already 64-bit, so this only stops the narrowing at the edge.
-
quic: validate session close error codes`session.close()` and `session.destroy()` only checked that `options.code` was a bigint or a number. Numbers were then converted to `uint64_t` unchecked, so fractions were truncated and negative, non-finite or too large values were undefined behavior. Bigints were only checked to fit in 64 bits, but QUIC error codes are variable-length integers limited to 62 bits, so larger codes cannot be encoded in the `CONNECTION_CLOSE` frame. Reject codes that are not integers between `0` and `2n ** 62n - 1n`, the range `QuicError` already enforces, before any close or destroy side effects.
-
quic: destroy stream on invalid promise bodyWhen `setBody()` receives a promise that resolves to an unsupported body type, `configureOutbound()` throws inside the fulfillment handler. The rejection handler only covered the original promise, so the error rejected a discarded promise and crashed the process as an unhandled rejection. Catch errors thrown by `configureOutbound()` in the fulfillment handler and destroy the stream with them, as the rejection handler already does. For an unsupported resolved value, `stream.closed` now rejects with the same `ERR_INVALID_ARG_TYPE` that `setBody()` throws synchronously.
-
fs: keep timestamps of files skipped by cpSyncWith `force: false` and `preserveTimestamps: true`, the native directory copy used by `cpSync()` left existing destination files in place but still copied the source timestamps onto them. The JavaScript walk, used by `cpSync()` with a `filter` and by `fs.cp()`, leaves those files untouched. Only copy the timestamps of files that were actually copied, as is already done for their mode.
-
ffi: reject unsafe integers as length or offsetGetValidatedSize() checks the value against static_cast<double>(SIZE_MAX), which rounds up to 2^64 on 64-bit platforms. A length or offset of 2 ** 64 gets through, and the cast to size_t after it is undefined behavior. With GCC on x64 it gives 0, so ffi.setUint8(ptr, 2 ** 64, 42) writes to ptr instead of throwing. Anything above Number.MAX_SAFE_INTEGER may already have been rounded by the time it gets here, so reject those values too. The export*() helpers already cap their length there, and so does setInt64() for number values. SIZE_MAX is still the limit on 32-bit platforms. When buffer.constants.MAX_LENGTH is Number.MAX_SAFE_INTEGER, as on 64-bit builds without the V8 sandbox, toBuffer() and toArrayBuffer() now throw ERR_OUT_OF_RANGE for MAX_LENGTH + 1 instead of ERR_BUFFER_TOO_LARGE.
-
fs: fix crash on negative zero file descriptor`isInt32()` accepts -0 because `-0 === (-0 | 0)`, but V8 does not represent -0 as an Int32 value, so `Value::IsInt32()` rejects it. The utf8 fast paths of `readFileSync()` and `writeFileSync()` hand the value straight to the binding, which then took it for a path and aborted on the null check. Coerce -0 to 0 before the call, matching `getValidatedFd()` and the rest of fs, where -0 is a valid way to name file descriptor 0.
-
fs: validate falsy openAsBlob type optionopenAsBlob() and openAsBlobSync() read the MIME type as options.type || '' before validating it, causing falsy non-string values to be replaced with the default before reaching validateString(). As a result, { type: 0 }, { type: false }, { type: null }, and { type: NaN } are accepted as an empty type, while { type: 1 } throws ERR_INVALID_ARG_TYPE. Default the option only when it is undefined so all other values are validated against the documented string type.
-
ffi: avoid memcpy() with a null pointerZero-length FFI memory operations accept a null pointer, but ToArrayBuffer() and ExportBytes() call memcpy() unconditionally. Passing a null pointer to memcpy() is undefined behavior even when the size is zero. Skip the copy when the length is zero, matching what Buffer::Copy() already does for the same case. An isolated reproduction compiled with -fsanitize=undefined reports "null pointer passed as argument 1, which is declared to never be null". The added test covers the reachable zero-length paths, but it passes without the fix: libc does not fault on memcpy(NULL, NULL, 0), and --enable-ubsan does not set -fno-sanitize-recover, so UBSan reports the call without failing the process.
-
ffi: reject non-boolean copy argumentsffi.toBuffer() and ffi.toArrayBuffer() document copy as a boolean, but read it with BooleanValue(), which applies JavaScript truthiness. A falsy non-boolean such as null, 0 or '' therefore selects the zero-copy mode, which returns a writable view over foreign memory instead of a copy, while values such as 'false' or 1 select a copy. Throw ERR_INVALID_ARG_TYPE when copy is neither undefined nor a boolean. Omitting copy or passing undefined still makes a copy, and true and false keep their current behavior.
-
fs: close fd 0 on discarded FileHandle transfer`FileHandle::TransferData` uses `-1` to indicate that it no longer owns a file descriptor. However, its destructor only closes descriptors greater than 0. If a transferred `FileHandle` owns fd 0 and the message is discarded, the descriptor is left open. Treat fd 0 like any other valid descriptor and only skip `-1`.
-
https: handle invalid TLS options in proxied requeststls.connect() can throw while validating TLS options. For proxied HTTPS requests, it is called after the CONNECT response has been received, so the throw happens asynchronously from the original https.request() call and ends the process as an uncaught exception. Catch the error, close the tunnel socket, and propagate it to the request.
-
fs: honor dereference for symlinks nested in cpSync treesWhen no filter is given, cpSync copies directory contents in C++. That loop recreated every symlink it found, consulting dereference only for the subdirectory-of-self guards, so a symlink nested in the tree was copied as a link even with dereference set. Only a symlink passed as src was dereferenced, because that one is resolved by stat() in JavaScript before the C++ copy starts. The directory and regular file branches already follow symlinks, so links that resolve to those types can fall through to them. A link whose target cannot be reached has nothing to copy, and uv_fs_stat() reports the underlying filesystem error. When following a link, preserve the existing force and errorOnExist behavior for occupied destinations. Under force, remove an existing destination first so copying does not write through a destination symlink.
-
vfs: write RealFSProvider files to open fdWrite RealFileHandle contents through the open file descriptor instead of reopening the original real path, mirroring 8cb83126b83 for reads. This keeps writes attached to the opened file across renames and makes them honor the handle's access mode. Preserve iterable support and filehandle.writeFile() current-position semantics.
-
test: deflake node-api test-free-called`node-api/test_worker_buffer_callback/test-free-called` checks that `getFreeCallCount()` is 0 on a line that runs after `new Worker()`. The worker thread can load the addon and run its finalizer before the main thread reaches that line, in which case the counter is already 1 and the assertion fails. The zero check is only a baseline, so it does not need the worker to exist. Move it above the worker creation. The equivalent test under test/addons/worker-buffer-callback was changed the same way in 64f7d0e0bd04.
-
quic: reject zero addressLRUSizeSocketAddressLRU::Upsert always inserts an entry before evicting down to max_size_. With max_size_ == 0, it evicts the entry it just inserted and then accesses the now-missing key via map_[address]->second. operator[] recreates the key with a default-constructed std::list iterator, which is then dereferenced. This is undefined behavior, observed as a SIGSEGV in Endpoint::Receive on the first UDP packet accepted by a QuicEndpoint constructed with { addressLRUSize: 0 }. SocketAddressLRU has no useful semantics for a zero-capacity cache, and Upsert's callers rely on it returning a valid pointer. Reject 0 (and 0n) at the options-parsing boundary instead of changing Upsert's contract.
-
test: handle EPIPE in closed channel testThe second handle is only sent once the first one is acknowledged, by which time the worker may already have exited, so the write can fail with EPIPE. Observed on AIX in the CI reliability report of 2026-09-04.
-
test: deflake test-permission-net-udp-handleSending a dgram socket over IPC duplicates the handle instead of moving it: `dgram.Socket` has no `postSend` in the child_process conversion table, and `bind()` calls `recvStart()` unconditionally, so the parent copy keeps consuming datagrams after the child adopts the handle. Both sockets then compete for every packet, and the child receives nothing until it wins that race. Locally the parent took up to 111 consecutive packets first, stretching the run to about 1.2s; the retry interval is the only thing keeping the test alive, and how long the parent can hold the socket is a property of the scheduler, not of the test. Close the parent copy as soon as the child reports it is receiving, so the child is the only reader by the time the first datagram is sent.
-
test: zero-fill buffers before the string length limit checkThe test allocates a buffer one byte longer than MAX_STRING_LENGTH and expects toString('utf8') to throw ERR_STRING_TOO_LONG. MAX_STRING_LENGTH counts UTF-16 units rather than bytes, so that only holds if every byte decodes to a single unit. For the two Buffer.allocUnsafe variants the contents are whatever the allocator hands back, and a single multi-byte UTF-8 sequence anywhere in the buffer decodes to fewer units than it occupies bytes, bringing the result down to MAX_STRING_LENGTH or less so that nothing is thrown. This goes unnoticed when the allocator returns zeroed pages, which is why the test passes elsewhere. The AIX builders expose non-zero contents and fail with "Missing expected exception (Error)".
-
errors: validate constructor namedetermineSpecificType() checks for a usable constructor name with `'name' in value.constructor`. That accepts an empty name, and the `in` operator requires its right-hand side to be an object. Anonymous classes own a `name` that is the empty string, so they produce messages ending in a dangling "Received an instance of ". A truthy primitive `constructor` reaches the `in` operator and throws while the message is being built, so ERR_INVALID_ARG_TYPE is replaced by a TypeError carrying no `code`. The latter is reachable from untrusted input, since `constructor` is an ordinary JSON key. The check changed in #49696, while this function was rewritten as a switch. That pull request updated test/common's invalidArgTypeHelper to match its deliberate change to the `function` branch, but left the helper's `object` branch on the original truthy check, so the two have disagreed since. Read `constructor` and its `name` once and use the name only when it is a non-empty string. Requiring a string also stops meaningless names from being interpolated: 42 currently yields "an instance of 42", and a symbol name throws outright. The current check reads `constructor` three times, which an accessor can observe. Move the helper to the same check so the two cannot drift apart again.
-
test: deflake test-runner-coverageThe subtests that set NODE_V8_COVERAGE leave a coverage-<pid>-*.json file in the test tmpdir, and nothing removes it. The later subtests spawn without NODE_V8_COVERAGE, so their coverage goes to a private mkdtemp directory that is removed on cleanup rather than to the test tmpdir. A match in findCoverageFileForPid(result.pid) can therefore only come from a stale file whose pid has been reused, which is why the failures are only reported on platforms that recycle pids quickly. Refresh the tmpdir from an after() hook on each subtest that dumps into it, so a failure in one of them cannot leave the file behind and turn every later check into a second, misleading failure. Drop the flaky designations.
-
test: deflake test-inspect-async-hook-setup-at-inspectThe test sends Debugger.setAsyncCallStackDepth in the same batch as Runtime.enable and Debugger.enable, and treats the command response as proof that async stack recording is on. It is not. While the target runs JS the command is dispatched from a V8 interrupt, where Agent::SyncAsyncHookState() cannot call into JS and defers enabling the async hook to an immediate, answering the command anyway. The `debugger` in the polling interval then pauses the target before that immediate runs, and the nested message loop does not process immediates, so setupTimeoutWithBreak() schedules the timer with the hook still disabled and Debugger.paused arrives without asyncStackTrace. Send the command after the first pause instead. Messages dispatched while the target is paused come from the nested message loop rather than an interrupt, so the hook is enabled inline and the response is the barrier the test assumed it to be. Deferring is deliberate: calling into JS from a V8 interrupt is not safe. This corrects an assumption of the test, not the runtime.
-
test: deflake test-watch-mode-restart-esm-loading-errorThe previous deflake of this test, #63390, gave the two restart waits common.platformTimeout(10_000) and left the first restart() on the helper's 1000 ms default. That first call is the one still timing out on CI. It is also the call that needs the budget most. --watch spawns a child process to run the script, so reaching the first Completed running costs two process startups, while the later restarts pay for one. Wrapping the default in platformTimeout() would not have been enough on its own: none of its multipliers reaches a factor of ten, so the budget would still be 1000 ms on these jobs, or 2000 ms in a debug build. Give that call the budget the other two already ask for, stated once in the default rather than three times. The timer bounds how long the test waits for watch mode to make progress, it is not an assertion about restart latency, and the assertions on stdout and stderr are untouched. The same helper is duplicated in test-watch-mode.mjs, with the same default and nine call sites that take it. That file has carried PASS, FLAKY since #44898, which is why only this one surfaces in the reliability reports.
-
vfs: fix rename over non-empty directoryThe memory provider only rejected renames whose destination had a different type than the source, so renaming a directory onto another directory silently dropped the destination and everything under it. An existing destination directory has to be empty; rename(2) reports ENOTEMPTY otherwise, and RealFSProvider already does so because it delegates to fs.renameSync(). Also, decrement nlink on a file that is replaced by a rename, and make a rename whose two names resolve to the same entry a no-op, which covers renaming one hard link onto another.
-
test: deflake fastutf8stream destroy and reopen testsBoth tests read the destination file with no ordering guarantee against the fs.write() that Utf8Stream still has in flight, so under load the read can observe an empty file. In test-fastutf8stream-destroy the read is issued right after destroy(). In test-fastutf8stream-reopen it is ordered on 'drain', documented as emitted when the buffer has drained enough to allow continued writing, which says nothing about the bytes being observable in the file. The reopen path also emits a 'drain' of its own from a nextTick before the write has landed. Order both reads on 'write' instead, documented as emitted when a write operation has completed and emitted from #release() once the underlying write returned. In sync mode it is emitted from within write(), so the listener is attached before the write call. No data is lost by Utf8Stream here: re-reading the file after a failed assertion shows the expected content. This corrects an expectation of the tests, not the runtime.
Updated daily, last on 2026-11-16. By Christian Aurich Zanettini Martins · All projects