Skip to content

Commit be27814

Browse files
authored
fix(store): consolidate mutation guards (#107)
Two store-directory walkers implemented the same algorithm and had drifted. The private walker recomputed the root realpath on every segment, so a root swapped mid-walk was silently adopted rather than detected. Neither naive form was correct: re-resolving follows the swap and hoisting cannot see it. The unified helper pins the root path and inode once, then revalidates identity per segment. The regression fails on the previous implementation. deny-mutations.ts also carried a private copy of the existing-ancestor resolver with a different loop guard. Both guards canonicalized the reported Windows paths identically after path.resolve, so removing the duplicate is cleanup rather than a behavior change; the Windows lanes confirm it. The four write-guard prologues in root-impl.ts now share one helper, preserving the move-fallback exception, so a new write entry point cannot omit the deny or alias check. Error codes, messages, and the public surface are unchanged.
1 parent 947fa83 commit be27814

7 files changed

Lines changed: 188 additions & 156 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Security and Correctness
66

7+
- Pin synchronous file-store roots across every parent-walk segment, so private and non-private writes reject a store root replaced during directory creation, and route deny-mutation ancestor canonicalization through the shared root resolver on Windows and POSIX.
78
- Keep the POSIX parent-directory no-follow identity check active for synchronous atomic-replacement adapters that omit `fchmodSync`, preventing the documented default adapter path from writing through a symlinked parent.
89
- Synchronize the actual destination after descriptor-bound mode application when atomic rename uses copy fallback, and include both bytes and mode in bounded fallback restoration.
910
- Continue accepting legacy atomic-replacement adapter literals that expose pathname `chmod` or `chmodSync` methods while keeping those methods unused.

‎src/deny-mutations.ts‎

Lines changed: 6 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,9 @@
1-
import fs from "node:fs/promises";
21
import path from "node:path";
32
import { FsSafeError } from "./errors.js";
4-
import { assertNoNulPathInput, isNotFoundPathError, isPathInside } from "./path.js";
3+
import { assertNoNulPathInput, isPathInside } from "./path.js";
4+
import { resolvePathViaExistingAncestor } from "./root-path-existing.js";
55

6-
async function pathExists(filePath: string): Promise<boolean> {
7-
try {
8-
await fs.lstat(filePath);
9-
return true;
10-
} catch (err) {
11-
if (!isNotFoundPathError(err)) {
12-
throw err;
13-
}
14-
return false;
15-
}
16-
}
17-
18-
async function resolvePathViaExistingAncestor(targetPath: string): Promise<string> {
19-
const normalized = path.resolve(targetPath);
20-
let cursor = normalized;
21-
const missingSuffix: string[] = [];
22-
23-
while (path.dirname(cursor) !== cursor && !(await pathExists(cursor))) {
24-
missingSuffix.unshift(path.basename(cursor));
25-
cursor = path.dirname(cursor);
26-
}
27-
28-
if (!(await pathExists(cursor))) {
29-
return normalized;
30-
}
31-
32-
try {
33-
const resolvedAncestor = path.resolve(await fs.realpath(cursor));
34-
return missingSuffix.length === 0
35-
? resolvedAncestor
36-
: path.resolve(resolvedAncestor, ...missingSuffix);
37-
} catch {
38-
return normalized;
39-
}
40-
}
41-
42-
async function comparablePaths(rawPath: string): Promise<Set<string>> {
6+
export async function resolveMutationComparablePaths(rawPath: string): Promise<Set<string>> {
437
assertNoNulPathInput(rawPath, "path contains a NUL byte");
448
const resolved = path.resolve(rawPath);
459
return new Set([resolved, await resolvePathViaExistingAncestor(resolved)]);
@@ -86,9 +50,9 @@ export async function assertMutationNotDenied(
8650
return;
8751
}
8852

89-
const targetPaths = await comparablePaths(filePath);
53+
const targetPaths = await resolveMutationComparablePaths(filePath);
9054
for (const deniedPath of policyPathEntries(policy.paths)) {
91-
const deniedPaths = await comparablePaths(deniedPath);
55+
const deniedPaths = await resolveMutationComparablePaths(deniedPath);
9256
for (const target of targetPaths) {
9357
for (const denied of deniedPaths) {
9458
if (
@@ -102,7 +66,7 @@ export async function assertMutationNotDenied(
10266
}
10367

10468
for (const deniedPrefix of policyPathEntries(policy.prefixes)) {
105-
const deniedPaths = await comparablePaths(deniedPrefix);
69+
const deniedPaths = await resolveMutationComparablePaths(deniedPrefix);
10670
for (const target of targetPaths) {
10771
for (const denied of deniedPaths) {
10872
if (

‎src/file-store-boundary.ts‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
type SyncDirectoryGuard,
1010
} from "./directory-guard.js";
1111
import { FsSafeError } from "./errors.js";
12+
import { sameFileIdentity } from "./file-identity.js";
1213
import { isPathInside, isPathRelativeEscape } from "./path.js";
1314
import { resolveOpenedFileRealPathForHandle, root, type Root } from "./root.js";
1415
import { resolveSecureTempRoot } from "./secure-temp-dir.js";
@@ -158,9 +159,23 @@ export function ensureParentSync(params: {
158159
rootDir: string;
159160
filePath: string;
160161
mode: number;
162+
}): SyncParentGuard {
163+
return ensureStoreDirectorySync({
164+
rootDir: params.rootDir,
165+
targetDir: path.dirname(path.resolve(params.filePath)),
166+
mode: params.mode,
167+
messagePrefix: "store",
168+
});
169+
}
170+
171+
export function ensureStoreDirectorySync(params: {
172+
rootDir: string;
173+
targetDir: string;
174+
mode: number;
175+
messagePrefix: "private store" | "store";
161176
}): SyncParentGuard {
162177
const rootDir = path.resolve(params.rootDir);
163-
const dir = path.dirname(path.resolve(params.filePath));
178+
const dir = path.resolve(params.targetDir);
164179
const relative = path.relative(rootDir, dir);
165180
if (isPathRelativeEscape(relative)) {
166181
throw new FsSafeError("outside-workspace", "file path escapes store root");
@@ -169,7 +184,10 @@ export function ensureParentSync(params: {
169184
syncFs.mkdirSync(rootDir, { recursive: true, mode: params.mode });
170185
const rootStat = syncFs.lstatSync(rootDir);
171186
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
172-
throw new FsSafeError("not-file", `store root must be a directory: ${rootDir}`);
187+
throw new FsSafeError(
188+
"not-file",
189+
`${params.messagePrefix} root must be a directory: ${rootDir}`,
190+
);
173191
}
174192
const rootReal = syncFs.realpathSync(rootDir);
175193
chmodDirectorySyncBestEffort(rootDir, params.mode);
@@ -180,17 +198,31 @@ export function ensureParentSync(params: {
180198
try {
181199
const stat = syncFs.lstatSync(current);
182200
if (stat.isSymbolicLink() || !stat.isDirectory()) {
183-
throw new FsSafeError("not-file", `store directory component must be a directory: ${current}`);
201+
throw new FsSafeError(
202+
"not-file",
203+
`${params.messagePrefix} directory component must be a directory: ${current}`,
204+
);
184205
}
185206
} catch (error) {
186207
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
187208
throw error;
188209
}
189210
syncFs.mkdirSync(current, { mode: params.mode });
190211
}
212+
const currentRootStat = syncFs.lstatSync(rootDir);
213+
const currentRootReal = syncFs.realpathSync(rootDir);
191214
const currentReal = syncFs.realpathSync(current);
192-
if (!isPathInside(rootReal, currentReal)) {
193-
throw new FsSafeError("outside-workspace", "store directory escapes root");
215+
if (
216+
currentRootStat.isSymbolicLink() ||
217+
!currentRootStat.isDirectory() ||
218+
!sameFileIdentity(rootStat, currentRootStat) ||
219+
currentRootReal !== rootReal ||
220+
!isPathInside(rootReal, currentReal)
221+
) {
222+
throw new FsSafeError(
223+
"outside-workspace",
224+
`${params.messagePrefix} directory escapes root`,
225+
);
194226
}
195227
chmodDirectorySyncBestEffort(current, params.mode);
196228
}

‎src/file-store.ts‎

Lines changed: 7 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import fs from "node:fs/promises";
44
import path from "node:path";
55
import type { Readable } from "node:stream";
66
import { readFileDescriptorBoundedSync } from "./bounded-read.js";
7-
import { createSyncDirectoryGuard } from "./directory-guard.js";
87
import { FsSafeError } from "./errors.js";
98
import { pruneExpiredStoreEntries, type FileStorePruneOptions } from "./file-store-prune.js";
109
export type { FileStorePruneOptions } from "./file-store-prune.js";
1110
import {
1211
assertSyncDirectoryGuard,
1312
ensureParentInRoot,
1413
ensureParentSync,
14+
ensureStoreDirectorySync,
1515
openWritableStoreRoot,
1616
type SyncParentGuard,
1717
writeStreamToTempSource,
@@ -394,50 +394,12 @@ export function fileStore(options: FileStoreOptions): FileStore {
394394
}
395395

396396
function ensurePrivateDirectorySync(rootDir: string, targetDir: string, mode: number): SyncParentGuard {
397-
const root = path.resolve(rootDir);
398-
const target = path.resolve(targetDir);
399-
assertStoreFilePath(root, target);
400-
let current = root;
401-
syncFs.mkdirSync(current, { recursive: true, mode });
402-
const rootStat = syncFs.lstatSync(current);
403-
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
404-
throw new FsSafeError("not-file", `private store root must be a directory: ${current}`);
405-
}
406-
try {
407-
syncFs.chmodSync(current, mode);
408-
} catch {
409-
// Best-effort on platforms that do not enforce POSIX modes.
410-
}
411-
for (const segment of path.relative(root, target).split(path.sep).filter(Boolean)) {
412-
current = path.join(current, segment);
413-
try {
414-
const stat = syncFs.lstatSync(current);
415-
if (stat.isSymbolicLink() || !stat.isDirectory()) {
416-
throw new FsSafeError(
417-
"not-file",
418-
`private store directory component must be a directory: ${current}`,
419-
);
420-
}
421-
} catch (error) {
422-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
423-
throw error;
424-
}
425-
syncFs.mkdirSync(current, { mode });
426-
}
427-
const rootReal = syncFs.realpathSync(root);
428-
const currentReal = syncFs.realpathSync(current);
429-
if (!isPathInside(rootReal, currentReal)) {
430-
throw new FsSafeError("outside-workspace", "private store directory escapes root");
431-
}
432-
try {
433-
syncFs.chmodSync(current, mode);
434-
} catch {
435-
// Best-effort on platforms that do not enforce POSIX modes.
436-
}
437-
}
438-
const guard = createSyncDirectoryGuard(target);
439-
assertSyncDirectoryGuard(guard);
440-
return guard;
397+
return ensureStoreDirectorySync({
398+
rootDir,
399+
targetDir,
400+
mode,
401+
messagePrefix: "private store",
402+
});
441403
}
442404

443405
function writeFileSyncAtomic(params: {

‎src/root-impl.ts‎

Lines changed: 63 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,43 @@ async function verifyAtomicWriteResult(params: {
809809
}
810810
}
811811

812+
type GuardedWritePath = Awaited<ReturnType<typeof resolvePathInRoot>>;
813+
814+
async function resolveGuardedWritePathInRoot(
815+
root: RootContext,
816+
params: {
817+
relativePath: string;
818+
denyMutations?: DenyMutationPolicy;
819+
allowFinalSymlink?: boolean;
820+
protectDeniedAncestors?: boolean;
821+
shouldAssertNoPathAlias?: (resolved: GuardedWritePath) => Promise<boolean> | boolean;
822+
},
823+
): Promise<GuardedWritePath> {
824+
const resolvedPath = await resolvePathInRoot(root, params.relativePath, {
825+
aliasErrorCode: "path-alias",
826+
allowFinalSymlink: params.allowFinalSymlink,
827+
});
828+
await assertMutationNotDenied(
829+
resolvedPath.resolved,
830+
params.denyMutations,
831+
params.protectDeniedAncestors ? { protectAncestors: true } : undefined,
832+
);
833+
if (await (params.shouldAssertNoPathAlias?.(resolvedPath) ?? true)) {
834+
try {
835+
await assertNoPathAliasEscape({
836+
absolutePath: resolvedPath.resolved,
837+
rootPath: resolvedPath.rootReal,
838+
boundaryLabel: "root",
839+
});
840+
} catch (error) {
841+
throw new FsSafeError("path-alias", "path alias escape blocked", {
842+
cause: error instanceof Error ? error : undefined,
843+
});
844+
}
845+
}
846+
return resolvedPath;
847+
}
848+
812849
async function openWritableFileInRoot(
813850
root: RootContext,
814851
params: {
@@ -820,21 +857,10 @@ async function openWritableFileInRoot(
820857
append?: boolean;
821858
},
822859
): Promise<WritableOpenResult> {
823-
const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(
824-
root,
825-
params.relativePath,
826-
{ aliasErrorCode: "path-alias" },
827-
);
828-
await assertMutationNotDenied(resolved, params.denyMutations);
829-
try {
830-
await assertNoPathAliasEscape({
831-
absolutePath: resolved,
832-
rootPath: rootReal,
833-
boundaryLabel: "root",
834-
});
835-
} catch (err) {
836-
throw new FsSafeError("path-alias", "path alias escape blocked", { cause: err });
837-
}
860+
const { rootReal, rootWithSep, resolved } = await resolveGuardedWritePathInRoot(root, {
861+
relativePath: params.relativePath,
862+
denyMutations: params.denyMutations,
863+
});
838864
let ioPath = params.mkdir === false
839865
? resolved
840866
: await prepareRootWriteTarget(rootReal, resolved);
@@ -1199,19 +1225,10 @@ async function resolvePinnedWriteTargetInRoot(
11991225
requestedMode?: number,
12001226
denyMutations?: DenyMutationPolicy,
12011227
): Promise<PinnedWriteTarget> {
1202-
const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(root, relativePath, {
1203-
aliasErrorCode: "path-alias",
1228+
const { rootReal, rootWithSep, resolved } = await resolveGuardedWritePathInRoot(root, {
1229+
relativePath,
1230+
denyMutations,
12041231
});
1205-
await assertMutationNotDenied(resolved, denyMutations);
1206-
try {
1207-
await assertNoPathAliasEscape({
1208-
absolutePath: resolved,
1209-
rootPath: rootReal,
1210-
boundaryLabel: "root",
1211-
});
1212-
} catch (err) {
1213-
throw new FsSafeError("path-alias", "path alias escape blocked", { cause: err });
1214-
}
12151232

12161233
// resolvePathInRoot already enforces isPathInside, so any actual escape
12171234
// is rejected upstream.
@@ -1468,31 +1485,24 @@ async function movePathFallback(
14681485
relativePath: params.fromRelative,
14691486
policy: PATH_ALIAS_POLICIES.strict,
14701487
});
1471-
const target = await resolvePathInRoot(root, params.toRelative, {
1472-
aliasErrorCode: "path-alias",
1473-
allowFinalSymlink: true,
1474-
});
1475-
await assertMutationNotDenied(target.resolved, params.denyMutations, { protectAncestors: true });
1476-
await resolvePinnedRootPathInRoot(root, {
1488+
const target = await resolveGuardedWritePathInRoot(root, {
14771489
relativePath: params.toRelative,
1478-
policy: PATH_ALIAS_POLICIES.unlinkTarget,
1479-
});
1480-
const targetStat = await fs.lstat(target.resolved).catch(() => undefined);
1481-
const replacesFinalSymlink =
1482-
process.platform !== "win32" && params.overwrite && targetStat?.isSymbolicLink() === true;
1483-
if (!replacesFinalSymlink) {
1484-
try {
1485-
await assertNoPathAliasEscape({
1486-
absolutePath: target.resolved,
1487-
rootPath: target.rootReal,
1488-
boundaryLabel: "root",
1489-
});
1490-
} catch (error) {
1491-
throw new FsSafeError("path-alias", "path alias escape blocked", {
1492-
cause: error instanceof Error ? error : undefined,
1490+
denyMutations: params.denyMutations,
1491+
allowFinalSymlink: true,
1492+
protectDeniedAncestors: true,
1493+
shouldAssertNoPathAlias: async (resolvedTarget) => {
1494+
await resolvePinnedRootPathInRoot(root, {
1495+
relativePath: params.toRelative,
1496+
policy: PATH_ALIAS_POLICIES.unlinkTarget,
14931497
});
1494-
}
1495-
}
1498+
const targetStat = await fs.lstat(resolvedTarget.resolved).catch(() => undefined);
1499+
return !(
1500+
process.platform !== "win32" &&
1501+
params.overwrite &&
1502+
targetStat?.isSymbolicLink() === true
1503+
);
1504+
},
1505+
});
14961506

14971507
let sourceStat: Stats;
14981508
try {
@@ -1627,19 +1637,10 @@ async function writeMissingFileFallback(
16271637
denyMutations?: DenyMutationPolicy;
16281638
},
16291639
): Promise<void> {
1630-
const { rootReal, resolved } = await resolvePathInRoot(root, params.relativePath, {
1631-
aliasErrorCode: "path-alias",
1640+
const { rootReal, resolved } = await resolveGuardedWritePathInRoot(root, {
1641+
relativePath: params.relativePath,
1642+
denyMutations: params.denyMutations,
16321643
});
1633-
await assertMutationNotDenied(resolved, params.denyMutations);
1634-
try {
1635-
await assertNoPathAliasEscape({
1636-
absolutePath: resolved,
1637-
rootPath: rootReal,
1638-
boundaryLabel: "root",
1639-
});
1640-
} catch (err) {
1641-
throw new FsSafeError("path-alias", "path alias escape blocked", { cause: err });
1642-
}
16431644
const targetPath = params.mkdir === false
16441645
? resolved
16451646
: await prepareRootWriteTarget(rootReal, resolved);

0 commit comments

Comments
 (0)