Skip to content

Bun.write: do not chmod a FIFO or device destination when copying from Bun.file() - #44985

Closed
robobun wants to merge 3 commits into
mainfrom
robobun/c987d9d5/bun-write-mode-skip-non-regular
Closed

robobun wants to merge 3 commits into
mainfrom
robobun/c987d9d5/bun-write-mode-skip-non-regular

Conversation

@robobun

@robobun robobun commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Bun.write(dest, Bun.file(src), { mode }) changes the mode of a FIFO, device or terminal that exists at dest. On 1.4.2 a FIFO goes from 644 to 600. A script that writes to /dev/stdout changes the mode of its terminal.
  • CopyFile::do_close (src/runtime/webcore/blob/copy_file.rs:184) calls fchmod on the destination with no file-type check. fix(io): respect mode option when copying files with Bun.write() #25906 added that call (v1.3.6).

Fix

  • do_close calls fstat first and applies mode to a regular file only. The data still reaches the FIFO or device, and the promise resolves.
  • A failed fstat rejects the write and skips the fchmod.
  • Verified: 4 new cases in test/js/bun/io/bun-write.test.js fail on 1.4.2 and on main. Also test/regression/issue/25903.test.ts and the bun-types test.

Background

Downsides

  • One fstat more per copy with mode (Linux: 7 to 8 syscalls). It is the only stat of the destination. Without mode: 6, as before.
  • Behavior change: a caller that does not own the FIFO or device got EPERM after the data was written. That call now resolves.
  • Release .text grows by 256 bytes.
Notes

Report. There is no GitHub issue and no user report. The defect was found by a read of the code while #32885 was reviewed. It is in every release since v1.3.6.

Repro (Linux, no root):

// repro.mjs
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bun-write-mode-"));
const src = path.join(dir, "src.txt");
const fifo = path.join(dir, "dest.fifo");
fs.writeFileSync(src, "hello\n");
execFileSync("mkfifo", ["-m", "644", fifo]);
// Without a reader, open(O_WRONLY) on a FIFO blocks.
const reader = fs.openSync(fifo, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);

const written = await Bun.write(fifo, Bun.file(src), { mode: 0o600 });
const chunk = Buffer.alloc(16);
const data = chunk.toString("utf8", 0, fs.readSync(reader, chunk, 0, chunk.length, null));
fs.closeSync(reader);
console.log(`written ${written}, reader got ${JSON.stringify(data)}, FIFO mode ${(fs.statSync(fifo).mode & 0o777).toString(8)} (was 644)`);
fs.rmSync(dir, { recursive: true, force: true });
bun 1.4.2:                 written 6, reader got "hello\n", FIFO mode 600 (was 644)
main (release build):      written 6, reader got "hello\n", FIFO mode 600 (was 644)
this branch (release):     written 6, reader got "hello\n", FIFO mode 644 (was 644)

Other cases run on Linux 6.1 x64 (bun 1.4.2 and a release build of main against a release build of this branch). The data arrives in every case.

Destination, with mode before after
FIFO at 644, by path 600 644
FIFO at 644, Bun.file(path) after exists() (Linux copies it with sendfile) 600 644
FIFO at 644, Bun.file(fd) 600 644
private mknod c 1 3 node at 666, by path (root) 600 666
the terminal of a child on a pty, written as /dev/stdout the requested mode unchanged
root-owned 0666 FIFO, caller is uid 65534 rejects EPERM (fchmod) after the data arrived resolves 6
existing regular file, new file 600 600
regular file that the caller can write but does not own rejects EPERM after the data is written the same (not changed here)

Workaround for released versions. Pass mode only when the destination is a regular file or does not exist:

const stat = fs.statSync(dest, { throwIfNoEntry: false });
await Bun.write(dest, Bun.file(src), !stat || stat.isFile() ? { mode: 0o600 } : undefined);

Measurements. Release builds of main (c6da4a4) and of this diff on that base (the branch was rebased afterwards, the diff is the same). Linux 6.1.155 x64.

  • Syscalls of the pool thread from the first open to the last close, for a 6-byte copy (gdb syscall catchpoints):

    Copy main this PR
    no mode, regular file 6 6
    no mode, BUN_CONFIG_DISABLE_COPY_FILE_RANGE=1 10 10
    mode, existing or new regular file 7 8
    mode, regular file, BUN_CONFIG_DISABLE_COPY_FILE_RANGE=1 11 12
    mode, FIFO or char device by path 12 12 (fstat in place of fchmod)
    mode, stat'ed FIFO BunFile, or a caller fd on a FIFO 7 7 (the same swap)
  • Instructions executed in CopyFile::do_close (gdb stepi): no mode 51 to 50. mode + regular file 64 to 78.

  • Among the CopyFile symbols only do_close changes size: 359 to 593 bytes. Release .text 65,782,357 to 65,782,613 bytes. The stripped binary has the same file size.

  • size_of::<CopyFile>() stays 496 bytes. The diff adds no field.

Test strength. With the non-regular arm of the new check removed, all 4 cases fail. With the check changed to drop the mode for a regular file too, 3 of 4 fail. No test forces fstat to fail, so nothing pins the Err arm.

The flag that is not in this PR. The first version of this branch recorded a proof in CopyFile when copy_file_range (Linux 4.11 and later) or the fallback's ftruncate succeeded, and skipped the fstat then. Measured: 7 stays 7 and 11 stays 11 syscalls, .text +512 bytes. A self-review said to remove it: it saves one fstat per copy with mode, no test fails when the proof is deleted, no CI lane runs a kernel older than 4.11, and it added 2 conflict hunks each against #41209, #37856 and #44301. If a maintainer wants the zero-syscall form, it is a follow-up after those PRs.

Open PRs on the same lines (conflict hunks counted with git merge-file against 29 open PR heads, 26 of which touch one of the three files):

  • Remove libuv on Windows #42819: 0 hunks. It rewrites the fchmod block that follows the new check, so that a descriptor the caller passed does not get the mode. This check is the other half: a destination that Bun opened by path gets the mode only when it is a regular file. After Remove libuv on Windows #42819 lands, self.destination_fd != Fd::INVALID in the check can become close_input.
  • Bun.write: apply mode for string, buffer, Blob and stream sources on POSIX #32885: 2 hunks, both JSDoc prose in bun.d.ts. Its apply_mode makes the same check for the other Bun.write sources. It leaves CopyFile alone and asks whether CopyFile should set the mode before the data.
  • Every other head: 0 hunks in copy_file.rs and in the test file.

Not changed here

Platforms. Built and run on Linux x64. cargo check -p bun_runtime passes for aarch64-apple-darwin, x86_64-unknown-freebsd, aarch64-linux-android and x86_64-pc-windows-msvc. The macOS and FreeBSD arms were not run here. In CI the FIFO cases pass on the macOS lanes (aarch64 and x64, build 124565). The terminal case is Linux only: macOS opens /dev/stdout as a dup of fd 1.

Question for a maintainer. For a FIFO, device or terminal that Bun.write opens by path, this PR writes the data and skips mode. The alternative is to reject such a destination when mode is given. Which one do you want?

Self-review. It raised 8 concerns, and all 8 are addressed. The flag is gone, and with it its kernel-version compare, its two-line comment and its untested splice arm. The FIFO cases now run on macOS lanes, the JSDoc is scoped to POSIX, Windows is named above, and the numbers are from the final diff. A later review asked for it.each, an async mkfifo spawn and a temp dir that the test body owns. The second commit does that.

Suites run (debug build): the 4 new cases, all of test/js/bun/io/bun-write.test.js (110 pass with --timeout 90000), test/regression/issue/25903.test.ts (7 pass), test/integration/bun-types/bun-types.test.ts (22 pass), cargo clippy -p bun_runtime.


no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/io/bun-write.test.js

@robobun
robobun requested a review from alii as a code owner October 11, 2026 13:40
@robobun

robobun commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:23 AM PT - Oct 17th, 2026

❌ @robobun, your commit 29683ac has 1 failures in Build #127388 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 44985

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

bun-44985 --bun

@robobun

robobun commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduction (Linux x64, bun 1.4.2 and a release build of main)

  • Bun.write(fifo, Bun.file(src), { mode: 0o600 }) with a reader on the FIFO: the data arrives, and the FIFO goes from 644 to 600.
  • A private mknod c 1 3 node (as root) goes from 666 to 600.
  • A child on a pty that writes to /dev/stdout with a mode changes the mode of its terminal.
  • On this branch the FIFO, the device and the terminal keep their mode. A regular destination still gets mode.
  • The script is in the Notes block of the PR body.

Tests

  • test/js/bun/io/bun-write.test.js has 4 new cases. All 4 fail on bun 1.4.2 and on a build of main. All 4 pass on this branch.
  • Three of the cases use a FIFO and run on every POSIX lane. They pass on the macOS lanes in CI (aarch64 and x64, build 124565). The terminal case is Linux only.

Fix

  • CopyFile::do_close calls fstat before the fchmod and applies mode to a regular file only.
  • Self-reviewed: 8 concerns raised, 8 addressed. The largest one removed a flag that skipped the fstat on Linux. The Notes block has the details.

CI

  • The diff is green. Every job that ran tests passed on the current head, on Linux, Windows and macOS (build 127388: 180 jobs passed, 1 failed).
  • test/js/bun/io/bun-write.test.js passed there on macOS aarch64 and macOS x64 (90 pass, 0 fail) and on every Linux lane.
  • The one red job is a macOS aarch64 test-bun shard that ran no test: buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun'. The same step failed the same way on another agent in build 126640.
  • The first push of this PR had all lanes green (build 124565). The code under src/ did not change since then.
  • I used my one retrigger. A retry of the red job, or a merge over it, is a maintainer's call.

Needs a maintainer's decision

  • For a FIFO, device or terminal that Bun.write opens by path: write the data and skip mode (this PR), or reject the call when mode is given.

@coderabbitai

coderabbitai Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: oven-sh/bun/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 4c18eb36-8401-4eb4-a7cf-de708451388e
📥 Commits

Reviewing files that changed from the base of the PR and between 6c1eb06 and c73c01a.

📒 Files selected for processing (3)
  • packages/bun-types/bun.d.ts
  • src/runtime/webcore/blob/copy_file.rs
  • test/js/bun/io/bun-write.test.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Walkthrough

On POSIX, Bun.write applies a requested destination mode only to regular files. The copy path checks the destination type before applying the mode. Tests cover FIFO, regular-file, and terminal destinations.

Changes

Bun.write destination modes

Layer / File(s) Summary
Regular-file-only mode application
packages/bun-types/bun.d.ts, src/runtime/webcore/blob/copy_file.rs, test/js/bun/io/bun-write.test.js
The declarations describe the POSIX behavior. CopyFile::do_close checks the destination with fstat and applies the requested mode only to regular files. Tests cover path, BunFile, file-descriptor, and terminal destinations.

Suggested reviewers: jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to c73c0

The change is mergeable after normal checks; no concrete issue remains identified.

Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description clearly explains the problem, implementation, behavior change, trade-offs, platform scope, and verification results. It does not use the template headings exactly, but it provides the …
Title check Passed The title is concise, specific, and accurately identifies the main change: preventing chmod on FIFO or device destinations when copying from Bun.file().
Full details: Description check

Explanation

The description clearly explains the problem, implementation, behavior change, trade-offs, platform scope, and verification results. It does not use the template headings exactly, but it provides the required information in equivalent sections.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

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

Beyond the inline nits, I also checked that the system_error set by the new fstat arm in do_close is observed by then() (it rejects at src/runtime/webcore/blob/copy_file.rs:160), that the st_mode as _ cast matches the existing S::ISREG call sites in the same file, and that the macOS clonefile chmod-by-path and Windows uv_fs_chmod paths remain unguarded — the description names both as intentionally out of scope. The PR also asks a maintainer to choose between skipping mode and rejecting the write for a non-regular destination; that design call needs a human.

Extended reasoning...

The change adds a single fstat guard in CopyFile::do_close so fchmod only runs on a regular file, plus JSDoc and a POSIX-only test block with FIFO and tty fixtures. It touches no auth, crypto, or input-parsing surface. Two test-convention nits were posted inline, and the author's open question about skip-versus-reject semantics is a behavior decision for a maintainer rather than something this review can settle.

Comment thread test/js/bun/io/bun-write.test.js Resolved
Comment thread test/js/bun/io/bun-write.test.js Resolved
…m Bun.file()

CopyFile::do_close called fchmod on the destination with no file-type
check. When the destination was an existing FIFO, device or terminal,
the copy wrote the data through it and then changed the mode of that
shared node.

do_close now calls fstat before the fchmod and applies `mode` to a
regular file only. A failed fstat rejects the write and skips the
fchmod.
…nation matrix

The FIFO fixture created the temp dir and then ran the fallible setup
(mkfifo, open), so a failed setup left the directory behind. Each test
now holds the temp dir with `using` before the setup runs. mkfifo runs
through Bun.spawn, and the two destination forms are an it.each table.
@robobun
robobun force-pushed the robobun/c987d9d5/bun-write-mode-skip-non-regular branch from c73c01a to 02311df Compare October 16, 2026 11:40

@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.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-17.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 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.

1 participant