Skip to content

Commit 2dbd7de

Browse files
committed
fix(write): add renameIdentity option for FUSE mounts with unstable inode numbers
On filesystems like rclone FUSE mounts, rename(2) causes every subsequent path-based lookup on the destination to return a freshly-minted inode number, making the post-rename (dev,ino) identity check always fail even with a single process and zero concurrency. This manifests as a deterministic FsSafeError("path-mismatch") on every overwrite-mode write through writeFileInRoot/runPinnedWriteFallback. Adds renameIdentity: "verify-content-with-lock" to RootDefaults and RootWriteOptions. When set, the write acquires an exclusive sidecar lock for the target path, performs the write under that lock, and verifies by comparing the SHA-256 of the written bytes against the bytes re-read from the target (using an fd-based stat for the returned identity to stay consistent across all subsequent lookups). Stale locks from crashed holders are detected via PID-liveness check and removed automatically. Default behavior is unchanged. Closes #32
1 parent dc0ea4e commit 2dbd7de

8 files changed

Lines changed: 448 additions & 25 deletions

File tree

‎docs/security-model.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ The library does not advertise different security guarantees per platform — it
9090
| Mode bits are not a full policy engine | `replaceFileAtomic` and secret-file helpers set requested modes, but you should still set umask and inspect modes when policy requires it. |
9191
| Archive extraction is path safety, not content safety | Unsafe entry paths and links are rejected; malicious payload contents remain your application layer's problem. |
9292
| Helper failures degrade fd-relative hardening | `helper-unavailable` falls back in `auto` mode and fails closed in `require` mode. Atomicity and identity checks remain, but parent-directory swaps between validation and mutation are less tightly pinned without the helper. |
93+
| FUSE mounts with unstable inode numbers | Some FUSE mounts (rclone is a confirmed example) assign a fresh inode number to a path on every lookup after a rename, making the post-rename `(dev, ino)` identity check always fail. Set `renameIdentity: "verify-content-with-lock"` on the root to use a SHA-256 content comparison under a cooperative sidecar lock instead. This verifies that the correct bytes reached the destination and that no cooperating writer interleaved, but it does not prove that the process owns the resulting file object — a same-UID process that ignores the lock could still interleave. See [Writing](writing.md) for details. |
9394

9495
## Recommended deployment shape
9596

‎docs/writing.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ await fs.write("data/blob.bin", buffer, { mkdir: false }); // override
192192
| `not-found` | Parent does not exist and `mkdir` is false. |
193193
| `not-empty` | `remove()` on a non-empty directory. |
194194
| `not-removable` | `remove()` could not unlink/rmdir (typically permissions or device busy). |
195-
| `path-mismatch` | Post-write fd identity check did not match. Almost always a parallel writer. |
195+
| `path-mismatch` | Post-write fd identity check did not match. Almost always a parallel writer, or a FUSE mount with unstable inode numbers — see `renameIdentity` below. |
196196
| `too-large` | `copyIn()` source exceeded `maxBytes`. |
197197
| `symlink` | A path component is a symlink and policy is `reject`. |
198198
| `hardlink` | `sourceHardlinks: "reject"` saw `nlink > 1`. |
@@ -232,6 +232,24 @@ try {
232232
await fs.append(today, line);
233233
```
234234

235+
## FUSE mounts and unstable inode numbers
236+
237+
Some FUSE mounts — rclone is a confirmed example — assign a fresh inode number to a path on every lookup that follows a rename, even within a single process with zero concurrency. This makes the default post-rename `(dev, ino)` identity check always fail with `path-mismatch`, regardless of whether a race actually occurred.
238+
239+
Set `renameIdentity: "verify-content-with-lock"` on the root (or per call) to use a SHA-256 content comparison under a cooperative sidecar lock instead:
240+
241+
```ts
242+
const fs = await root("/mnt/rclone-workspace", {
243+
renameIdentity: "verify-content-with-lock",
244+
});
245+
246+
await fs.write("state.json", body); // succeeds on rclone FUSE
247+
```
248+
249+
**How it works.** A write first runs with the default strict check. If that check detects a `path-mismatch` (genuine race or FUSE inode churn), it acquires an exclusive sidecar lock at `{targetPath}.lock` and retries the full write under that lock. The retry accepts the destination if the SHA-256 of the re-read bytes matches the SHA-256 of the bytes written. The lock is always released before the call returns.
250+
251+
**Security note.** `verify-content-with-lock` provides two guarantees: (1) the bytes that reached the destination match the bytes the caller asked to write, and (2) no *cooperating* writer interleaved during the locked retry. It does **not** prove that the process that called `write()` is the exclusive owner of the resulting file object on disk. A same-UID process that deliberately bypasses the sidecar lock can still interleave — this is the same residual risk as any advisory lock and is explicitly outside fs-safe's documented threat model. Do not use this option on directories that are writable by untrusted same-UID processes.
252+
235253
## See also
236254

237255
- [Atomic writes](atomic.md) — the lower-level `replaceFileAtomic` and friends.

‎src/file-identity.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { createHash } from "node:crypto";
2+
13
export type FileIdentityStat = {
24
dev: number | bigint;
35
ino: number | bigint;
@@ -11,6 +13,11 @@ function sameStatValue(left: number | bigint, right: number | bigint): boolean {
1113
return typeof left === typeof right ? left === right : BigInt(left) === BigInt(right);
1214
}
1315

16+
export function sha256Hex(data: string | Buffer, encoding?: BufferEncoding): string {
17+
const buffer = typeof data === "string" ? Buffer.from(data, encoding ?? "utf8") : data;
18+
return createHash("sha256").update(buffer).digest("hex");
19+
}
20+
1421
export function sameFileIdentity(
1522
left: FileIdentityStat,
1623
right: FileIdentityStat,

‎src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export {
99
root,
1010
type DenyMutationPolicy,
1111
type HardlinkPolicy,
12+
type RenameIdentityPolicy,
1213
type OpenResult,
1314
type ReadResult,
1415
type Root,

‎src/pinned-write.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { createAsyncDirectoryGuard, createNearestExistingDirectoryGuard } from "
88
import { FsSafeError } from "./errors.js";
99
import { syncDirectoryBestEffort } from "./fsync.js";
1010
import type { FileIdentityStat } from "./file-identity.js";
11-
import { sameFileIdentity } from "./file-identity.js";
11+
import { sameFileIdentity, sha256Hex } from "./file-identity.js";
1212
import { withAsyncDirectoryGuards } from "./guarded-mutation.js";
1313
import { mkdirPathComponentsWithGuards } from "./guarded-mkdir.js";
1414
import { canFallbackFromPythonError, getFsSafePythonConfig } from "./pinned-python-config.js";
@@ -97,6 +97,8 @@ async function inputToBase64(
9797
return Buffer.concat(chunks, bytes).toString("base64");
9898
}
9999

100+
type RenameIdentityMismatchPolicy = "throw" | "verify-content";
101+
100102
export async function runPinnedWriteHelper(params: {
101103
rootPath: string;
102104
relativeParentPath: string;
@@ -107,6 +109,7 @@ export async function runPinnedWriteHelper(params: {
107109
maxBytes?: number;
108110
input: PinnedWriteInput;
109111
rootIdentity?: FileIdentityStat;
112+
onRenameIdentityMismatch?: RenameIdentityMismatchPolicy;
110113
}): Promise<FileIdentityStat> {
111114
assertSafeBasename(params.basename);
112115
validatePinnedOperationPayload({
@@ -196,6 +199,7 @@ async function runPinnedWriteFallback(params: {
196199
overwrite?: boolean;
197200
maxBytes?: number;
198201
input: PinnedWriteInput;
202+
onRenameIdentityMismatch?: RenameIdentityMismatchPolicy;
199203
}): Promise<FileIdentityStat> {
200204
const parentPath = params.relativeParentPath
201205
? path.join(params.rootPath, ...params.relativeParentPath.split("/"))
@@ -294,9 +298,47 @@ async function runPinnedWriteFallback(params: {
294298
renamed = true;
295299
await syncDirectoryBestEffort(parentPath);
296300
targetStat = await fs.lstat(targetPath);
297-
if (targetStat.isSymbolicLink() || !sameFileIdentity(targetStat, expectedTempStat)) {
301+
if (targetStat.isSymbolicLink()) {
298302
throw new FsSafeError("path-mismatch", "fallback target changed during write");
299303
}
304+
if (!sameFileIdentity(targetStat, expectedTempStat)) {
305+
// On filesystems like rclone FUSE where rename(2) causes every subsequent
306+
// path-based lookup to mint a fresh inode, the (dev,ino) check always fails
307+
// even with zero concurrency. The caller is responsible for ensuring mutual
308+
// exclusion before passing "verify-content"; fall back to a content-hash
309+
// comparison. A hash mismatch still throws.
310+
if (params.onRenameIdentityMismatch !== "verify-content") {
311+
throw new FsSafeError("path-mismatch", "fallback target changed during write");
312+
}
313+
if (params.input.kind !== "buffer") {
314+
throw new FsSafeError("path-mismatch", "fallback target changed during write");
315+
}
316+
const expectedHash = sha256Hex(params.input.data, params.input.encoding);
317+
const readFlags =
318+
fsSync.constants.O_RDONLY |
319+
(process.platform !== "win32" && "O_NOFOLLOW" in fsSync.constants
320+
? fsSync.constants.O_NOFOLLOW
321+
: 0);
322+
const readHandle = await fs.open(targetPath, readFlags);
323+
let actualHash: string;
324+
let readHandleStat: Awaited<ReturnType<typeof readHandle.stat>>;
325+
try {
326+
// Capture fd-based identity before reading — this is stable across all
327+
// subsequent lookups (on FUSE and locally), unlike the lstat-based
328+
// targetStat that triggered this fallback.
329+
readHandleStat = await readHandle.stat();
330+
actualHash = sha256Hex(await readHandle.readFile());
331+
} finally {
332+
await readHandle.close().catch(() => undefined);
333+
}
334+
if (actualHash !== expectedHash) {
335+
throw new FsSafeError("path-mismatch", "fallback target changed during write");
336+
}
337+
// Replace the unreliable lstat-based targetStat with the fd-based stat so
338+
// the returned identity is consistent with what subsequent verifications
339+
// (e.g. verifyAtomicWriteResult) will obtain by opening the same file.
340+
targetStat = readHandleStat;
341+
}
300342
});
301343
} catch (error) {
302344
await handle?.close().catch(() => undefined);

‎src/root-impl.ts‎

Lines changed: 81 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import { getFsSafeTestHooks } from "./test-hooks.js";
5555
import { stringifyJsonDocument } from "./json-stringify.js";
5656
import type { DirEntry, PathStat } from "./types.js";
5757
import { registerTempPathForExit } from "./temp-cleanup.js";
58+
import { withSidecarLock } from "./sidecar-lock.js";
5859
import { serializePathWrite } from "./write-queue.js";
5960

6061
export type { DenyMutationPolicy } from "./deny-mutations.js";
@@ -77,13 +78,16 @@ export type SymlinkPolicy = "reject" | "follow-within-root";
7778
export type HardlinkPolicy = "reject" | "allow";
7879
export type WritableOpenMode = "replace" | "append" | "update";
7980

81+
export type RenameIdentityPolicy = "strict" | "verify-content-with-lock";
82+
8083
export type RootDefaults = {
8184
hardlinks?: HardlinkPolicy;
8285
maxBytes?: number;
8386
mkdir?: boolean;
8487
mode?: number;
8588
denyMutations?: DenyMutationPolicy;
8689
nonBlockingRead?: boolean;
90+
renameIdentity?: RenameIdentityPolicy;
8791
symlinks?: SymlinkPolicy;
8892
};
8993

@@ -94,7 +98,7 @@ export type RootReadOptions = Pick<
9498

9599
export type RootOpenOptions = Omit<RootReadOptions, "maxBytes">;
96100

97-
export type RootWriteOptions = Pick<RootDefaults, "denyMutations" | "mkdir" | "mode"> & {
101+
export type RootWriteOptions = Pick<RootDefaults, "denyMutations" | "mkdir" | "mode" | "renameIdentity"> & {
98102
encoding?: BufferEncoding;
99103
overwrite?: boolean;
100104
};
@@ -479,6 +483,7 @@ class RootHandle implements Root {
479483
data,
480484
mkdir: this.defaults.mkdir,
481485
mode: this.defaults.mode,
486+
renameIdentity: this.defaults.renameIdentity,
482487
...options,
483488
denyMutations: mergeDenyMutationPolicies(this.defaults.denyMutations, options.denyMutations),
484489
});
@@ -1048,6 +1053,7 @@ async function writeFileInRoot(
10481053
mode?: number;
10491054
denyMutations?: DenyMutationPolicy;
10501055
overwrite?: boolean;
1056+
renameIdentity?: RenameIdentityPolicy;
10511057
},
10521058
): Promise<void> {
10531059
if (process.platform === "win32") {
@@ -1069,40 +1075,93 @@ async function writeFileInRoot(
10691075
});
10701076
}
10711077

1078+
function lockHolderIsAlive(payload: Record<string, unknown> | null): boolean {
1079+
const pid = Number(payload?.pid);
1080+
if (!Number.isFinite(pid) || pid <= 0) {
1081+
// No valid PID in payload — cannot determine liveness. Treat as alive so
1082+
// we don't aggressively reclaim a lock whose holder we cannot identify.
1083+
return true;
1084+
}
1085+
try {
1086+
// Signal 0 does not kill the process; it checks whether we have permission
1087+
// to send signals to pid. Throws ESRCH if the process does not exist.
1088+
process.kill(pid, 0);
1089+
return true;
1090+
} catch (err) {
1091+
// EPERM: the process exists but we cannot signal it — treat as alive.
1092+
return (err as NodeJS.ErrnoException).code === "EPERM";
1093+
}
1094+
}
1095+
10721096
async function commitPinnedWriteInRoot(
10731097
root: RootContext,
10741098
pinned: PinnedWriteTarget,
1075-
params: { data: string | Buffer; encoding?: BufferEncoding; mkdir?: boolean; mode?: number; overwrite?: boolean },
1099+
params: {
1100+
data: string | Buffer;
1101+
encoding?: BufferEncoding;
1102+
mkdir?: boolean;
1103+
mode?: number;
1104+
overwrite?: boolean;
1105+
renameIdentity?: RenameIdentityPolicy;
1106+
},
10761107
): Promise<void> {
1108+
const helperParams = {
1109+
rootPath: pinned.rootReal,
1110+
relativeParentPath: pinned.relativeParentPath,
1111+
basename: pinned.basename,
1112+
mkdir: params.mkdir !== false,
1113+
mode: params.mode ?? pinned.mode,
1114+
overwrite: params.overwrite,
1115+
input: { kind: "buffer" as const, data: params.data, encoding: params.encoding },
1116+
};
1117+
10771118
let identity;
1078-
try {
1079-
identity = await runPinnedWriteHelper({
1080-
rootPath: pinned.rootReal,
1081-
relativeParentPath: pinned.relativeParentPath,
1082-
basename: pinned.basename,
1083-
mkdir: params.mkdir !== false,
1084-
mode: params.mode ?? pinned.mode,
1085-
overwrite: params.overwrite,
1086-
input: {
1087-
kind: "buffer",
1088-
data: params.data,
1089-
encoding: params.encoding,
1119+
1120+
if (params.renameIdentity === "verify-content-with-lock") {
1121+
// On FUSE mounts where rename(2) causes inode-churn, hold a cooperative
1122+
// sidecar lock for the entire write so content-hash verification is
1123+
// meaningful. If the holder crashes, the PID-liveness check reclaims the
1124+
// stale lock immediately rather than after a fixed timeout.
1125+
await withSidecarLock(
1126+
pinned.targetPath,
1127+
{
1128+
managerKey: `fs-safe.write:${pinned.targetPath}`,
1129+
staleMs: 30_000,
1130+
payload: () => ({ pid: process.pid, createdAt: new Date().toISOString() }),
1131+
retry: { retries: 5, minTimeout: 100, maxTimeout: 2_000, factor: 2 },
1132+
shouldReclaim: ({ payload }) => !lockHolderIsAlive(payload),
1133+
staleRecovery: "remove-if-unchanged",
1134+
shouldRemoveStaleLock: ({ payload }) => !lockHolderIsAlive(payload),
10901135
},
1091-
});
1092-
} catch (error) {
1093-
if (params.overwrite === false && isAlreadyExistsError(error)) {
1094-
throw new FsSafeError("already-exists", "file already exists", {
1095-
cause: error instanceof Error ? error : undefined,
1096-
});
1136+
async () => {
1137+
try {
1138+
identity = await runPinnedWriteHelper({
1139+
...helperParams,
1140+
onRenameIdentityMismatch: "verify-content",
1141+
});
1142+
} catch (error) {
1143+
throw normalizePinnedWriteError(error);
1144+
}
1145+
},
1146+
);
1147+
} else {
1148+
try {
1149+
identity = await runPinnedWriteHelper(helperParams);
1150+
} catch (error) {
1151+
if (params.overwrite === false && isAlreadyExistsError(error)) {
1152+
throw new FsSafeError("already-exists", "file already exists", {
1153+
cause: error instanceof Error ? error : undefined,
1154+
});
1155+
}
1156+
throw normalizePinnedWriteError(error);
10971157
}
1098-
throw normalizePinnedWriteError(error);
10991158
}
11001159

11011160
try {
11021161
await verifyAtomicWriteResult({
11031162
root,
11041163
targetPath: pinned.targetPath,
1105-
expectedIdentity: identity,
1164+
expectedIdentity: identity!,
11061165
});
11071166
} catch (err) {
11081167
emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);

‎src/root.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export {
66
root,
77
type DenyMutationPolicy,
88
type HardlinkPolicy,
9+
type RenameIdentityPolicy,
910
type OpenResult,
1011
type ReadResult,
1112
type Root,

0 commit comments

Comments
 (0)