Skip to content

Commit 1d037a2

Browse files
committed
fix: bind atomic file modes to descriptors
1 parent 2477f56 commit 1d037a2

10 files changed

Lines changed: 383 additions & 62 deletions

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66

77
- Suffix Windows reserved basenames with `_` in `sanitizeUntrustedFileName()` while preserving case and extensions on every platform, including dollar names and superscript COM/LPT variants; thanks @SebTardif (#67).
88

9+
### Security and Correctness
10+
11+
- 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).
12+
13+
### Compatibility
14+
15+
- Add optional `promises.fchmod` and `fchmodSync` operations to the injectable atomic-replacement filesystem types. Custom adapters that pass `mode` or `preserveExistingMode` must implement the matching descriptor operation and now fail before mutation when it is absent; adapters that request neither option remain compatible.
16+
917
## 0.5.1 - 2026-08-01
1018

1119
### Security and Correctness

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ publication policy, creation callback, and platform contract.
276276

277277
## Atomic writes
278278

279-
`replaceFileAtomic()` writes a sibling temp file, optionally fsyncs it, and renames it over the destination. Mode preservation, pinned-destination hardlink rejection, rename retry / copy fallback on `EPERM`, bounded original-content restoration after a torn fallback, parent-directory fsync, and a `beforeRename` hook for backup or observer flows are all opt-in. `movePathWithCopyFallback()` stages cross-device moves before commit and removes only the copied source entries, so concurrent source additions or replacements are preserved.
279+
`replaceFileAtomic()` writes a sibling temp file, applies its exact mode through the still-open descriptor, optionally fsyncs it, and renames it over the destination. It never follows the published destination path to set file permissions. Mode preservation, pinned-destination hardlink rejection, rename retry / copy fallback on `EPERM`, bounded original-content restoration after a torn fallback, parent-directory fsync, and a `beforeRename` hook for backup or observer flows are all opt-in. `movePathWithCopyFallback()` stages cross-device moves before commit and removes only the copied source entries, so concurrent source additions or replacements are preserved.
280280

281281
```ts
282282
import { replaceFileAtomic } from "@openclaw/fs-safe/atomic";
@@ -290,7 +290,7 @@ await replaceFileAtomic({
290290
});
291291
```
292292

293-
`replaceFileAtomicSync()` covers the synchronous case with the same options shape. Both accept an injectable `fileSystem` for tests.
293+
`replaceFileAtomicSync()` covers the synchronous case with the same options shape. Both accept an injectable `fileSystem` for tests; custom adapters using `mode` or `preserveExistingMode` provide the optional descriptor-bound `promises.fchmod` or `fchmodSync` operation.
294294

295295
## External outputs
296296

‎docs/atomic.md‎

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

1515
## `replaceFileAtomic` / `replaceFileAtomicSync`
1616

17-
Write `content` to a sibling temp file in the destination directory, optionally `fsync` the temp file, optionally `fsync` the parent directory after rename, then atomically rename over the destination.
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.
1818

1919
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.
2020

@@ -121,7 +121,7 @@ Use it when callers must see a whole staged tree at the target path. For single-
121121
## `writeTextAtomic`
122122

123123
Atomic UTF-8 text write with the same secure defaults as `writeJson`: sibling
124-
temp file, temp fsync, rename, parent fsync, and final chmod best-effort.
124+
temp file, descriptor-bound mode setting and fsync, rename, and parent fsync.
125125
It delegates to `replaceFileAtomic()` with a smaller call shape. Use it when
126126
you do not need replacement hooks such as `beforeRename`, `preserveExistingMode`,
127127
or custom copy-fallback policy.
@@ -205,13 +205,32 @@ await replaceFileAtomic({
205205
fileSystem: {
206206
promises: {
207207
...realFs,
208+
fchmod: async (handle, mode) => handle.chmod(mode),
208209
writeFile: async (...args) => { ops.push("write"); return realFs.writeFile(...args); },
209210
rename: async (...args) => { ops.push("rename"); return realFs.rename(...args); },
210211
},
211212
},
212213
});
213214
```
214215

216+
The injectable interfaces add optional descriptor-mode operations:
217+
218+
```ts
219+
type ReplaceFileAtomicFileSystem = {
220+
promises: {
221+
// other required operations omitted
222+
fchmod?: (handle: import("node:fs/promises").FileHandle, mode: number) => Promise<void>;
223+
};
224+
};
225+
226+
type ReplaceFileAtomicSyncFileSystem = {
227+
// other required operations omitted
228+
fchmodSync?: typeof import("node:fs").fchmodSync;
229+
};
230+
```
231+
232+
The built-in filesystem always applies the resolved mode through the temporary file descriptor. A custom filesystem that passes `mode` or `preserveExistingMode` must supply the matching descriptor operation; omission fails before any file is created and never falls back to `chmod(destination)`. Existing custom filesystems that request neither option may omit the new member. Copy fallback applies the mode through its pinned destination descriptor as well, preserving exact modes despite the process umask.
233+
215234
## See also
216235

217236
- [`root()`](root.md) — when you want method-style writes with the boundary baked in.

‎docs/types.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
The types most callers reach for. Shared data shapes are exported from `@openclaw/fs-safe/types`; method-specific option/result types live next to their subpath.
44

5+
For atomic replacement, `ReplaceFileAtomicFileSystem` and `ReplaceFileAtomicSyncFileSystem` are exported from `@openclaw/fs-safe/atomic`. Their optional `promises.fchmod(handle, mode)` and `fchmodSync(fd, mode)` members let injected filesystems apply exact modes through pinned descriptors. Custom adapters that explicitly request `mode` or `preserveExistingMode` must implement the corresponding member; see [Atomic writes](atomic.md#test-injection).
6+
57
```ts
68
import type {
79
BasePathOptions,

‎src/replace-file-copy-fallback.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ export async function copyFallbackReplace(params: {
300300
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
301301
restore: ReplaceFileCopyFallbackRestorePolicy;
302302
maxRestoreBytes?: number;
303+
fchmod?: (handle: FileHandle, mode: number) => Promise<void>;
303304
}): Promise<void> {
304305
const sourcePreview = await params.fsModule.lstat(params.src);
305306
if (sourcePreview.isSymbolicLink() || !sourcePreview.isFile()) {
@@ -350,6 +351,9 @@ export async function copyFallbackReplace(params: {
350351
);
351352
await destHandle.writeFile(replacement);
352353
}
354+
if (params.fchmod) {
355+
await params.fchmod(destHandle, sourceStat.mode);
356+
}
353357
} finally {
354358
await destHandle?.close().catch(() => undefined);
355359
await sourceHandle.close().catch(() => undefined);
@@ -364,6 +368,7 @@ export function copyFallbackReplaceSync(params: {
364368
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
365369
restore: ReplaceFileCopyFallbackRestorePolicy;
366370
maxRestoreBytes?: number;
371+
fchmodSync?: (fd: number, mode: number) => void;
367372
}): void {
368373
const sourcePreview = params.fsModule.lstatSync(params.src);
369374
if (sourcePreview.isSymbolicLink() || !sourcePreview.isFile()) {
@@ -421,6 +426,7 @@ export function copyFallbackReplaceSync(params: {
421426
);
422427
writeAllSync(params.fsModule, destFd, replacement);
423428
}
429+
params.fchmodSync?.(destFd, sourceStat.mode);
424430
} finally {
425431
if (destFd !== undefined) {
426432
try {

‎src/replace-file-descriptor.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import syncFs, { type Stats } from "node:fs";
2+
import fs, { type FileHandle } from "node:fs/promises";
3+
4+
type AsyncTempFileSystem = Pick<typeof fs, "open" | "writeFile">;
5+
type SyncTempFileSystem = Pick<
6+
typeof syncFs,
7+
"closeSync" | "fstatSync" | "fsyncSync" | "openSync" | "writeFileSync"
8+
>;
9+
10+
export type AsyncFchmod = (handle: FileHandle, mode: number) => Promise<void>;
11+
export type SyncFchmod = (fd: number, mode: number) => void;
12+
13+
export async function writeTempFile(params: {
14+
fsModule: AsyncTempFileSystem;
15+
tempPath: string;
16+
content: string | Uint8Array;
17+
mode: number;
18+
fchmod?: AsyncFchmod;
19+
sync: boolean;
20+
}): Promise<Stats> {
21+
const handle = await params.fsModule.open(params.tempPath, "wx", params.mode);
22+
try {
23+
await params.fsModule.writeFile(handle, params.content);
24+
if (params.fchmod) {
25+
await params.fchmod(handle, params.mode);
26+
}
27+
if (params.sync) {
28+
try {
29+
await handle.sync();
30+
} catch (error) {
31+
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
32+
throw error;
33+
}
34+
}
35+
}
36+
return await handle.stat();
37+
} finally {
38+
await handle.close();
39+
}
40+
}
41+
42+
export function writeTempFileSync(params: {
43+
fsModule: SyncTempFileSystem;
44+
tempPath: string;
45+
content: string | Uint8Array;
46+
mode: number;
47+
fchmodSync?: SyncFchmod;
48+
sync: boolean;
49+
}): Stats {
50+
const fd = params.fsModule.openSync(params.tempPath, "wx", params.mode);
51+
try {
52+
params.fsModule.writeFileSync(fd, params.content);
53+
params.fchmodSync?.(fd, params.mode);
54+
if (params.sync) {
55+
try {
56+
params.fsModule.fsyncSync(fd);
57+
} catch (error) {
58+
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
59+
throw error;
60+
}
61+
}
62+
}
63+
return params.fsModule.fstatSync(fd);
64+
} finally {
65+
params.fsModule.closeSync(fd);
66+
}
67+
}

0 commit comments

Comments
 (0)