Skip to content

Commit a5354d3

Browse files
authored
fix(root): verify restrictive-mode writes through retained descriptors (#154)
* fix(root): verify restrictive-mode writes through retained descriptors Retain the published descriptor through Root verification while preserving exact identity, link, and confinement checks. Avoid a read reopen failure after the mode-000 file has already been published. * fix(root): preserve Windows opaque-path verification Reopen paths through the guarded reader only when Windows pathname identity is unavailable, then compare the fresh descriptor against the original retained bigint identity. Keep POSIX mode-000 verification unchanged.
1 parent d733275 commit a5354d3

16 files changed

Lines changed: 1294 additions & 138 deletions

‎.github/workflows/ci.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ jobs:
115115
FS_SAFE_PAX_REQUIRE_NATIVE: "1"
116116
run: pnpm test test/native-integration.test.ts test/native-write-containment.test.ts test/native-staging-regression.test.ts test/staged-file.test.ts test/staged-file-failures.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/private-directory.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
117117

118+
- name: Test native Root publication verification
119+
env:
120+
FS_SAFE_NATIVE_MODE: require
121+
run: pnpm test test/root-write-mode.test.ts test/root-write-verification.test.ts test/root-write-lifetime.test.ts test/root-write-exact-identity.test.ts
122+
118123
native-musl:
119124
name: Native check (linux-x64-musl)
120125
runs-on: ubuntu-latest
@@ -136,6 +141,7 @@ jobs:
136141
node scripts/native-mode-smoke.mjs require
137142
node scripts/native-mode-smoke.mjs off
138143
FS_SAFE_PAX_REQUIRE_NATIVE=1 pnpm test test/native-write-containment.test.ts test/native-staging-regression.test.ts test/staged-file.test.ts test/staged-file-failures.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
144+
FS_SAFE_NATIVE_MODE=require pnpm test test/root-write-mode.test.ts test/root-write-verification.test.ts test/root-write-lifetime.test.ts test/root-write-exact-identity.test.ts
139145
'
140146
141147
cargo-quality:

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
### Security and Correctness
66

77
- Preserve underlying command diagnostics (command, timing, timeout flag, exit code/signal, and sanitized stderr) and cause on Windows ACL `permission-unverified` errors without changing verification semantics.
8+
- Verify `Root.write()` and `create()` through retained descriptors and exact bigint identities for restrictive final modes, retaining guarded Windows path opens when pathname identity is unavailable; preserve explicit mode zero in `copyIn()`.
89
- Preserve filesystem failures from `ensureDirectoryWithinRoot()` and `pathScope().ensureDir()` in an optional operational `FsSafeError` diagnostic with the original cause and bounded, escaped display text, instead of misreporting them as containment violations; keep nonthrowing string results and directory safety checks.
910
- Accept bounded local PAX paths, sizes, and descriptive metadata, including inert binary macOS provenance xattrs, consistently in JavaScript and native TAR extraction/reads; reject ambiguous records, extension chains, and sparse semantics while retaining byte/count limits and guarded staging. Return TAR read traversal failures through the public promise instead of escaping the parser callback.
1011
- Add native-required Linux/macOS `stageFileInDirectory()` under `advanced` with retained-directory abort cleanup, private `0600` staging until publication is identity-checked, exact identity checks, explicit publication/cleanup receipts, and async disposal; share that ownership with POSIX native streaming writes so parent moves no longer strand their unpublished temps.

‎docs/native.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,18 @@ Native writers share root and parent admission, but keep their platform identity
104104
checks and leaf ownership. POSIX coordinator disposal uses `SuppressedError` to
105105
retain both an operation failure and a disposal failure, including their receipts;
106106
stage preparation and cleanup keep their documented error mappings.
107+
Root replacement verification borrows the published descriptor after final mode
108+
application, while a private coordinator retains the staged owner until the
109+
asynchronous check finishes. The owner never escapes that coordinator; public
110+
staging methods and receipts expose no descriptor or verification callback.
111+
Verification failures preserve the published name, and disposal still retains
112+
both verification and cleanup errors when both fail.
113+
The private verification channel carries exact bigint identity from the original
114+
owned descriptor (or the content-accepted FUSE descriptor). Root compares it
115+
against exact fd and pathname metadata; legacy helper return facts and public
116+
read metadata behavior are unchanged. Missing Windows pathname identity still
117+
requires a guarded path reopen and comparison with the original retained file;
118+
that fallback does not apply to POSIX no-read modes.
107119

108120
## JavaScript fallback guarantees and delta
109121

‎docs/writing.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ old-or-new guarantee does not apply to `append()` or `openWritable()`, which
3333
write in place, or to lower-level atomic helpers when their explicitly
3434
non-atomic permission-error copy fallback is enabled.
3535

36+
Post-publication verification can still reject after a complete replacement has
37+
been committed. Rejection does not promise that a successful rename was rolled
38+
back; the published file or a raced replacement may remain at the destination.
39+
3640
## Denying mutations
3741

3842
All mutation verbs accept `denyMutations?: DenyMutationPolicy`, either as a root default or per-call option:
@@ -64,6 +68,20 @@ await fs.write("notes/today.txt", "hello\n", { encoding: "utf8" });
6468

6569
`data` accepts `string | Buffer`. `options` are `{ denyMutations?: DenyMutationPolicy; encoding?: BufferEncoding; mkdir?: boolean; mode?: number; overwrite?: boolean; renameIdentity?: RenameIdentityPolicy }`. `mode` sets the file's POSIX mode. If neither the call nor `RootDefaults` supplies it, a replacement preserves the existing file mode and a new file uses `0o600`. `mkdir` and `overwrite` both default to `true`; set `overwrite: false` for the same no-clobber behavior as `create()`.
6670

71+
POSIX modes without read permission, including `0o000` and `0o200`, succeed:
72+
final verification uses a descriptor retained by the writer rather than reopening
73+
the published file. The requested mode is not relaxed for verification.
74+
Publication verification compares exact bigint descriptor and pathname identities,
75+
including large file indexes that cannot be represented by a JavaScript number.
76+
Later reads still obey OS permissions, and access checks on a pre-existing
77+
destination are unchanged. The explicit FUSE compatibility policy still requires
78+
a readable destination to prove matching content when rename changes its identity.
79+
80+
When Windows cannot report a pathname's identity, verification retains the guarded
81+
reader fallback: reopen the name and compare that descriptor's exact identity with
82+
the original retained file. Unknown pathname metadata is not proof that the name
83+
still refers to the published file.
84+
6785
### `fs.create(rel, data, options?)`
6886

6987
Don't-clobber variant of `write()`. Throws `already-exists` if the target is there.

‎src/native-pinned-write-windows.ts‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { randomUUID } from "node:crypto";
22
import fsSync, { type Stats } from "node:fs";
33
import type { FileHandle } from "node:fs/promises";
4+
import type { AsyncDirectoryGuard } from "./directory-guard.js";
45
import { FsSafeError } from "./errors.js";
56
import type { FileIdentityStat } from "./file-identity.js";
67
import {
@@ -19,18 +20,29 @@ export function sameNativeIdentity(
1920
return left.dev === right.dev && left.ino === right.ino;
2021
}
2122

23+
function closeWriteFd(fd: number | undefined): unknown {
24+
if (fd === undefined) return;
25+
try {
26+
fsSync.closeSync(fd);
27+
} catch (error) {
28+
return error;
29+
}
30+
}
31+
2232
export async function runPinnedWriteWindows(
2333
binding: NativeBinding,
2434
params: PinnedWriteParams,
2535
root: FileHandle,
2636
parentFd: number,
27-
parentPath: string,
37+
parentGuard: AsyncDirectoryGuard,
2838
): Promise<FileIdentityStat> {
39+
const parentPath = parentGuard.realPath;
2940
let tempFd: number | undefined;
3041
let targetFd: number | undefined;
3142
let tempIdentity: Stats | undefined;
3243
let tempName = "";
3344
let renamed = false;
45+
let completed = false;
3446
try {
3547
tempName = `.${params.basename}.${randomUUID()}.native.tmp`;
3648
tempFd = binding.openBeneath(
@@ -41,6 +53,7 @@ export async function runPinnedWriteWindows(
4153
),
4254
).fd;
4355
tempIdentity = fsSync.fstatSync(tempFd);
56+
const verificationIdentity = fsSync.fstatSync(tempFd, { bigint: true });
4457
// Creation is requested at 0600 in the binding, but a restrictive umask
4558
// can remove owner access. Keep the unpublished inode private and
4659
// reopenable until the published name has been identity-fenced.
@@ -69,7 +82,7 @@ export async function runPinnedWriteWindows(
6982
fsSync.fchmodSync(targetFd, params.mode);
7083
syncNativeFileBestEffort(targetFd);
7184
} catch (error) {
72-
fsSync.closeSync(targetFd);
85+
closeWriteFd(targetFd);
7386
targetFd = undefined;
7487
removeNativeCreatedFileIfStillPinned({
7588
binding,
@@ -81,14 +94,13 @@ export async function runPinnedWriteWindows(
8194
throw error;
8295
}
8396
syncNativeFileBestEffort(parentFd);
97+
// Verification follows publication and final chmod, outside rollback handling.
98+
await params.verifyPublished?.(targetFd, verificationIdentity, parentGuard);
99+
completed = true;
84100
return { dev: targetIdentity.dev, ino: targetIdentity.ino };
85101
} finally {
86-
if (targetFd !== undefined) {
87-
fsSync.closeSync(targetFd);
88-
}
89-
if (tempFd !== undefined) {
90-
fsSync.closeSync(tempFd);
91-
}
102+
const targetCloseError = closeWriteFd(targetFd);
103+
const tempCloseError = closeWriteFd(tempFd);
92104
if (!renamed) {
93105
removeNativeCreatedFileIfStillPinned({
94106
binding,
@@ -98,7 +110,9 @@ export async function runPinnedWriteWindows(
98110
created: tempIdentity,
99111
});
100112
}
101-
fsSync.closeSync(parentFd);
113+
const parentCloseError = closeWriteFd(parentFd);
102114
await root.close().catch(() => undefined);
115+
const closeError = targetCloseError ?? tempCloseError ?? parentCloseError;
116+
if (completed && closeError !== undefined) throw closeError;
103117
}
104118
}

‎src/native-pinned-write.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from "node:path";
44
import { FsSafeError } from "./errors.js";
55
import type { FileIdentityStat } from "./file-identity.js";
66
import { runPinnedWriteWindows, sameNativeIdentity } from "./native-pinned-write-windows.js";
7-
import { assertNativeStaging, createNativeStage, type NativeStagingBinding } from "./native-staged-file.js";
7+
import { assertNativeStaging, writeNativeStage, type NativeStagingBinding } from "./native-staged-file.js";
88
import type { NativeBinding } from "./native.js";
99
import type { PinnedWriteParams } from "./pinned-write.js";
1010
import { describeStagedDirectory, exactIdentityMatches } from "./staged-directory.js";
@@ -54,13 +54,16 @@ export async function runPinnedWriteNative(binding: NativeBinding, params: Pinne
5454
: params.rootPath,
5555
);
5656
const directory = windows ? undefined : describeStagedDirectory(parentFd, parentPath);
57+
const parentPathStat = await fs.lstat(parentPath);
5758
if (windows) {
58-
const parentPathStat = await fs.lstat(parentPath);
5959
const parentIdentity = binding.fstatIdentity(parentFd);
6060
if (parentPathStat.isSymbolicLink() || !sameNativeIdentity(parentPathStat, parentIdentity)) {
6161
throw new FsSafeError("path-mismatch", "native write parent changed during resolution");
6262
}
63+
} else if (parentPathStat.isSymbolicLink() || !exactIdentityMatches(parentPathStat, directory!.identity)) {
64+
throw new FsSafeError("path-mismatch", "native write parent changed during resolution");
6365
}
66+
const verificationGuard = { dir: parentPath, realPath: parentPath, stat: parentPathStat };
6467
if (params.overwrite === false) {
6568
try {
6669
await fs.lstat(path.join(parentPath, params.basename));
@@ -72,17 +75,15 @@ export async function runPinnedWriteNative(binding: NativeBinding, params: Pinne
7275
}
7376
}
7477
if (windows) {
75-
// Keep the released Windows leaf/parent/root close sequence and policy.
78+
// The Windows leaf owns both directories after admission.
7679
windowsOwnsDirectories = true;
77-
return await runPinnedWriteWindows(binding, params, root, parentFd, parentPath);
80+
return await runPinnedWriteWindows(binding, params, root, parentFd, verificationGuard);
7881
}
7982
const ownedParent = parentFd;
8083
parentFd = undefined;
81-
await using staged = await createNativeStage(
82-
binding as NativeStagingBinding, ownedParent, directory!, params.input, params.mode, params.maxBytes, false,
84+
return await writeNativeStage(
85+
binding as NativeStagingBinding, ownedParent, directory!, params, verificationGuard,
8386
);
84-
const published = await staged.publish(params.basename, { overwrite: params.overwrite !== false });
85-
return { dev: published.staged.identity.dev, ino: published.staged.identity.ino };
8687
} finally {
8788
if (windows && !windowsOwnsDirectories) {
8889
if (parentFd !== undefined) {

‎src/native-staged-file.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { randomUUID } from "node:crypto";
22
import fs from "node:fs";
3+
import type { AsyncDirectoryGuard } from "./directory-guard.js";
34
import { FsSafeError } from "./errors.js";
5+
import type { FileIdentityStat } from "./file-identity.js";
46
import type { NativeBinding } from "./native-binding.js";
57
import { syncNativeFileBestEffort, writeNativeInput } from "./native-operations.js";
6-
import type { PinnedWriteInput } from "./pinned-write.js";
8+
import type { PinnedWriteInput, PinnedWriteParams } from "./pinned-write.js";
79
import { assertStagedDirectoryCurrent } from "./staged-directory.js";
810
import type {
911
PublishedFileReceipt,
@@ -92,7 +94,7 @@ class NativeStagedFile implements StagedFile {
9294
maxBytes?: number,
9395
// Public staging uses portable names; existing POSIX writes accept literal names.
9496
portableNames = true,
95-
): Promise<StagedFile> {
97+
): Promise<NativeStagedFile> {
9698
let staged: NativeStagedFile;
9799
try {
98100
staged = new NativeStagedFile(binding, parentFd, directory, portableNames, mode);
@@ -108,6 +110,24 @@ class NativeStagedFile implements StagedFile {
108110
return staged;
109111
}
110112

113+
static async write(
114+
binding: NativeStagingBinding,
115+
parentFd: number,
116+
directory: StagedFileReceipt["directory"],
117+
params: PinnedWriteParams,
118+
parentGuard: AsyncDirectoryGuard,
119+
): Promise<FileIdentityStat> {
120+
// This owner never escapes. Only the internal verifier borrows its fd;
121+
// public descriptor methods remain await-free and cannot race disposal.
122+
await using staged = await NativeStagedFile.create(
123+
binding, parentFd, directory, params.input, params.mode, params.maxBytes, false,
124+
);
125+
const published = await staged.publish(params.basename, { overwrite: params.overwrite !== false });
126+
const identity = published.staged.identity;
127+
await params.verifyPublished?.(staged.#file(), identity, parentGuard);
128+
return { dev: identity.dev, ino: identity.ino };
129+
}
130+
111131
get receipt(): StagedFileReceipt {
112132
if (!this.#receipt) {
113133
throw new FsSafeError("helper-failed", "staged file preparation is incomplete");
@@ -312,4 +332,6 @@ class NativeStagedFile implements StagedFile {
312332
}
313333
}
314334

315-
export const createNativeStage = NativeStagedFile.create;
335+
export const createNativeStage: (...args: Parameters<typeof NativeStagedFile.create>) => Promise<StagedFile> =
336+
NativeStagedFile.create;
337+
export const writeNativeStage = NativeStagedFile.write;

‎src/opened-realpath.ts‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,35 @@
1-
import type { Stats } from "node:fs";
21
import fs from "node:fs/promises";
32
import type { FileHandle } from "node:fs/promises";
43
import path from "node:path";
54
import { FsSafeError } from "./errors.js";
6-
import { sameFileIdentity } from "./file-identity.js";
5+
import { sameFileIdentity, type FileIdentityStat } from "./file-identity.js";
76
import { isNotFoundPathError } from "./path.js";
87

98
export async function resolveOpenedFileRealPathForHandle(
109
handle: FileHandle,
1110
ioPath: string,
1211
): Promise<string> {
1312
const handleStat = await handle.stat();
13+
return await resolveOpenedFileRealPathForFd(handle.fd, handleStat, ioPath);
14+
}
15+
16+
export async function resolveOpenedFileRealPathForFd(
17+
fd: number,
18+
handleStat: FileIdentityStat,
19+
ioPath: string,
20+
): Promise<string> {
21+
const statOptions = typeof handleStat.dev === "bigint" || typeof handleStat.ino === "bigint"
22+
? { bigint: true as const } : undefined;
1423
const fdCandidates =
1524
process.platform === "linux"
16-
? [`/proc/self/fd/${handle.fd}`, `/dev/fd/${handle.fd}`]
25+
? [`/proc/self/fd/${fd}`, `/dev/fd/${fd}`]
1726
: process.platform === "win32"
1827
? []
19-
: [`/dev/fd/${handle.fd}`];
28+
: [`/dev/fd/${fd}`];
2029
for (const fdPath of fdCandidates) {
2130
try {
2231
const fdRealPath = await fs.realpath(fdPath);
23-
const fdRealStat = await fs.stat(fdRealPath);
32+
const fdRealStat = statOptions ? await fs.stat(fdRealPath, statOptions) : await fs.stat(fdRealPath);
2433
if (sameFileIdentity(handleStat, fdRealStat)) {
2534
return fdRealPath;
2635
}
@@ -31,7 +40,7 @@ export async function resolveOpenedFileRealPathForHandle(
3140

3241
try {
3342
const ioRealPath = await fs.realpath(ioPath);
34-
const ioRealStat = await fs.stat(ioRealPath);
43+
const ioRealStat = statOptions ? await fs.stat(ioRealPath, statOptions) : await fs.stat(ioRealPath);
3544
if (sameFileIdentity(handleStat, ioRealStat)) {
3645
return ioRealPath;
3746
}
@@ -40,16 +49,17 @@ export async function resolveOpenedFileRealPathForHandle(
4049
throw err;
4150
}
4251
}
43-
const parentResolved = await resolveOpenedFileRealPathFromParent(handleStat, ioPath);
52+
const parentResolved = await resolveOpenedFileRealPathFromParent(handleStat, ioPath, statOptions);
4453
if (parentResolved) {
4554
return parentResolved;
4655
}
4756
throw new FsSafeError("path-mismatch", "unable to resolve opened file path");
4857
}
4958

5059
async function resolveOpenedFileRealPathFromParent(
51-
handleStat: Stats,
60+
handleStat: FileIdentityStat,
5261
ioPath: string,
62+
statOptions?: { bigint: true },
5363
): Promise<string | null> {
5464
let parentReal: string;
5565
try {
@@ -74,7 +84,7 @@ async function resolveOpenedFileRealPathFromParent(
7484
for (const entry of entries.toSorted()) {
7585
const candidatePath = path.join(parentReal, entry);
7686
try {
77-
const candidateStat = await fs.lstat(candidatePath);
87+
const candidateStat = statOptions ? await fs.lstat(candidatePath, statOptions) : await fs.lstat(candidatePath);
7888
if (candidateStat.isFile() && sameFileIdentity(handleStat, candidateStat)) {
7989
return await fs.realpath(candidatePath);
8090
}

0 commit comments

Comments
 (0)