Skip to content

Commit fb0d13f

Browse files
committed
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 8b58650 commit fb0d13f

9 files changed

Lines changed: 147 additions & 41 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +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 so final modes such as `000` and large file indexes succeed without relaxing permissions or post-publication checks; preserve explicit mode zero in `copyIn()`.
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()`.
99
- 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.
1010
- 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.
1111
- 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: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ both verification and cleanup errors when both fail.
113113
The private verification channel carries exact bigint identity from the original
114114
owned descriptor (or the content-accepted FUSE descriptor). Root compares it
115115
against exact fd and pathname metadata; legacy helper return facts and public
116-
read metadata behavior are unchanged.
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.
117119

118120
## JavaScript fallback guarantees and delta
119121

‎docs/writing.md‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,14 +68,19 @@ await fs.write("notes/today.txt", "hello\n", { encoding: "utf8" });
6868

6969
`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()`.
7070

71-
Modes without read permission, including `0o000` and `0o200`, succeed: final
72-
verification uses a descriptor retained by the writer rather than reopening the
73-
published file. The requested mode is not relaxed for verification. Publication verification compares
74-
exact bigint descriptor and pathname identities, including large file indexes
75-
that cannot be represented by a JavaScript number. Later reads
76-
still obey OS permissions, and access checks on a pre-existing destination are
77-
unchanged. The explicit FUSE compatibility policy still requires a readable
78-
destination to prove matching content when rename changes its identity.
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.
7984

8085
### `fs.create(rel, data, options?)`
8186

‎src/root-impl.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1125,7 +1125,7 @@ async function commitPinnedWriteInRoot(
11251125
fd,
11261126
expectedIdentity,
11271127
parentGuard,
1128-
});
1128+
}, openVerifiedLocalFile);
11291129
} catch (error) {
11301130
emitWriteBoundaryWarning(`post-write verification failed: ${String(error)}`);
11311131
throw error;
@@ -1627,7 +1627,7 @@ async function writeFileFallback(
16271627
expectedIdentity: written.identity,
16281628
fd: written.handle.fd,
16291629
parentGuard: destinationGuard,
1630-
});
1630+
}, openVerifiedLocalFile);
16311631
} catch (err) {
16321632
emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);
16331633
throw err;
@@ -1700,7 +1700,7 @@ async function writeMissingFileFallback(
17001700
expectedIdentity: writtenStat,
17011701
fd: handle.fd,
17021702
parentGuard,
1703-
});
1703+
}, openVerifiedLocalFile);
17041704
} catch (err) {
17051705
if (verifyingPublication) throw err;
17061706
if (hasNodeErrorCode(err, "EEXIST")) {

‎src/root-write-verification.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import fsSync, { type BigIntStats } from "node:fs";
2-
import fs from "node:fs/promises";
2+
import fs, { type FileHandle } from "node:fs/promises";
33
import { assertAsyncDirectoryGuard, type AsyncDirectoryGuard } from "./directory-guard.js";
44
import { FsSafeError } from "./errors.js";
55
import { sameFileIdentity } from "./file-identity.js";
@@ -15,7 +15,11 @@ export async function verifyAtomicWriteResult(params: {
1515
fd: number;
1616
expectedIdentity: PublishedWriteIdentity;
1717
parentGuard: AsyncDirectoryGuard;
18-
}): Promise<void> {
18+
}, reopenVerified: (
19+
filePath: string,
20+
options: { hardlinks: "reject" },
21+
) => Promise<{ handle: FileHandle; realPath: string }>): Promise<void> {
22+
let needsPathOpen = false;
1923
const assertFile = (stat: BigIntStats) => {
2024
if (stat.isSymbolicLink()) {
2125
throw new FsSafeError("symlink", "symlink not allowed");
@@ -30,8 +34,12 @@ export async function verifyAtomicWriteResult(params: {
3034
throw hardlinkedPathNotAllowedError();
3135
}
3236
};
33-
const assertDescriptor = () => {
34-
const stat = fsSync.fstatSync(params.fd, { bigint: true });
37+
const assertPath = (stat: BigIntStats) => {
38+
assertFile(stat);
39+
needsPathOpen ||= process.platform === "win32" && (stat.dev === 0n || stat.ino === 0n);
40+
};
41+
const assertDescriptor = (fd = params.fd) => {
42+
const stat = fsSync.fstatSync(fd, { bigint: true });
3543
// Only Windows pathname stats may have unknown identity; fd stats must match exactly.
3644
if (params.expectedIdentity.dev !== stat.dev || params.expectedIdentity.ino !== stat.ino) {
3745
throw new FsSafeError("path-mismatch", "descriptor changed during write");
@@ -42,17 +50,32 @@ export async function verifyAtomicWriteResult(params: {
4250
try {
4351
// This descriptor remains owned by the writer, even when final mode forbids opens.
4452
const stat = assertDescriptor();
45-
assertFile(await fs.lstat(params.targetPath, { bigint: true }));
53+
assertPath(await fs.lstat(params.targetPath, { bigint: true }));
4654
const realPath = await resolveOpenedFileRealPathForFd(params.fd, stat, params.targetPath);
47-
assertFile(await fs.stat(realPath, { bigint: true }));
55+
assertPath(await fs.stat(realPath, { bigint: true }));
4856
if (!isPathInside(params.root.rootWithSep, realPath)) {
4957
throw outsideWorkspaceError();
5058
}
5159
await assertAsyncDirectoryGuard(params.parentGuard);
5260
await assertRootIdentityCurrent(params.root);
5361
// Recheck after canonical resolution and directory checks, including late links.
54-
assertFile(await fs.lstat(params.targetPath, { bigint: true }));
62+
assertPath(await fs.lstat(params.targetPath, { bigint: true }));
5563
assertDescriptor();
64+
if (needsPathOpen) {
65+
// A retained fd cannot prove that an opaque Windows pathname still names it.
66+
// Keep the guarded reader fallback; POSIX no-read modes never take this path.
67+
const opened = await reopenVerified(params.targetPath, { hardlinks: "reject" });
68+
try {
69+
if (!isPathInside(params.root.rootWithSep, opened.realPath)) {
70+
throw outsideWorkspaceError();
71+
}
72+
await assertAsyncDirectoryGuard(params.parentGuard);
73+
await assertRootIdentityCurrent(params.root);
74+
assertDescriptor(opened.handle.fd);
75+
} finally {
76+
await opened.handle.close().catch(() => undefined);
77+
}
78+
}
5679
} catch (error) {
5780
if (isNotFoundPathError(error)) throw fileNotFoundError();
5881
throw error;

‎test/platform-fallback-coverage.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,12 +200,12 @@ describe("platform fallback coverage", () => {
200200
await fs.writeFile(outsideTarget, "attacker");
201201
const scoped = await openRoot(rootDir, { mkdir: false });
202202
let swapped = false;
203-
vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params) => {
203+
vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params, reopenVerified) => {
204204
expect(params.targetPath).toBe(target);
205205
swapped = true;
206206
await fs.rename(parent, `${parent}-original`);
207207
await fs.symlink(outsideDir, parent, "dir");
208-
await verifyPublished(params);
208+
await verifyPublished(params, reopenVerified);
209209
});
210210

211211
await expect(scoped.create("nested/created.txt", "library", {
@@ -234,12 +234,12 @@ describe("platform fallback coverage", () => {
234234
process.env.FS_SAFE_DEBUG_WARNINGS = "1";
235235
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
236236
let swapped = false;
237-
vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params) => {
237+
vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params, reopenVerified) => {
238238
expect(params.targetPath).toBe(target);
239239
swapped = true;
240240
await fs.rename(parent, `${parent}-original`);
241241
await fs.symlink(outsideDir, parent, "dir");
242-
await verifyPublished(params);
242+
await verifyPublished(params, reopenVerified);
243243
});
244244

245245
try {

‎test/root-write-exact-identity.test.ts‎

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ import { __loadBundledNativeForTest, __resetNativeLoaderForTest, __setNativeLoad
88
import { resolveOpenedFileRealPathForFd, resolveOpenedFileRealPathForHandle } from "../src/opened-realpath.js";
99
import { runPinnedWriteHelper } from "../src/pinned-write.js";
1010
import { resolveRootContext } from "../src/root-context.js";
11+
import { openLocalFileSafely } from "../src/root.js";
1112
import * as verification from "../src/root-write-verification.js";
1213
import { __setFsSafeTestHooksForTest } from "../src/test-hooks.js";
1314
import { useRealTempDirs } from "./helpers/vitest.js";
1415

1516
const { tempRoot } = useRealTempDirs();
1617
const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
1718
const verify = verification.verifyAtomicWriteResult;
19+
const reopenForTest = async (filePath: string) => await openLocalFileSafely({ filePath });
1820
const inode = 9007199254740993n;
1921
const device = 9007199254740995n;
2022
let nativeAvailable = false;
@@ -61,7 +63,7 @@ describe("Root exact publication identity", () => {
6163
const stat = fs.stat.bind(fs);
6264
vi.spyOn(fsSync, "fstatSync").mockImplementation(((...args: Parameters<typeof fsSync.fstatSync>) => {
6365
const actual = fstat(...args);
64-
return args[0] === handle.fd ? project(actual, scenario === "fd mismatch" ? inode : expectedInode, expectedDevice) : actual;
66+
return actual.isFile() ? project(actual, scenario === "fd mismatch" ? inode : expectedInode, expectedDevice) : actual;
6567
}) as typeof fsSync.fstatSync);
6668
vi.spyOn(fs, "lstat").mockImplementation((async (...args: Parameters<typeof fs.lstat>) => {
6769
const actual = await lstat(...args);
@@ -77,7 +79,7 @@ describe("Root exact publication identity", () => {
7779
}) as typeof fs.stat);
7880
try {
7981
const pending = verify({ root: context, targetPath: target, fd: handle.fd,
80-
expectedIdentity: { dev: expectedDevice, ino: expectedInode }, parentGuard });
82+
expectedIdentity: { dev: expectedDevice, ino: expectedInode }, parentGuard }, reopenForTest);
8183
if (scenario.includes("mismatch")) await expect(pending).rejects.toMatchObject({ code: "path-mismatch" });
8284
else await expect(pending).resolves.toBeUndefined();
8385
} finally {
@@ -191,13 +193,13 @@ for (const route of routes) {
191193
configureFsSafeNative({ mode: route.includes("native") ? "require" : "off" });
192194
let callbacks = 0;
193195
let fd: number | undefined;
194-
const check: typeof verify = async (params) => {
196+
const check: typeof verify = async (params, reopenVerified) => {
195197
callbacks++;
196198
fd = params.fd;
197199
expect(params.expectedIdentity).toMatchObject({ dev: device, ino: inode });
198200
// Direct-create paths have no rename; mutate only after their expected snapshot.
199201
published = true;
200-
await verify(params);
202+
await verify(params, reopenVerified);
201203
};
202204
let pending: Promise<unknown>;
203205
if (route === "windows fallback") {
@@ -208,7 +210,7 @@ for (const route of routes) {
208210
rootPath: directory, relativeParentPath: "", basename: "target", mkdir: false,
209211
mode: 0o600, overwrite: operation === "write", input: { kind: "buffer", data: "payload" },
210212
verifyPublished: async (fd, expectedIdentity, parentGuard) =>
211-
await check({ root: context, targetPath: target, fd, expectedIdentity, parentGuard }),
213+
await check({ root: context, targetPath: target, fd, expectedIdentity, parentGuard }, reopenForTest),
212214
});
213215
}
214216
if (changed) await expect(pending).rejects.toMatchObject({ code: "path-mismatch" });
@@ -237,13 +239,87 @@ it.skipIf(process.platform === "win32")("passes the exact content-accepted FUSE
237239
await fs.rename(target, original);
238240
await fs.writeFile(target, "payload");
239241
} });
240-
const check = vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params) => {
242+
const check = vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(async (params, reopenVerified) => {
241243
const accepted = fsSync.fstatSync(params.fd, { bigint: true });
242244
expect(params.expectedIdentity).toMatchObject({ dev: accepted.dev, ino: accepted.ino });
243245
expect(accepted.ino).not.toBe((await fs.stat(original, { bigint: true })).ino);
244-
await verify(params);
246+
await verify(params, reopenVerified);
245247
});
246248
const capability = await root(directory, { renameIdentity: "verify-content-with-lock" });
247249
await expect(capability.write("target", "payload")).resolves.toBeUndefined();
248250
expect(check).toHaveBeenCalledTimes(1);
249251
});
252+
253+
for (const backend of ["fallback", "native"] as const) {
254+
describe.skipIf(backend === "native" && !nativeAvailable)(
255+
`Windows opaque pathname identity with ${backend}`,
256+
() => {
257+
it.each(["write", "create"].flatMap((operation) =>
258+
["known identity", "unchanged", "same bytes", "different bytes", "read error"].map(
259+
(behavior) => ({ operation, behavior }),
260+
),
261+
))("$operation: $behavior", async ({ operation, behavior }) => {
262+
const directory = await tempRoot("fs-safe-windows-opaque-write-");
263+
const target = path.join(directory, "target");
264+
const published = path.join(directory, "published");
265+
const payload = "mode-zero-proof";
266+
const swapped = behavior === "same bytes" || behavior === "different bytes";
267+
if (operation === "write") await fs.writeFile(target, "old", { mode: 0o600 });
268+
const binding = backend === "native" ? __loadBundledNativeForTest() : undefined;
269+
if (binding) __setNativeLoaderForTest(() => binding);
270+
configureFsSafeNative({ mode: backend === "native" ? "require" : "off" });
271+
// POSIX hosts exercise the Windows branch; Windows CI runs its real mechanism.
272+
Object.defineProperty(process, "platform", { value: "win32" });
273+
const capability = await root(directory);
274+
const failure = Object.assign(new Error("opaque pathname cannot be opened"), { code: "EACCES" });
275+
let opaque = false;
276+
let retainedFd: number | undefined;
277+
let reopens = 0;
278+
const reopened: Array<{ fd: number }> = [];
279+
for (const method of ["stat", "lstat"] as const) {
280+
const original = fs[method].bind(fs);
281+
vi.spyOn(fs, method).mockImplementation((async (...args: Parameters<typeof fs.stat>) => {
282+
const stat = await original(...args);
283+
if (!opaque || String(args[0]) !== target) return stat;
284+
return Object.assign(Object.create(stat), {
285+
dev: typeof stat.dev === "bigint" ? 0n : 0,
286+
ino: typeof stat.ino === "bigint" ? 0n : 0,
287+
});
288+
}) as typeof fs.stat);
289+
}
290+
const verifier = vi.spyOn(verification, "verifyAtomicWriteResult").mockImplementation(
291+
async (params, openVerified) => {
292+
expect(params.targetPath).toBe(target);
293+
retainedFd = params.fd;
294+
if (swapped) {
295+
await fs.rename(target, published);
296+
await fs.writeFile(target, behavior === "same bytes" ? payload : "replacement", { mode: 0o600 });
297+
}
298+
opaque = behavior !== "known identity";
299+
await verify(params, async (...args) => {
300+
reopens++;
301+
if (behavior === "read error") throw failure;
302+
const opened = await openVerified(...args);
303+
reopened.push(opened.handle);
304+
return opened;
305+
});
306+
},
307+
);
308+
const pending = operation === "create"
309+
? capability.create("target", payload, { mode: 0o600 })
310+
: capability.write("target", payload, { mode: 0o600 });
311+
if (swapped) await expect(pending).rejects.toMatchObject({ code: "path-mismatch" });
312+
else if (behavior === "read error") await expect(pending).rejects.toBe(failure);
313+
else await expect(pending).resolves.toBeUndefined();
314+
expect(verifier).toHaveBeenCalledTimes(1);
315+
expect(reopens).toBe(behavior === "known identity" ? 0 : 1);
316+
expect(reopened.every((handle) => handle.fd === -1)).toBe(true);
317+
expect(() => fsSync.fstatSync(retainedFd!)).toThrowError(expect.objectContaining({ code: "EBADF" }));
318+
vi.restoreAllMocks();
319+
expect(await fs.readFile(swapped ? published : target, "utf8")).toBe(payload);
320+
if (swapped) expect(await fs.readFile(target, "utf8")).toBe(behavior === "same bytes" ? payload : "replacement");
321+
expect((await fs.readdir(directory)).sort()).toEqual(swapped ? ["published", "target"] : ["target"]);
322+
});
323+
},
324+
);
325+
}

0 commit comments

Comments
 (0)