Skip to content

Commit c7cd3cc

Browse files
author
Peter Steinberger
committed
fix(move): bind staging modes to descriptors
movePathWithCopyFallback() closed the staging descriptor and then applied the mode to the staging pathname, and applied staged directory modes by path. The staging names are randomized but visible to anyone who can list the writable target directory, so the entry could be replaced with a symlink before the chmod and the mode change redirected before publication. Regular files now keep the staging handle and use FileHandle.chmod(). POSIX directories use an O_RDONLY|O_DIRECTORY|O_NOFOLLOW handle. Windows performs no pathname fallback, since Node cannot portably open a directory descriptor there and POSIX modes are not enforced. No injectable filesystem member was added.
1 parent eda9a61 commit c7cd3cc

3 files changed

Lines changed: 177 additions & 12 deletions

File tree

‎CHANGELOG.md‎

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

55
### Security and Correctness
66

7+
- Apply `movePathWithCopyFallback()` file and POSIX directory modes through staging descriptors before publication, so a replaceable staging pathname cannot redirect `chmod` to an unrelated symlink target. Windows no longer uses a pathname fallback for directory modes because Node cannot portably open a directory descriptor there and does not enforce POSIX modes.
8+
79
- Reject drive-relative segments such as `C:secret.txt` and `a/C:b` in portable relative-path parsing and every `FileStore` key, and reject leading drive-relative spellings on `Root` destinations and `resolve()` with `invalid-path`. Existing-object Root operations, including reads, inspection, removal, and the source of `move()`, continue to accept legal POSIX filenames such as `c:notes.txt`; thanks @Yigtwxx for the fix.
810

911
- Apply atomic-replacement parent-directory modes through verified no-follow descriptors on POSIX, so a directory-entry swap cannot redirect `chmod` through a symlink to an unrelated directory. Windows keeps its explicit `mkdir(mode)`-only behavior because Node does not enforce POSIX directory modes there.

‎src/move-path.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,24 @@ function regularReadFlags(): number {
169169
);
170170
}
171171

172+
async function chmodDirectoryPinned(directoryPath: string, mode: number): Promise<void> {
173+
if (process.platform === "win32") {
174+
// Node cannot portably open a Windows directory for descriptor-bound
175+
// chmod. POSIX modes are not enforced there, so do not fall back to a
176+
// pathname operation that could follow a replacement symlink.
177+
return;
178+
}
179+
const handle = await fs.open(
180+
directoryPath,
181+
fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,
182+
);
183+
try {
184+
await handle.chmod(mode);
185+
} finally {
186+
await handle.close();
187+
}
188+
}
189+
172190
async function writeAll(handle: FileHandle, buffer: Buffer, bytesRead: number): Promise<void> {
173191
let offset = 0;
174192
while (offset < bytesRead) {
@@ -219,20 +237,19 @@ async function copyRegularFilePinned(params: {
219237
}
220238
await writeAll(destinationHandle, scratch, bytesRead);
221239
}
240+
// Re-check the opened source before the staged tree can be committed. If
241+
// it changed while we copied, the caller should retry the move.
242+
const finalSourceStat = await sourceHandle.stat();
243+
if (params.rejectHardlinks && finalSourceStat.nlink > 1) {
244+
throw hardlinkedSourceError(params.from);
245+
}
246+
if (!sameIdentity(params.identity, entryIdentity(finalSourceStat))) {
247+
throw sourceChangedError(params.from);
248+
}
249+
await destinationHandle.chmod(modeBits(params.mode)).catch(() => undefined);
222250
} finally {
223251
await destinationHandle.close();
224252
}
225-
226-
// Re-check the opened handle before the staged tree can be committed. If
227-
// the source changed while we copied, the caller should retry the move.
228-
const finalSourceStat = await sourceHandle.stat();
229-
if (params.rejectHardlinks && finalSourceStat.nlink > 1) {
230-
throw hardlinkedSourceError(params.from);
231-
}
232-
if (!sameIdentity(params.identity, entryIdentity(finalSourceStat))) {
233-
throw sourceChangedError(params.from);
234-
}
235-
await fs.chmod(params.to, modeBits(params.mode)).catch(() => undefined);
236253
} catch (error) {
237254
if (destinationCreated) {
238255
await fs.rm(params.to, { force: true }).catch(() => undefined);
@@ -284,7 +301,7 @@ async function copyEntryWithManifest(
284301
await assertSourceStillMatches(from, identity);
285302
// mkdir() honors process umask. Restore the source mode before commit so
286303
// EXDEV fallback preserves directory permissions like fs.cp did.
287-
await fs.chmod(to, modeBits(sourceStat.mode));
304+
await chmodDirectoryPinned(to, modeBits(sourceStat.mode));
288305
return { ...identity, children, kind: "directory" };
289306
}
290307

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { movePathWithCopyFallback } from "../src/move-path.js";
6+
7+
const tempDirs: string[] = [];
8+
9+
async function tempRoot(prefix: string): Promise<string> {
10+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
11+
tempDirs.push(dir);
12+
return dir;
13+
}
14+
15+
async function installStagingModeSwap(params: {
16+
targetDir: string;
17+
victimPath: string;
18+
symlinkType: "dir" | "file";
19+
}): Promise<() => number> {
20+
const probePath = path.join(params.targetDir, "handle-probe");
21+
const probe = await fs.open(probePath, "w");
22+
const handlePrototype = Object.getPrototypeOf(probe) as {
23+
chmod(mode: number): Promise<void>;
24+
};
25+
const realHandleChmod = handlePrototype.chmod;
26+
await probe.close();
27+
await fs.unlink(probePath);
28+
29+
const realPathChmod = fs.chmod;
30+
let swaps = 0;
31+
32+
const findStagingPath = async (): Promise<string> => {
33+
const name = (await fs.readdir(params.targetDir)).find(
34+
(entry) => entry.startsWith(".fs-safe-move-") && entry.endsWith(".tmp"),
35+
);
36+
if (!name) {
37+
throw new Error("move staging entry not found");
38+
}
39+
return path.join(params.targetDir, name);
40+
};
41+
42+
const swapAround = async (stagingPath: string, applyMode: () => Promise<void>) => {
43+
swaps += 1;
44+
const parkedPath = `${stagingPath}.parked`;
45+
await fs.rename(stagingPath, parkedPath);
46+
await fs.symlink(params.victimPath, stagingPath, params.symlinkType);
47+
try {
48+
await applyMode();
49+
} finally {
50+
await fs.unlink(stagingPath);
51+
await fs.rename(parkedPath, stagingPath);
52+
}
53+
};
54+
55+
vi.spyOn(fs, "chmod").mockImplementation(async (candidate, mode) => {
56+
const candidatePath = String(candidate);
57+
if (!path.basename(candidatePath).startsWith(".fs-safe-move-")) {
58+
await realPathChmod(candidate, mode);
59+
return;
60+
}
61+
await swapAround(candidatePath, async () => await realPathChmod(candidate, mode));
62+
});
63+
vi.spyOn(handlePrototype, "chmod").mockImplementation(async function (mode) {
64+
const stagingPath = await findStagingPath();
65+
await swapAround(stagingPath, async () => await realHandleChmod.call(this, mode));
66+
});
67+
68+
return () => swaps;
69+
}
70+
71+
afterEach(async () => {
72+
vi.restoreAllMocks();
73+
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { force: true, recursive: true })));
74+
});
75+
76+
describe.runIf(process.platform !== "win32")("move staging descriptor modes", () => {
77+
it("does not redirect a staged file mode through a swapped symlink", async () => {
78+
const sourceDir = await tempRoot("fs-safe-move-file-source-");
79+
const targetDir = await tempRoot("fs-safe-move-file-target-");
80+
const victimDir = await tempRoot("fs-safe-move-file-victim-");
81+
const sourcePath = path.join(sourceDir, "source.txt");
82+
const targetPath = path.join(targetDir, "target.txt");
83+
const victimPath = path.join(victimDir, "victim.txt");
84+
await fs.writeFile(sourcePath, "source");
85+
await fs.chmod(sourcePath, 0o666);
86+
await fs.writeFile(victimPath, "victim");
87+
await fs.chmod(victimPath, 0o644);
88+
const swaps = await installStagingModeSwap({
89+
targetDir,
90+
victimPath,
91+
symlinkType: "file",
92+
});
93+
94+
const previousUmask = process.umask(0o077);
95+
try {
96+
await movePathWithCopyFallback({
97+
from: sourcePath,
98+
sourceHardlinks: "reject",
99+
to: targetPath,
100+
});
101+
} finally {
102+
process.umask(previousUmask);
103+
}
104+
105+
expect({
106+
publishedMode: (await fs.stat(targetPath)).mode & 0o777,
107+
swaps: swaps(),
108+
victimMode: (await fs.stat(victimPath)).mode & 0o777,
109+
}).toEqual({ publishedMode: 0o666, swaps: 1, victimMode: 0o644 });
110+
});
111+
112+
it("does not redirect a staged directory mode through a swapped symlink", async () => {
113+
const sourceParent = await tempRoot("fs-safe-move-dir-source-");
114+
const targetDir = await tempRoot("fs-safe-move-dir-target-");
115+
const victimParent = await tempRoot("fs-safe-move-dir-victim-");
116+
const sourcePath = path.join(sourceParent, "source");
117+
const targetPath = path.join(targetDir, "target");
118+
const victimPath = path.join(victimParent, "victim");
119+
await fs.mkdir(sourcePath, { mode: 0o777 });
120+
await fs.chmod(sourcePath, 0o777);
121+
await fs.mkdir(victimPath, { mode: 0o755 });
122+
await fs.chmod(victimPath, 0o755);
123+
const swaps = await installStagingModeSwap({
124+
targetDir,
125+
victimPath,
126+
symlinkType: "dir",
127+
});
128+
129+
const previousUmask = process.umask(0o077);
130+
try {
131+
await movePathWithCopyFallback({
132+
from: sourcePath,
133+
sourceHardlinks: "reject",
134+
to: targetPath,
135+
});
136+
} finally {
137+
process.umask(previousUmask);
138+
}
139+
140+
expect({
141+
publishedMode: (await fs.stat(targetPath)).mode & 0o777,
142+
swaps: swaps(),
143+
victimMode: (await fs.stat(victimPath)).mode & 0o777,
144+
}).toEqual({ publishedMode: 0o777, swaps: 1, victimMode: 0o755 });
145+
});
146+
});

0 commit comments

Comments
 (0)