Skip to content

Commit da387a7

Browse files
authored
fix(atomic): bind replacement modes to descriptors (#91)
replaceFileAtomic() and replaceFileAtomicSync() reached the requested mode with a chmod on the destination path after the rename, so a local user able to write the parent directory could swap in a symlink and redirect the mode change to an unrelated file. The exclusive temp descriptor is now held open across write, mode application, optional fsync and close, before the rename. The copy fallback applies modes through its pinned destination descriptor. No post-publication destination chmod remains. The async path needs no interface change: it applies the mode through the FileHandle returned by the already-required open. The sync path adds an optional fchmodSync, since openSync returns a bare descriptor; adapters that request a mode without providing it fail before mutating anything. Reported by @yetval with a complete reproduction.
1 parent b1132f9 commit da387a7

10 files changed

Lines changed: 356 additions & 61 deletions

‎CHANGELOG.md‎

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

1212
- 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).
1313

14+
### Security and Correctness
15+
16+
- 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).
17+
18+
### Compatibility
19+
20+
- 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.
21+
1422
## 0.5.1 - 2026-08-01
1523

1624
### 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. Async adapters use `chmod()` on the `FileHandle` returned by their required `open()` operation; custom sync adapters using `mode` or `preserveExistingMode` provide the optional descriptor-bound `fchmodSync` operation.
294294

295295
## External outputs
296296

‎docs/atomic.md‎

Lines changed: 13 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.
@@ -212,6 +212,17 @@ await replaceFileAtomic({
212212
});
213213
```
214214

215+
The synchronous injectable interface adds one optional descriptor-mode operation:
216+
217+
```ts
218+
type ReplaceFileAtomicSyncFileSystem = {
219+
// other required operations omitted
220+
fchmodSync?: typeof import("node:fs").fchmodSync;
221+
};
222+
```
223+
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.
225+
215226
## See also
216227

217228
- [`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`. Async adapters use `chmod()` on the `FileHandle` returned by their required `open()` operation. The synchronous type adds optional `fchmodSync(fd, mode)`; custom sync adapters that explicitly request `mode` or `preserveExistingMode` must implement it. See [Atomic writes](atomic.md#test-injection).
6+
57
```ts
68
import type {
79
BasePathOptions,

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,7 @@ export async function copyFallbackReplace(params: {
350350
);
351351
await destHandle.writeFile(replacement);
352352
}
353+
await destHandle.chmod(sourceStat.mode);
353354
} finally {
354355
await destHandle?.close().catch(() => undefined);
355356
await sourceHandle.close().catch(() => undefined);
@@ -364,6 +365,7 @@ export function copyFallbackReplaceSync(params: {
364365
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
365366
restore: ReplaceFileCopyFallbackRestorePolicy;
366367
maxRestoreBytes?: number;
368+
fchmodSync?: (fd: number, mode: number) => void;
367369
}): void {
368370
const sourcePreview = params.fsModule.lstatSync(params.src);
369371
if (sourcePreview.isSymbolicLink() || !sourcePreview.isFile()) {
@@ -421,6 +423,7 @@ export function copyFallbackReplaceSync(params: {
421423
);
422424
writeAllSync(params.fsModule, destFd, replacement);
423425
}
426+
params.fchmodSync?.(destFd, sourceStat.mode);
424427
} finally {
425428
if (destFd !== undefined) {
426429
try {

‎src/replace-file-descriptor.ts‎

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

‎src/replace-file.ts‎

Lines changed: 36 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ import {
1313
type ReplaceFileCopyFallbackRestorePolicy,
1414
type ReplaceFileDestinationHardlinkPolicy,
1515
} from "./replace-file-copy-fallback.js";
16+
import {
17+
type SyncFchmod,
18+
writeTempFile,
19+
writeTempFileSync,
20+
} from "./replace-file-descriptor.js";
1621
import { assertSafePathPrefix } from "./safe-path-segment.js";
1722
import { registerTempPathForExit } from "./temp-cleanup.js";
1823
import { serializePathWrite } from "./write-queue.js";
@@ -52,7 +57,9 @@ export type ReplaceFileAtomicSyncFileSystem = Pick<
5257
| "ftruncateSync"
5358
| "readSync"
5459
| "writeSync"
55-
>;
60+
> & {
61+
fchmodSync?: typeof syncFs.fchmodSync;
62+
};
5663

5764
export type {
5865
ReplaceFileAtomicRestoreCleanup,
@@ -160,6 +167,7 @@ function renameWithRetrySync(params: {
160167
copyFallbackRestore: ReplaceFileCopyFallbackRestorePolicy;
161168
maxRestoreBytes?: number;
162169
destinationHardlinks?: ReplaceFileDestinationHardlinkPolicy;
170+
fchmodSync?: SyncFchmod;
163171
}): ReplaceFileAtomicResult {
164172
for (let attempt = 0; attempt <= params.maxRetries; attempt++) {
165173
try {
@@ -178,6 +186,7 @@ function renameWithRetrySync(params: {
178186
destinationHardlinks: params.destinationHardlinks,
179187
restore: params.copyFallbackRestore,
180188
maxRestoreBytes: params.maxRestoreBytes,
189+
fchmodSync: params.fchmodSync,
181190
});
182191
return { method: "copy-fallback" };
183192
}
@@ -240,30 +249,10 @@ function resolveModeSync(options: ReplaceFileAtomicSyncOptions): number {
240249
return stat ? stat.mode : defaultMode;
241250
}
242251

243-
async function syncTempFile(fsModule: ReplaceFileAtomicFileSystem["promises"], tempPath: string) {
244-
const handle = await fsModule.open(tempPath, "r+");
245-
try {
246-
await handle.sync();
247-
} catch (error) {
248-
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
249-
throw error;
250-
}
251-
} finally {
252-
await handle.close();
253-
}
254-
}
255-
256-
function syncTempFileSync(fsModule: ReplaceFileAtomicSyncFileSystem, tempPath: string): void {
257-
const fd = fsModule.openSync(tempPath, "r+");
258-
try {
259-
fsModule.fsyncSync(fd);
260-
} catch (error) {
261-
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
262-
throw error;
263-
}
264-
} finally {
265-
fsModule.closeSync(fd);
266-
}
252+
function missingFchmodSyncError(): TypeError {
253+
return new TypeError(
254+
"fileSystem.fchmodSync is required when mode or preserveExistingMode is specified",
255+
);
267256
}
268257

269258
async function syncDirectoryBestEffort(
@@ -346,11 +335,13 @@ async function replaceFileAtomicUnserialized(
346335
await fsModule.chmod(dir, dirMode).catch(() => undefined);
347336
try {
348337
tempExists = true;
349-
await fsModule.writeFile(tempPath, options.content, { mode, flag: "wx" });
350-
unregisterTempPath.setIdentity(await fsModule.lstat(tempPath));
351-
if (options.syncTempFile) {
352-
await syncTempFile(fsModule, tempPath);
353-
}
338+
unregisterTempPath.setIdentity(await writeTempFile({
339+
fsModule,
340+
tempPath,
341+
content: options.content,
342+
mode,
343+
sync: options.syncTempFile === true,
344+
}));
354345
if (options.beforeRename) {
355346
await options.beforeRename({ filePath, tempPath });
356347
}
@@ -368,7 +359,6 @@ async function replaceFileAtomicUnserialized(
368359
});
369360
tempExists = false;
370361
unregisterTempPath();
371-
await fsModule.chmod(filePath, mode).catch(() => undefined);
372362
if (options.syncParentDir) {
373363
await syncDirectoryBestEffort(fsModule, dir);
374364
}
@@ -399,6 +389,12 @@ export function replaceFileAtomicSync(
399389
const dir = path.dirname(filePath);
400390
const dirMode = options.dirMode ?? 0o700;
401391
const mode = resolveModeSync(options);
392+
const fchmodSync = options.fileSystem?.fchmodSync ?? (
393+
options.fileSystem === undefined ? syncFs.fchmodSync : undefined
394+
);
395+
if (!fchmodSync && (options.mode !== undefined || options.preserveExistingMode === true)) {
396+
throw missingFchmodSyncError();
397+
}
402398
const tempPath = buildReplaceTempPath(filePath, options.tempPrefix);
403399
const unregisterTempPath = registerTempPathForExit(tempPath);
404400
let tempExists = false;
@@ -411,11 +407,14 @@ export function replaceFileAtomicSync(
411407
}
412408
try {
413409
tempExists = true;
414-
fsModule.writeFileSync(tempPath, options.content, { mode, flag: "wx" });
415-
unregisterTempPath.setIdentity(fsModule.lstatSync(tempPath));
416-
if (options.syncTempFile) {
417-
syncTempFileSync(fsModule, tempPath);
418-
}
410+
unregisterTempPath.setIdentity(writeTempFileSync({
411+
fsModule,
412+
tempPath,
413+
content: options.content,
414+
mode,
415+
fchmodSync,
416+
sync: options.syncTempFile === true,
417+
}));
419418
if (options.beforeRename) {
420419
options.beforeRename({ filePath, tempPath });
421420
}
@@ -430,14 +429,10 @@ export function replaceFileAtomicSync(
430429
copyFallbackRestore: options.copyFallbackRestore ?? "none",
431430
maxRestoreBytes: options.maxRestoreBytes,
432431
destinationHardlinks: options.destinationHardlinks,
432+
fchmodSync,
433433
});
434434
tempExists = false;
435435
unregisterTempPath();
436-
try {
437-
fsModule.chmodSync(filePath, mode);
438-
} catch {
439-
// Best-effort on platforms that do not enforce POSIX modes.
440-
}
441436
if (options.syncParentDir) {
442437
syncDirectoryBestEffortSync(fsModule, dir);
443438
}

0 commit comments

Comments
 (0)