Skip to content

node:fs: report the real errno from rm, and stop resolving fs stream paths - #41486

Closed
robobun wants to merge 4 commits into
mainfrom
robobun/95b4dcd9/fs-rm-errno-stream-path
Closed

robobun wants to merge 4 commits into
mainfrom
robobun/95b4dcd9/fs-rm-errno-stream-path

Conversation

@robobun

@robobun robobun commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Draft. An earlier version said the rm lstat rule matches Node in all three forms. It does not. See Downsides.

Problem

  • fs.rmSync("file.txt/child"), fs.rm and fs.promises.rm throw EFAULT: bad address in system call argument, rm 'file.txt/child'. Node throws ENOTDIR from lstat. map_rm_errno_narrow (src/runtime/node/node_fs.rs:9605 on main) maps most unlink errnos to EFAULT. The JS wrapper drops every lstat error.
  • fs.createReadStream("nope/../file.txt") opens file.txt. Node fails with ENOENT. getValidatedPath (src/js/internal/fs/streams.ts:96 on main) runs path.resolve() before open(). A Buffer path throws ERR_INVALID_ARG_TYPE.

Fix

  • NodeFS::rm, non-recursive branch: return the unlink errno. Delete map_rm_errno_narrow.
  • rmSync and promises.rm: lstat when !force || !recursive, and rethrow every lstat error except ENOENT.
  • ReadStream and WriteStream: pass the path to open() as given, after getValidatedFsPath.
  • Verified: three new tests in test/js/node/fs/fs.test.ts fail on bun 1.4.3. No test reaches the native errno change.

Background

Downsides

  • Known gap: { recursive: true, force: true } on a path through a file. Node's fs.rm and fs.promises.rm report ENOTDIR from lstat. This branch reports it from rm, and the new test asserts that. Node's rmSync returns with no error. This branch throws.
  • Cost: rm with { recursive: true } and no force runs one more lstat per call. Counted from the diff, not measured.
  • Behaviour change: stream.path is the given value, not an absolute path. A relative path resolves at open time.
Notes

Correction log. The first description said rmSync and promises.rm run the lstat when !force || !recursive, "like node". The { recursive: true, force: true } case was not run against Node before the PR opened. Node v26.3.0 source, read from the binary with --expose-internals: validateRmOptionsSync has the gate !options.force || expectDir || !options.recursive. validateRmOptions calls lstat with no gate.

rm("file.txt/child", options), where file.txt is a regular file. Each cell is code syscall.

options form node v26.3.0 bun 1.4.3 this branch
none, {force} all three ENOTDIR lstat EFAULT rm ENOTDIR lstat
{recursive} all three ENOTDIR lstat ENOTDIR rm ENOTDIR lstat
{recursive, force} rmSync no error ENOTDIR rm ENOTDIR rm
{recursive, force} fs.promises.rm ENOTDIR lstat ENOTDIR rm ENOTDIR rm
{recursive, force} fs.rm ENOTDIR lstat ENOTDIR rm ENOTDIR rm

The node and bun 1.4.3 columns are from a run on Linux x64. In the branch column, the first two rows and the fs.promises.rm cell are from a debug build of the first commit of this PR before the rebase (a6bfdb0). The rmSync and fs.rm cells for {recursive, force} are read from the diff, which does not touch that path. They were not run on a build of this branch.

Limits of the proof.

  • The native change is reachable only when the lstat succeeds and the unlink then fails with an errno outside the old list (EPERM, EISDIR, EIO). No test does that.
  • On bun 1.4.3 the two stream tests fail at their first assertion, the Buffer path (ERR_INVALID_ARG_TYPE). They do not get to the .. and stream.path assertions. A manual run showed those: createReadStream("nope/../file.txt") opens the file on 1.4.3 and fails with ENOENT on a6bfdb0, as in Node.
  • The evidence block below records that the automated fail-before check did not run for this test file.
  • Windows: nothing here was run on Windows. The tests skip the .. case and the rm ENOTDIR case there. The reasons for the skips (Win32 collapses .. before the filesystem sees it, and libuv reports a path through a file with a different errno) come from reading, not from a run.
  • Versions: reproduced on bun 1.4.3. The sweep that found both divergences reports them on 1.3.14, 1.4.0, 1.4.2 and main.

Runs on a6bfdb0 (debug build). test/js/node/fs/fs.test.ts (568 pass, 8 skip), test/js/node/fs/fs-leak.test.js, test-fs-rm.js, test-fs-rmSync-special-char.js, test-fs-rmdir-throws-on-file.js, test-fs-rmdir-throws-not-found.js, and the 34 files that match test-fs-read-stream*, test-fs-write-stream* or test-file-write-stream*. The first description listed test-fs-rmdir*.js. test-fs-rmdir-type-check.js was not in that run. The status comment lists the runs on the rebased head.

Costs counted from the diff.

  • Before: the JS lstat ran only without recursive. After: it also runs for { recursive: true } without force. That is one more lstat for rmSync, and one more fs.lstat on the thread pool for fs.rm and fs.promises.rm. Calls with { recursive: true, force: true } and non-recursive calls run the same syscalls as before.
  • stream.path was an absolute string. It is now the value passed in (a string, a Buffer, or the path of a URL). A relative path resolves against the cwd when the stream opens. A process.chdir() between the constructor and the open changes the file, as in Node.

Background detail. The EFAULT table is a port of the Zig source before the Rust rewrite (src/runtime/node/node_fs.zig at the parent of 23427db): std.posix.unlinkZ(dest) catch |err1| followed by a switch that ends in else => .FAULT. bun_sys::unlink returns the raw errno, so the table can only hide information.

Related PRs.


no test proof · iteration 1 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/fs/fs.test.ts

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 33 seconds.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between c643ea8 and 5cf0198.

Files selected for processing: 5
  • src/js/internal/fs/streams.ts
  • src/js/node/fs.promises.ts
  • src/js/node/fs.ts
  • src/runtime/node/node_fs.rs
  • test/js/node/fs/fs.test.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — focused Node-compat fix with the full sync/callback/promises matrix covered.

What was reviewed:

  • rmSync/promises.rm lstat gate: !force || !recursive matches Node's validateRmOptions; non-ENOENT rethrow and !recursive-gated EISDIR are correct; callback fs.rm routes through promises.rm so all three stay in sync.
  • map_rm_errno_narrow deletion: only call site removed in the same hunk; raw errno now surfaces with the rm tag.
  • Stream path handling: getValidatedFsPath accepts string/Buffer/URL with a NUL check and no resolve; the fastPath bypass is preserved (and the old cwd-deletion caveat is moot without path.resolve).
  • Tests: added to the existing file, use tempDir, await open/error events (no sleeps), assert {code, syscall, path}, and Windows-gate the ../trailing-/ cases with a stated reason.
Extended reasoning...

Overview

This PR fixes two node:fs compatibility divergences. For rm/rmSync/promises.rm, it widens the JS-side pre-removal lstat to run whenever !force || !recursive (matching Node's validateRmOptions), rethrows non-ENOENT lstat errors as-is instead of swallowing them, and deletes the native map_rm_errno_narrow table that collapsed most unlink errnos to EFAULT. For createReadStream/createWriteStream, it swaps a local getValidatedPath (which ran path.resolve() and rejected Buffers) for the shared getValidatedFsPath validator, so .path preserves the input verbatim and open() sees the literal path. Five files touched: src/js/internal/fs/streams.ts, src/js/node/fs.ts, src/js/node/fs.promises.ts, src/runtime/node/node_fs.rs, and test/js/node/fs/fs.test.ts.

Security risks

None identified. The change surfaces more accurate errnos rather than hiding them, and stops normalizing user paths before open() — which is actually the safer direction (a nope/../file.txt path now fails at the kernel walk of nope instead of silently collapsing). No auth, crypto, or permission logic is involved; input validation is delegated to the existing shared getValidatedFsPath which retains the NUL-byte check.

Level of scrutiny

Moderate. This is Node-compat work in src/js/node/ and src/runtime/node/, so the bar is "match Node's full error contract across every sibling form." I verified: the fs.ts and fs.promises.ts guards are byte-for-byte parallel; the callback fs.rm delegates to promises.rm so it inherits the fix; the EISDIR branch is correctly re-gated on !recursive now that the outer condition is wider; the deleted Rust helper has no remaining callers; and getValidatedFsPath in internal/validators.ts handles URL→path, string/Buffer passthrough, and NUL rejection as described. The removed fastPath comment about cwd deletion is no longer needed because path.resolve() is no longer called.

Other factors

Tests land in the existing test/js/node/fs/fs.test.ts, use tempDir from harness, iterate the full option matrix (undefined, {force}, {recursive}, {recursive, force}) across all three rm entry points, assert the exact {code, syscall, path} shape, and wire both open and error to resolve the awaited promise (no sleeps). Windows-specific kernel-normalization behavior is gated with isWindows and explained inline. No CODEOWNERS cover these paths. The bug hunt ran to a dry streak with no findings and no ruled-out candidates. The PR description states these tests fail on released Bun and that the relevant Node parallel tests still pass.

@robobun

robobun commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Overlap note. This PR now owns the fs.rm errno passthrough (the removal of map_rm_errno_narrow and the JS-side lstat rethrow). #33436 carried the same change on a stale base and is closed in favor of this one. Its { recursive: true, force: true } success case was not carried over: Node's fs.promises.rm and callback fs.rm throw ENOTDIR there, which is what the test here asserts.

#41480 reworks the recursive walker and also deletes map_rm_errno_narrow in the same region. It depends on this change for the non-recursive path and needs a rebase once this merges. The stream path fix in this PR does not overlap with anything else.

Comment thread src/js/node/fs.promises.ts Resolved
Comment thread src/js/node/fs.ts Resolved
@robobun

robobun commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:27 AM PT - Oct 27th, 2026

❌ @robobun, your commit 5cf0198 has 2 failures in Build #133609 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 41486

That installs a local version of the PR into your bun-41486 executable, so you can run:

bun-41486 --bun

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

…paths

fs.rm and fs.rmSync mapped every unlink errno outside a short list to
EFAULT, so a path that goes through a regular file reported EFAULT
instead of ENOTDIR. Pass the errno through. The JS-side lstat that runs
before the removal now rethrows every error except ENOENT, which is
what node does, so the ENOTDIR is tagged lstat like in node.

fs.ReadStream and fs.WriteStream ran path.resolve() on the path before
open(). A ".." through a missing directory then opened the collapsed
path, and stream.path was absolute instead of the given value. Buffer
paths were rejected. Validate the path like node does and hand it to
open() as given.
The src/js type check (`tsc --noEmit -p src/js/tsconfig.json`) runs in
CI since #43649. This branch was last checked before that.

- `FSStream.path` accepts a `Uint8Array`. The streams keep a Buffer
  path as it is now, so the old `string` type was wrong.
- The fast-path `Bun.file(this.path)` call casts to `string`. Only
  internal callers reach it, and they pass a string.
- The `rm` and `rmSync` lstat catch blocks read `err.code`, so the
  catch variable is `any`, like the other catch blocks in fs.ts.
- The three new tests in fs.test.ts no longer add type errors to
  `test/`.

Types only. The bundled JS is byte-identical.
@robobun
robobun force-pushed the robobun/95b4dcd9/fs-rm-errno-stream-path branch from 705b816 to 5cf0198 Compare October 27, 2026 09:10
@robobun

robobun commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: draft. Not ready to merge.

Correction, Oct 27. The description said the rm lstat rule (!force || !recursive) matches Node for rmSync, fs.rm and fs.promises.rm. That case was not run against Node before the PR opened. Node v26.3.0 uses the rule only in validateRmOptionsSync. validateRmOptions, which fs.rm and fs.promises.rm use, always runs the lstat.

rm("file.txt/child", { recursive: true, force: true }), where file.txt is a regular file:

form node v26.3.0 bun 1.4.3 this branch
rmSync no error ENOTDIR, rm ENOTDIR, rm (read from the diff, not run)
fs.promises.rm ENOTDIR, lstat ENOTDIR, rm ENOTDIR, rm (the new test asserts this)
fs.rm ENOTDIR, lstat ENOTDIR, rm ENOTDIR, rm (read from the diff, not run)

The overlap note above says the test matches Node for this case. The error code matches. The syscall does not.

The description now also states what the first version left out:

  • rm with { recursive: true } and no force runs one more lstat per call.
  • stream.path changes from an absolute path to the given value.
  • No test reaches the native errno change. The two stream tests fail on bun 1.4.3 at the Buffer path assertion, before the .. assertions.

Not checked before the PR opened: whether the lstat belongs in JS before the removal, or in NodeFS::rm after a failed removal. #44588 takes the second approach, which adds no syscall to a successful call. That comparison comes next. The test and the lstat rule change after it.

Earlier status (Oct 27, before the correction)

Status: ready for review. CI runs on 5cf0198.

Oct 27: rebased onto main (c643ea8), with one commit on top. The previous head was 705b816.

CI did not type-check src/js when this branch was last checked (#43649 added that). On today's main the branch failed that check:

src/js/internal/fs/streams.ts(142,5): error TS2322: Type 'string | Uint8Array<ArrayBufferLike>' is not assignable to type 'string | null | undefined'.
src/js/internal/fs/streams.ts(384,5): error TS2322: Type 'string | Uint8Array<ArrayBufferLike> | null | undefined' is not assignable to type 'string | null | undefined'.
src/js/node/fs.promises.ts(350,18): error TS2339: Property 'code' does not exist on type '{}'.
src/js/node/fs.ts(564,18): error TS2339: Property 'code' does not exist on type '{}'.

5cf0198 fixes them with types only. FSStream.path now includes Uint8Array, because the streams keep a Buffer path as given. The fast-path Bun.file(this.path) call casts to string: only internal callers reach it, and they pass a string. The two rm catch variables are typed, and so are the three new tests. The bundled JS is byte-identical with and without the commit.

Reproduced again on the rebased branch with a debug build: the three new tests in test/js/node/fs/fs.test.ts fail with main's src/ (EFAULT from rm, ERR_INVALID_ARG_TYPE for a Buffer stream path) and pass with this branch. Also passing with this branch: test/js/node/fs/fs-leak.test.js and the upstream test-fs-rm*, test-fs-rmdir*, test-fs-read-stream*, test-fs-write-stream*, test-file-write-stream* and test-fs-stream-* files.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline finding, I also checked whether widening FSStream.path to Uint8Array can reach Bun.file(this.path as string) in underscoreWriteFast with a Buffer — it cannot: that branch only runs when the internal $fastPath option is set, and every such caller (writableFromFileSink, process stdio, tty) passes ""/null plus an fd, so a user-supplied Buffer path never takes the fast path.

Extended reasoning...

The change touches the node:fs rm pre-check in both fs.ts and fs.promises.ts, the non-recursive unlink errno mapping in src/runtime/node/node_fs.rs, and path validation in fs ReadStream/WriteStream; no auth, crypto or injection surface. A confirmed finding is posted inline and the hunt stopped at its bug cap rather than running dry, so approval is not on the table; this note only records the one additional candidate ruled out from reading the fast-path wiring in streams.ts.

Comment thread src/js/node/fs.promises.ts Resolved
@robobun

robobun commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Closing. The stream half is now #47968, on its own and rebased on main. The rm half should not land in this form.

Why the rm half stops here. A design review compared it with the other open rm work. Its conclusion: the lstat does not belong in the JS wrappers before the removal. NodeFS::rm should decide the error natively after a removal fails, with no JS pre-check and no errno table. A successful call then runs fewer syscalls than today, and all three forms can match Node. I have the conclusion and the list of steps of that review, not its full text.

State of main today (debug build of b1007f1, Linux x64). For rm("file.txt/child", options) and rm("file.txt/", options), where file.txt is a regular file, 24 of the 60 cells in my matrix differ from Node v26.3.0. Each cell is code syscall.

options node v26.3.0 main
none, {force} ENOTDIR lstat in all three forms EFAULT rm
{recursive} ENOTDIR lstat in all three forms ENOTDIR rm
{recursive, force} rmSync: no error. fs.rm and fs.promises.rm: ENOTDIR lstat ENOTDIR rm

The other 36 cells (a missing path, a directory) agree with Node.

Open work in the same function.

No open PR does these two things yet: report the real errno from the non-recursive unlink (delete map_rm_errno_narrow), and give the lstat tag to an error that Node's pre-check raises. That is a follow-up on top of #44588. I did not open it now, because it would conflict with #44588 and #47879.

The status comment above has the earlier analysis and the correction of my first description.

@robobun robobun closed this Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants