Skip to content

Commit cfaa746

Browse files
committed
fix(atomic): bind directory modes to descriptors
1 parent 8926c33 commit cfaa746

6 files changed

Lines changed: 303 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Security and Correctness
66

7+
- Apply atomic-replacement parent-directory modes through verified no-follow descriptors on POSIX, so a directory-entry swap cannot redirect `chmod` through a symlink to an unrelated directory. Windows keeps its explicit `mkdir(mode)`-only behavior because Node does not enforce POSIX directory modes there.
78
- Retry a contended file-lock acquisition when Windows denies access to a lock file whose directory entry is still being torn down, including when the native binding performs the exclusive create. Both the exclusive create and the holder's snapshot read reported that transient `EPERM` as a hard failure, so concurrent `acquireFileLock()` calls failed intermittently on Windows even though the very next attempt would have succeeded. Retries stay bounded, so a genuine permission denial still surfaces as `EPERM` rather than a lock timeout; thanks @Yigtwxx for the fix.
89
- Apply `replaceFileAtomic()` and `replaceFileAtomicSync()` modes through pinned temp-file descriptors before rename, and through pinned copy-fallback descriptors, so a post-rename symlink swap cannot redirect `chmod` to an unrelated file while exact modes remain independent of umask; thanks @yetval for reporting this (#86).
910
- Bound fallback Windows owner and ACL command execution to 10 seconds per process and report owner-query failures as unverified instead of returning a partial permission classification; thanks @Yigtwxx for the diagnosis.
@@ -13,7 +14,7 @@
1314
### Compatibility
1415

1516
- Report access-denied failures from native Windows operations as `EPERM` rather than `EACCES`, matching Node/libuv and the JavaScript fallback. Consumers that matched the previous native-only `EACCES` code should accept `EPERM` as well when supporting older package versions.
16-
- Add an optional `fchmodSync` operation to the injectable synchronous atomic-replacement filesystem type. Async adapters need no new member because their required `open()` returns a mode-capable `FileHandle`; custom sync adapters that pass `mode` or `preserveExistingMode` now fail before mutation when `fchmodSync` is absent, while adapters that request neither option remain compatible.
17+
- Add an optional `fchmodSync` operation to the injectable synchronous atomic-replacement filesystem type. Async adapters need no new member because their required `open()` returns a mode-capable `FileHandle`; custom sync adapters that pass `mode`, `dirMode`, or `preserveExistingMode` now fail before mutation when `fchmodSync` is absent, while plain `node:fs` injection and adapters that request none of those options remain compatible.
1718
- Classify `not-found`, `not-empty` and `not-removable` as operational rather than policy errors, so `FsSafeError.category` no longer reports routine filesystem outcomes as safety-policy rejections.
1819

1920
### Features

‎docs/atomic.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import {
1414

1515
## `replaceFileAtomic` / `replaceFileAtomicSync`
1616

17-
Write `content` to a sibling temp file in the destination directory, apply the final mode through its still-open descriptor, optionally `fsync` that descriptor, optionally `fsync` the parent directory after rename, then atomically rename over the destination. No permission change follows the caller-supplied destination path after publication.
17+
Write `content` to a sibling temp file in the destination directory, apply the parent-directory and final file modes through verified descriptors, optionally `fsync` the file descriptor, optionally `fsync` the parent directory after rename, then atomically rename over the destination. No permission change follows a caller-supplied pathname.
18+
19+
On POSIX, the parent is opened with no-follow and directory-only flags, checked against its pre-open identity, and mode-adjusted through that descriptor. A replacement symlink is rejected rather than followed. If the directory cannot be opened for descriptor access, the operation fails closed instead of retrying by pathname. Windows does not enforce POSIX directory modes and Node cannot consistently open directory descriptors there, so `dirMode` is passed only to `mkdir`; no pathname `chmod` fallback is attempted.
1820

1921
Async replacements to the same destination are serialized inside the current process, so two overlapping `replaceFileAtomic()` calls do not interleave their temp-write/rename phases. Use a sidecar lock when multiple processes may write the same target.
2022

@@ -36,7 +38,7 @@ await replaceFileAtomic({
3638
type ReplaceFileAtomicOptions = {
3739
filePath: string; // destination
3840
content: string | Uint8Array;
39-
dirMode?: number; // mode for parent dirs created by the helper
41+
dirMode?: number; // parent-directory mode (POSIX; default 0o700)
4042
mode?: number; // explicit mode for the new file (e.g. 0o600)
4143
preserveExistingMode?: boolean; // copy mode from existing destination, when present
4244
tempPrefix?: string;
@@ -212,7 +214,7 @@ await replaceFileAtomic({
212214
});
213215
```
214216

215-
The synchronous injectable interface adds one optional descriptor-mode operation:
217+
The synchronous injectable interface has one optional descriptor-mode operation:
216218

217219
```ts
218220
type ReplaceFileAtomicSyncFileSystem = {
@@ -221,7 +223,7 @@ type ReplaceFileAtomicSyncFileSystem = {
221223
};
222224
```
223225

224-
The async interface already requires `open()`, whose `FileHandle` supplies `chmod()`, so injecting `node:fs` or another conforming adapter needs no new async member. A custom synchronous filesystem that passes `mode` or `preserveExistingMode` must supply `fchmodSync`; omission fails before any file is created and never falls back to `chmod(destination)`. Existing synchronous adapters that request neither option may omit it. Copy fallback applies the mode through its pinned destination descriptor as well, preserving exact modes despite the process umask.
226+
The async interface already requires `open()`, whose `FileHandle` supplies `chmod()`, so injecting `node:fs` or another conforming adapter needs no new async member. On POSIX, that `open()` must support no-follow directory descriptors as Node does. A custom synchronous filesystem that passes `mode`, `dirMode`, or `preserveExistingMode` must supply `fchmodSync`; omission fails before any file or directory is created and never falls back to a pathname `chmod`. Existing synchronous adapters that request none of those options may omit it. Injecting plain `node:fs` supports explicit file and directory modes. Copy fallback applies the file mode through its pinned destination descriptor as well, preserving exact modes despite the process umask.
225227

226228
## See also
227229

‎src/replace-file-descriptor.ts‎

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,85 @@
11
import syncFs, { type Stats } from "node:fs";
22
import fs, { type FileHandle } from "node:fs/promises";
3+
import { FsSafeError } from "./errors.js";
4+
import { sameFileIdentity } from "./file-identity.js";
35

4-
type AsyncTempFileSystem = Pick<typeof fs, "open" | "writeFile">;
6+
type AsyncTempFileSystem = Pick<typeof fs, "lstat" | "open" | "writeFile">;
57
type SyncTempFileSystem = Pick<
68
typeof syncFs,
7-
"closeSync" | "fstatSync" | "fsyncSync" | "openSync" | "writeFileSync"
9+
"closeSync" | "fstatSync" | "fsyncSync" | "lstatSync" | "openSync" | "writeFileSync"
810
>;
911

1012
export type SyncFchmod = (fd: number, mode: number) => void;
1113

14+
function directoryOpenFlags(): number {
15+
return (
16+
syncFs.constants.O_RDONLY |
17+
syncFs.constants.O_DIRECTORY |
18+
syncFs.constants.O_NOFOLLOW |
19+
syncFs.constants.O_NONBLOCK
20+
);
21+
}
22+
23+
function assertDirectory(identity: Stats, dirPath: string): void {
24+
if (identity.isSymbolicLink() || !identity.isDirectory()) {
25+
throw new FsSafeError("not-file", `Atomic replace parent must be a real directory: ${dirPath}`);
26+
}
27+
}
28+
29+
function assertSameDirectory(expected: Stats, opened: Stats, dirPath: string): void {
30+
assertDirectory(opened, dirPath);
31+
if (!sameFileIdentity(expected, opened)) {
32+
throw new FsSafeError(
33+
"path-mismatch",
34+
`Atomic replace parent changed before its mode could be applied: ${dirPath}`,
35+
);
36+
}
37+
}
38+
39+
export async function applyDirectoryMode(params: {
40+
fsModule: AsyncTempFileSystem;
41+
dirPath: string;
42+
mode: number;
43+
}): Promise<void> {
44+
// Node does not enforce POSIX directory modes on Windows, and its directory
45+
// descriptors are not consistently openable. mkdir(mode) remains the only
46+
// bounded behavior there; never fall back to a pathname chmod.
47+
if (process.platform === "win32") {
48+
return;
49+
}
50+
51+
const expected = await params.fsModule.lstat(params.dirPath);
52+
assertDirectory(expected, params.dirPath);
53+
const handle = await params.fsModule.open(params.dirPath, directoryOpenFlags());
54+
try {
55+
assertSameDirectory(expected, await handle.stat(), params.dirPath);
56+
await handle.chmod(params.mode);
57+
} finally {
58+
await handle.close();
59+
}
60+
}
61+
62+
export function applyDirectoryModeSync(params: {
63+
fsModule: SyncTempFileSystem;
64+
dirPath: string;
65+
mode: number;
66+
fchmodSync?: SyncFchmod;
67+
}): void {
68+
if (process.platform === "win32" || !params.fchmodSync) {
69+
return;
70+
}
71+
72+
const expected = params.fsModule.lstatSync(params.dirPath);
73+
assertDirectory(expected, params.dirPath);
74+
const fd = params.fsModule.openSync(params.dirPath, directoryOpenFlags());
75+
try {
76+
assertSameDirectory(expected, params.fsModule.fstatSync(fd), params.dirPath);
77+
params.fchmodSync(fd, params.mode);
78+
} finally {
79+
params.fsModule.closeSync(fd);
80+
}
81+
}
82+
1283
export async function writeTempFile(params: {
1384
fsModule: AsyncTempFileSystem;
1485
tempPath: string;

‎src/replace-file.ts‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
type ReplaceFileDestinationHardlinkPolicy,
1515
} from "./replace-file-copy-fallback.js";
1616
import {
17+
applyDirectoryMode,
18+
applyDirectoryModeSync,
1719
type SyncFchmod,
1820
writeTempFile,
1921
writeTempFileSync,
@@ -26,7 +28,6 @@ export type ReplaceFileAtomicFileSystem = {
2628
promises: Pick<
2729
typeof fs,
2830
| "mkdir"
29-
| "chmod"
3031
| "writeFile"
3132
| "rename"
3233
| "copyFile"
@@ -41,7 +42,6 @@ export type ReplaceFileAtomicFileSystem = {
4142
export type ReplaceFileAtomicSyncFileSystem = Pick<
4243
typeof syncFs,
4344
| "mkdirSync"
44-
| "chmodSync"
4545
| "readFileSync"
4646
| "writeFileSync"
4747
| "renameSync"
@@ -251,7 +251,7 @@ function resolveModeSync(options: ReplaceFileAtomicSyncOptions): number {
251251

252252
function missingFchmodSyncError(): TypeError {
253253
return new TypeError(
254-
"fileSystem.fchmodSync is required when mode or preserveExistingMode is specified",
254+
"fileSystem.fchmodSync is required when mode, dirMode, or preserveExistingMode is specified",
255255
);
256256
}
257257

@@ -332,7 +332,7 @@ async function replaceFileAtomicUnserialized(
332332
let tempExists = false;
333333
let originalError: unknown;
334334
await fsModule.mkdir(dir, { recursive: true, mode: dirMode });
335-
await fsModule.chmod(dir, dirMode).catch(() => undefined);
335+
await applyDirectoryMode({ fsModule, dirPath: dir, mode: dirMode });
336336
try {
337337
tempExists = true;
338338
unregisterTempPath.setIdentity(await writeTempFile({
@@ -392,19 +392,20 @@ export function replaceFileAtomicSync(
392392
const fchmodSync = options.fileSystem?.fchmodSync ?? (
393393
options.fileSystem === undefined ? syncFs.fchmodSync : undefined
394394
);
395-
if (!fchmodSync && (options.mode !== undefined || options.preserveExistingMode === true)) {
395+
if (
396+
!fchmodSync &&
397+
(options.mode !== undefined ||
398+
options.preserveExistingMode === true ||
399+
(process.platform !== "win32" && options.dirMode !== undefined))
400+
) {
396401
throw missingFchmodSyncError();
397402
}
398403
const tempPath = buildReplaceTempPath(filePath, options.tempPrefix);
399404
const unregisterTempPath = registerTempPathForExit(tempPath);
400405
let tempExists = false;
401406
let originalError: unknown;
402407
fsModule.mkdirSync(dir, { recursive: true, mode: dirMode });
403-
try {
404-
fsModule.chmodSync(dir, dirMode);
405-
} catch {
406-
// Best-effort on platforms that do not enforce POSIX modes.
407-
}
408+
applyDirectoryModeSync({ fsModule, dirPath: dir, mode: dirMode, fchmodSync });
408409
try {
409410
tempExists = true;
410411
unregisterTempPath.setIdentity(writeTempFileSync({

0 commit comments

Comments
 (0)