Skip to content

Commit 22f5862

Browse files
committed
feat: harden atomic replacement and output staging
1 parent b1be2a1 commit 22f5862

13 files changed

Lines changed: 1179 additions & 120 deletions

‎CHANGELOG.md‎

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

1414
### Security and Correctness
1515

16+
- Add pinned-destination hardlink rejection and bounded original-content restoration to `replaceFileAtomic()` and its sync variant, including typed `restored` / `restore-failed` receipts for torn copy-fallback writes.
17+
- Add sibling staging to `writeExternalFileWithinRoot()`: external producers can write a randomized file in the target directory for fsynced same-filesystem atomic replacement, while private workspace staging remains the cross-device-tolerant default.
1618
- Enforce `movePathWithCopyFallback({ sourceHardlinks: "reject" })` with a streaming, entry-capped recursive preflight before mutation, closing a shipped 0.4.x gap where the common same-filesystem rename bypassed the policy; approved trees commit through a fresh staged copy with open-time and post-copy link-count fences so a scan/rename race cannot publish a hardlinked inode.
1719
- Abort and tear down JavaScript TAR extraction immediately when entry policy, path validation, link rejection, or a budget fails, preventing node-tar from leaving a paused parser after rejected fleet-restore entries; both native and JavaScript paths now return the same typed archive-policy errors.
1820
- Attach a post-creation failure receipt to `publishFileExclusive()` errors with the failing phase, whether this call created the target, its observed identity, and whether cleanup removed, preserved, or could not classify the target.

‎README.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ publication policy, creation callback, and platform contract.
268268

269269
## Atomic writes
270270

271-
`replaceFileAtomic()` writes a sibling temp file, optionally fsyncs it, and renames it over the destination. Mode preservation, rename retry / copy fallback on `EPERM`, 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.
271+
`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.
272272

273273
```ts
274274
import { replaceFileAtomic } from "@openclaw/fs-safe/atomic";
@@ -295,16 +295,19 @@ import { writeExternalFileWithinRoot } from "@openclaw/fs-safe/output";
295295
await writeExternalFileWithinRoot({
296296
rootDir: "/safe/workspace/downloads",
297297
path: "reports/today.pdf",
298+
staging: "sibling",
298299
write: async (filePath) => {
299300
await download.saveAs(filePath);
300301
},
301302
});
302303
```
303304

304-
The callback receives a private temp file path, not the final destination. After
305-
the callback returns, fs-safe finalizes the staged file with `Root.copyIn()`,
306-
creating missing parents by default and rejecting traversal, symlink parent
307-
escapes, hardlinked final targets, and size-limit violations.
305+
The callback receives a staged path, not the final destination. The default
306+
`"workspace"` mode uses private temp storage plus `Root.copyIn()` for
307+
cross-device-tolerant finalization. `"sibling"` stages in the target directory,
308+
fsyncs the completed file, and atomically renames it over the target. Choose it
309+
when the destination directory is itself the writable boundary and atomic
310+
replacement matters.
308311

309312
Use it when the final filename is known before the external writer runs. If the
310313
filename depends on sniffing the produced bytes, write to a private temp

‎docs/atomic.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ type ReplaceFileAtomicOptions = {
4343
renameMaxRetries?: number;
4444
renameRetryBaseDelayMs?: number;
4545
copyFallbackOnPermissionError?: boolean;
46+
copyFallbackRestore?: "restore-original" | "none"; // default: "none"
47+
maxRestoreBytes?: number; // required with "restore-original"
48+
destinationHardlinks?: "reject";
4649
syncTempFile?: boolean; // fsync(temp) before rename
4750
syncParentDir?: boolean; // fsync(parent) after rename (POSIX only)
4851
beforeRename?: (params: { filePath: string; tempPath: string }) => Promise<void>;
@@ -75,6 +78,25 @@ with exclusive/no-follow flags where the platform supports them, and refuses
7578
known symlink destinations so it does not write through a replaced destination
7679
link.
7780

81+
Set `destinationHardlinks: "reject"` when an existing regular-file destination
82+
must not have aliases. The policy reads `nlink` from a pinned destination
83+
descriptor, not pathname metadata, before rename and rechecks it in the copy
84+
fallback.
85+
86+
The default `copyFallbackRestore: "none"` preserves the existing fallback
87+
contract: a failed copy can leave a partial destination. For state files where
88+
preserving the old bytes is more important, choose `"restore-original"` and set
89+
an explicit `maxRestoreBytes` memory budget. If the destination exists, fs-safe
90+
snapshots it through a pinned descriptor, overwrites through that same
91+
descriptor, and synchronizes the result. Any write or sync failure triggers a
92+
restore and another sync through the same descriptor.
93+
94+
Restore failures are `FsSafeError("helper-failed")` values with typed
95+
`details.cleanup` set to `"restored"` or `"restore-failed"`. An original larger
96+
than `maxRestoreBytes` fails with `too-large` before mutation. A missing
97+
destination has no original to restore and follows the exclusive-create copy
98+
fallback.
99+
78100
### Sync variant
79101

80102
`replaceFileAtomicSync` accepts the same options shape, with the obvious removal of the async-only hooks. Use it inside synchronous boot paths or test setup code.

‎docs/durability.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,38 @@ modified. Clone support is filesystem- and mount-dependent, so callers must
147147
not infer durability or physical independence from timing; an unsupported
148148
clone or `copy_file_range` transparently continues down the fallback chain.
149149

150+
## Recoverable atomic-replace fallback
151+
152+
`replaceFileAtomic()` normally publishes a synchronized sibling temp with an
153+
atomic rename. Some Windows filesystems and file owners reject that rename with
154+
`EPERM` or `EEXIST`; `copyFallbackOnPermissionError: true` permits a non-atomic
155+
copy fallback.
156+
157+
Callers that cannot tolerate a torn in-place fallback can add:
158+
159+
```ts
160+
await replaceFileAtomic({
161+
filePath: statePath,
162+
content: nextState,
163+
syncTempFile: true,
164+
syncParentDir: true,
165+
copyFallbackOnPermissionError: true,
166+
copyFallbackRestore: "restore-original",
167+
maxRestoreBytes: 4 * 1024 * 1024,
168+
destinationHardlinks: "reject",
169+
});
170+
```
171+
172+
The existing regular-file destination is pinned before its link count is
173+
accepted. Its original bytes are read within `maxRestoreBytes`, then the new
174+
bytes are written and synchronized through the same descriptor. If a write or
175+
sync tears, fs-safe rewrites the snapshot and fsyncs it before throwing. Inspect
176+
`details.cleanup`: `"restored"` means the original bytes were put back and
177+
synchronized; `"restore-failed"` means the replacement and recovery both
178+
failed, so the destination must be treated as indeterminate. This is recovery
179+
from a live-process I/O failure, not a transaction or a substitute for an
180+
application backup protocol.
181+
150182
## Streaming SHA-256
151183

152184
`sha256File()` hashes either a pathname string or an already-open Node

‎docs/errors.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ target identity, cleanup decision, and failed directory-sync outcome. Narrow
3131
by `code` and a documented details field before consuming it; do not assume all
3232
`FsSafeError` instances carry the same keys.
3333

34+
`replaceFileAtomic({ copyFallbackRestore: "restore-original" })` reports a
35+
failed copy fallback with the exported `ReplaceFileAtomicRestoreFailureDetails`
36+
shape:
37+
38+
```ts
39+
type ReplaceFileAtomicRestoreFailureDetails = {
40+
cleanup: "restored" | "restore-failed";
41+
};
42+
```
43+
44+
Both outcomes use `code: "helper-failed"`. `"restored"` means the original
45+
snapshot was written back and fsynced through the pinned destination handle.
46+
`"restore-failed"` means both the replacement and recovery failed; `cause` is
47+
an `AggregateError` containing both failures. A snapshot that exceeds
48+
`maxRestoreBytes` fails earlier with `too-large` and does not overwrite the
49+
destination.
50+
3451
`category` separates caller-policy failures from operational failures:
3552

3653
- `"policy"` — unsafe input or target state, such as `outside-workspace`, `symlink`, `hardlink`, or `too-large`.

‎docs/output.md‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ await writeExternalFileWithinRoot({
1616
});
1717
```
1818

19-
The external writer never receives the final destination path. It receives a
20-
private temp file path instead. After the callback returns, fs-safe copies that
21-
staged file into the requested target through the same root boundary used by
22-
`Root.copyIn()`.
19+
The external writer receives a staged path instead of the final destination.
20+
The default private-workspace mode finalizes through `Root.copyIn()`. An
21+
opt-in sibling mode stages in the destination directory and atomically renames
22+
the completed file over the target.
2323

2424
## Signature
2525

@@ -34,6 +34,8 @@ type ExternalFileWriteOptions<T = void> = {
3434
write: (filePath: string) => Promise<T>;
3535
maxBytes?: number;
3636
mode?: number;
37+
staging?: "workspace" | "sibling"; // default: "workspace"
38+
fallbackFileName?: string; // safe staged-name fallback
3739
};
3840

3941
type ExternalFileWriteResult<T = void> = {
@@ -46,18 +48,40 @@ The requested `path` must name a file. Missing destination parents are created
4648
by the helper because the operation is "produce this output file under the
4749
root"; callers should choose the filename before calling this API.
4850

49-
Use `maxBytes` when the external producer can create arbitrarily large files.
50-
Use `mode` when the finalized file needs a specific POSIX mode. Both are
51-
enforced during the `Root.copyIn()` finalization step, after the external writer
52-
has produced the staged file and before the final target is committed.
51+
Use `maxBytes` when the external producer can create arbitrarily large files,
52+
and `mode` when the finalized file needs a specific POSIX mode. Both staging
53+
modes enforce them after the producer returns and before committing the target.
54+
`fallbackFileName` supplies the sanitized staged-file tail when the requested
55+
target basename sanitizes to an empty or special name; it does not rename the
56+
final target.
57+
58+
## Choosing a staging mode
59+
60+
`staging: "workspace"` is the default. The producer writes in private temp
61+
storage, then fs-safe copies through the guarded root boundary. Choose it when
62+
the temp and destination filesystems may differ, or when an externally produced
63+
partial file must never appear in the destination directory. The final target
64+
still appears only after guarded finalization.
65+
66+
`staging: "sibling"` gives the producer a randomized temp path in the target
67+
directory. Choose it only when that directory itself is the approved writable
68+
boundary and same-filesystem atomic replacement is required. After the callback
69+
returns, fs-safe pins and validates the staged regular file, rejects hardlinks
70+
and size-limit violations, applies `mode`, fsyncs it, and atomically renames it
71+
over the target. Existing files and symlink entries are replaced without
72+
following their contents or referents. The parent identity is guarded across
73+
the operation and the parent directory is synchronized best-effort after
74+
rename.
5375

5476
## Why not pass the final path to the library?
5577

5678
If a target parent can be swapped after validation, handing an external library
5779
the final path can make the library write outside the intended root before
58-
fs-safe has a chance to finalize or reject the operation. This helper stages in
59-
a private temp workspace first, then finalizes with `Root.copyIn()`. That keeps
60-
the trust-boundary write inside fs-safe's root-aware copy/atomic-write path.
80+
fs-safe has a chance to finalize or reject the operation. Workspace staging
81+
keeps the trust-boundary write inside fs-safe's root-aware copy/atomic-write
82+
path. Sibling staging intentionally shifts the writable boundary to the
83+
destination directory, while keeping pathname validation, staged-file identity
84+
checks, and the final rename under fs-safe's control.
6185

6286
## Browser download example
6387

‎src/atomic.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ export {
33
replaceFileAtomicSync,
44
type ReplaceFileAtomicFileSystem,
55
type ReplaceFileAtomicOptions,
6+
type ReplaceFileAtomicRestoreCleanup,
7+
type ReplaceFileAtomicRestoreFailureDetails,
68
type ReplaceFileAtomicResult,
9+
type ReplaceFileCopyFallbackRestorePolicy,
10+
type ReplaceFileDestinationHardlinkPolicy,
711
type ReplaceFileAtomicSyncFileSystem,
812
type ReplaceFileAtomicSyncOptions,
913
} from "./replace-file.js";

‎src/output-sibling.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import { randomUUID } from "node:crypto";
2+
import fsSync from "node:fs";
3+
import fs, { type FileHandle } from "node:fs/promises";
4+
import path from "node:path";
5+
import { createAsyncDirectoryGuard } from "./directory-guard.js";
6+
import { syncDirectoryBestEffort } from "./directory-durability.js";
7+
import { FsSafeError } from "./errors.js";
8+
import { sameFileIdentity } from "./file-identity.js";
9+
import { withAsyncDirectoryGuards } from "./guarded-mutation.js";
10+
import { sanitizeUntrustedFileName } from "./filename.js";
11+
import { registerTempPathForExit } from "./temp-cleanup.js";
12+
import { serializePathWrite } from "./write-queue.js";
13+
14+
const OPEN_READ_WRITE_NOFOLLOW =
15+
fsSync.constants.O_RDWR |
16+
(process.platform !== "win32" && typeof fsSync.constants.O_NOFOLLOW === "number"
17+
? fsSync.constants.O_NOFOLLOW
18+
: 0);
19+
20+
function safeFallbackFileName(fallbackFileName?: string): string {
21+
return sanitizeUntrustedFileName(fallbackFileName ?? "output.bin", "output.bin");
22+
}
23+
24+
function buildSiblingTempPath(targetPath: string, fallbackFileName?: string): string {
25+
const safeTail = sanitizeUntrustedFileName(
26+
path.basename(targetPath),
27+
safeFallbackFileName(fallbackFileName),
28+
);
29+
return path.join(
30+
path.dirname(targetPath),
31+
`.fs-safe-output-${process.pid}-${randomUUID()}-${safeTail}.part`,
32+
);
33+
}
34+
35+
function assertStagedFile(
36+
pathname: Awaited<ReturnType<typeof fs.lstat>>,
37+
opened: Awaited<ReturnType<FileHandle["stat"]>>,
38+
maxBytes?: number,
39+
): void {
40+
if (pathname.isSymbolicLink() || !pathname.isFile() || !opened.isFile()) {
41+
throw new FsSafeError("not-file", "sibling-staged output must be a regular file");
42+
}
43+
if (!sameFileIdentity(pathname, opened)) {
44+
throw new FsSafeError("path-mismatch", "sibling-staged output changed while opening");
45+
}
46+
if (opened.nlink > 1) {
47+
throw new FsSafeError("hardlink", "hardlinked sibling-staged output not allowed");
48+
}
49+
if (maxBytes !== undefined && opened.size > maxBytes) {
50+
throw new FsSafeError("too-large", `sibling-staged output exceeds maxBytes (${maxBytes})`);
51+
}
52+
}
53+
54+
async function openPinnedStagedFile(
55+
tempPath: string,
56+
maxBytes?: number,
57+
): Promise<{ handle: FileHandle; identity: Awaited<ReturnType<FileHandle["stat"]>> }> {
58+
const preview = await fs.lstat(tempPath);
59+
if (preview.isSymbolicLink()) {
60+
throw new FsSafeError("symlink", "symlink sibling-staged output not allowed");
61+
}
62+
const handle = await fs.open(tempPath, OPEN_READ_WRITE_NOFOLLOW);
63+
try {
64+
const identity = await handle.stat();
65+
assertStagedFile(await fs.lstat(tempPath), identity, maxBytes);
66+
return { handle, identity };
67+
} catch (error) {
68+
await handle.close().catch(() => undefined);
69+
throw error;
70+
}
71+
}
72+
73+
async function syncFile(handle: FileHandle): Promise<void> {
74+
try {
75+
await handle.sync();
76+
} catch (error) {
77+
if ((error as NodeJS.ErrnoException).code !== "EPERM") throw error;
78+
}
79+
}
80+
81+
async function cleanupTempPath(
82+
tempPath: string,
83+
identity?: Awaited<ReturnType<FileHandle["stat"]>>,
84+
): Promise<void> {
85+
try {
86+
const current = await fs.lstat(tempPath);
87+
if (!identity || (!current.isSymbolicLink() && sameFileIdentity(current, identity))) {
88+
await fs.rm(tempPath, { force: true });
89+
}
90+
} catch (error) {
91+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
92+
// Cleanup is best-effort; the randomized path remains inside the writable boundary.
93+
}
94+
}
95+
}
96+
97+
export async function writeExternalFileViaSibling<T>(params: {
98+
finalPath: string;
99+
write: (filePath: string) => Promise<T>;
100+
fallbackFileName?: string;
101+
maxBytes?: number;
102+
mode?: number;
103+
}): Promise<T> {
104+
const finalPath = path.resolve(params.finalPath);
105+
const parentPath = path.dirname(finalPath);
106+
const parentGuard = await createAsyncDirectoryGuard(parentPath);
107+
const tempPath = buildSiblingTempPath(finalPath, params.fallbackFileName);
108+
const unregisterTempPath = registerTempPathForExit(tempPath);
109+
let stagedIdentity: Awaited<ReturnType<FileHandle["stat"]>> | undefined;
110+
let renamed = false;
111+
112+
try {
113+
const result = await params.write(tempPath);
114+
const pinned = await openPinnedStagedFile(tempPath, params.maxBytes);
115+
stagedIdentity = pinned.identity;
116+
unregisterTempPath.setIdentity(stagedIdentity);
117+
try {
118+
if (params.mode !== undefined) {
119+
await pinned.handle.chmod(params.mode);
120+
}
121+
await syncFile(pinned.handle);
122+
await serializePathWrite(finalPath, async () => {
123+
await withAsyncDirectoryGuards([parentGuard], async () => {
124+
const currentIdentity = await pinned.handle.stat();
125+
assertStagedFile(await fs.lstat(tempPath), currentIdentity, params.maxBytes);
126+
if (!sameFileIdentity(currentIdentity, stagedIdentity!)) {
127+
throw new FsSafeError("path-mismatch", "sibling-staged output changed before rename");
128+
}
129+
await fs.rename(tempPath, finalPath);
130+
renamed = true;
131+
const published = await fs.lstat(finalPath);
132+
if (published.isSymbolicLink() || !sameFileIdentity(published, currentIdentity)) {
133+
throw new FsSafeError("path-mismatch", "sibling-staged output changed during rename");
134+
}
135+
});
136+
await syncDirectoryBestEffort(parentPath);
137+
});
138+
} finally {
139+
await pinned.handle.close().catch(() => undefined);
140+
}
141+
return result;
142+
} finally {
143+
if (!renamed) {
144+
await cleanupTempPath(tempPath, stagedIdentity);
145+
}
146+
unregisterTempPath();
147+
}
148+
}

0 commit comments

Comments
 (0)