Skip to content

Commit eda9a61

Browse files
steipeteYigtwxx
andauthored
fix(root): scope drive-relative destination guards (#97)
path.win32.isAbsolute() reports false for the drive-relative spelling C:name while path.resolve() still consumes the prefix, so C:secret.txt aliased secret.txt on Windows and C:.. slipped past the .. check, letting splitSafeRelativePath() violate its own documented postcondition. The rejection applies where a path is created or resolved: safe-relative parsing, every FileStore key, Root resolve, write, create, append, openWritable, mkdir, copyIn, and the destination of move. It does not apply to operations on an object that already exists — reads, stat, exists, list, walk, remove, and the source of move — because c:notes.txt is a legal POSIX filename and refusing to read a file that exists is collateral rather than containment. isDriveRelativePath stays internal and is absent from the published ./path subpath. Supersedes #85. Co-authored-by: Yigtwxx <[email protected]>
1 parent 14448ba commit eda9a61

11 files changed

Lines changed: 245 additions & 12 deletions

‎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+
- 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.
8+
79
- 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.
810
- Retry a contended file-lock acquisition when Windows denies access to a lock file whose directory entry is still being torn down, including when the native binding performs the exclusive create. Both the exclusive create and the holder's snapshot read reported that transient `EPERM` as a hard failure, so concurrent `acquireFileLock()` calls failed intermittently on Windows even though the very next attempt would have succeeded. Retries stay bounded, so a genuine permission denial still surfaces as `EPERM` rather than a lock timeout; thanks @Yigtwxx for the fix.
911
- Apply `replaceFileAtomic()` and `replaceFileAtomicSync()` modes through pinned temp-file descriptors before rename, and through pinned copy-fallback descriptors, so a post-rename symlink swap cannot redirect `chmod` to an unrelated file while exact modes remain independent of umask; thanks @yetval for reporting this (#86).

‎docs/errors.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ type FsSafeErrorCode =
9696
| `helper-failed` | A native mechanism or multi-step operational helper failed. | Inspect `cause` and any operation-specific `details`; retrying may be unsafe if the operation partially completed. |
9797
| `helper-unavailable` | Required native binding could not be loaded. | Unsupported platform, missing/incompatible bundled binary, or `FS_SAFE_NATIVE_MODE=require`. `auto` falls back where possible; `require` fails closed. |
9898
| `insecure-permissions` | A secure file or path permission check found a mode/ACL that allows broader access than requested. | File or directory is group/world writable/readable; Windows ACL grants broad read. |
99-
| `invalid-path` | Input was empty, contained NUL, was an unparseable URL, or otherwise unusable. | Caller didn't validate input; input was a network path on Windows. |
99+
| `invalid-path` | Input was empty, contained NUL, was an unparseable URL, or otherwise unusable. | Caller didn't validate input; input was a network path on Windows, a drive-relative segment in a portable relative path or store key, or a leading drive-relative spelling such as `C:name` used as a Root destination. Existing-object Root lookups retain legal POSIX drive-like names. |
100100
| `not-empty` | `remove()` on a non-empty directory. | Use `replaceDirectoryAtomic` or remove children first. |
101101
| `not-file` | Read or copy targeted a non-regular file. | Target was a directory, FIFO, socket, device. |
102102
| `not-found` | The target does not exist (or its parent does not, with `mkdir: false`). | Typical missing-file case. |

‎docs/file-store.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ type FileStore = {
6464

6565
`path()` returns the absolute path the store would use, after asserting it stays inside `rootDir`. Useful for logging or for handing to other libraries.
6666

67+
Every `relativePath` is a portable store key, including keys passed to reads,
68+
`exists`, and `remove`. A segment with a Windows drive-relative spelling such
69+
as `C:name` (including an embedded segment such as `a/C:name`) throws
70+
`invalid-path` on every platform. This prevents a key created on POSIX from
71+
aliasing a different file when the store is moved to Windows. Colons elsewhere,
72+
such as the timestamp in `logs/2026-08-02T10:30:00Z.log`, remain valid.
73+
6774
`root()` returns a [`Root`](root.md) handle for the same directory when you need the full surface (move, list, mkdir). It's a fresh handle per call and is safe to call frequently.
6875

6976
## Writes

‎docs/root.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,14 @@ fs.ensureRoot(options?) // accepts "" / "." as the root itself
103103
104104
`copyIn` is a one-shot ingest from a trusted absolute source path: it streams the source through the boundary, atomically renames into the root, and respects `maxBytes`.
105105
106+
Root operations that choose a new destination reject a leading Windows
107+
drive-relative spelling such as `C:name` on every platform. This applies to
108+
`write`, `create`, `append`, `openWritable`, `mkdir`, `copyIn`, and the
109+
destination argument of `move`. In particular, `copyIn(path.basename(source),
110+
source)` can reject a legal POSIX basename such as `c:photo.png`; callers that
111+
derive portable destination names from host files must sanitize or map that
112+
basename first.
113+
106114
`openWritable` opens a writable file with options `mode?: number` and `writeMode?: "replace" | "append" | "update"`. `replace` truncates existing files and is the default; `update` keeps existing contents. Use it for streaming output. Prefer `await using` for cleanup.
107115
108116
All mutation methods accept `denyMutations?: { paths?: string[]; prefixes?: string[] }`. Entries must be absolute paths. `paths` blocks those exact paths; `prefixes` blocks those paths and their descendants. fs-safe preserves path strings exactly and canonicalizes through existing ancestors before comparing, so a symlinked ancestor to a denied location is still denied. Denied mutations throw `FsSafeError` with code `denied-path`. Use this for caller-specific sensitive paths, not as a replacement for the root boundary, symlink, or hardlink checks.
@@ -119,6 +127,12 @@ fs.resolve(rel) // absolute path inside the root, after canonic
119127
120128
These do not pin a later operation. They are safe to expose to UIs and decision points; for the actual read or write, use the verb methods so the operation pins identity at the point of use.
121129
130+
`resolve()` is the exception to the existing-object rule: because it selects a
131+
location for later use, it rejects a leading drive-relative spelling. Reads,
132+
`stat`, `exists`, `list`, `walk`, `remove`, and the source argument of `move`
133+
accept an existing POSIX filename such as `c:notes.txt`. For `move`, only the
134+
new destination name is subject to the portable guard.
135+
122136
## Native helper mode
123137
124138
Create-only writes prefer the bundled native helper for fd-relative opens and
@@ -151,7 +165,7 @@ Every method throws `FsSafeError` with a `code`. Branch on `err.code`, not messa
151165
152166
| Code | When it fires |
153167
|---|---|
154-
| `invalid-path` | The input path is malformed, including embedded NUL bytes. |
168+
| `invalid-path` | The input path is malformed, including embedded NUL bytes. Portable relative-path helpers and `FileStore` keys reject drive-relative segments; Root destination and resolution operations reject a leading drive-relative spelling such as `C:name`. |
155169
| `outside-workspace` | The input resolves outside the root, or contains a `..` segment that would escape it. |
156170
| `not-found` | The target does not exist (or its parent does not, with `mkdir: false`). |
157171
| `not-file` | A read or copy targeted a non-regular file (directory, FIFO, socket, …). |

‎src/file-store.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ import type { Readable } from "node:stream";
66
import { readFileDescriptorBoundedSync } from "./bounded-read.js";
77
import { createSyncDirectoryGuard } from "./directory-guard.js";
88
import { FsSafeError } from "./errors.js";
9-
import {
10-
pruneExpiredStoreEntries,
11-
type FileStorePruneOptions,
12-
} from "./file-store-prune.js";
9+
import { pruneExpiredStoreEntries, type FileStorePruneOptions } from "./file-store-prune.js";
1310
export type { FileStorePruneOptions } from "./file-store-prune.js";
1411
import {
1512
assertSyncDirectoryGuard,
@@ -26,6 +23,7 @@ import { isPathInside, resolveSafeRelativePath } from "./path.js";
2623
import { root, type OpenResult, type ReadResult, type Root, type RootReadOptions } from "./root.js";
2724
import { DEFAULT_ROOT_MAX_BYTES } from "./root-impl.js";
2825
import { matchRootFileOpenFailure, openRootFileSync, type RootFileOpenFailure } from "./root-file.js";
26+
import { assertNoDriveRelativePathSegments } from "./safe-path-segment.js";
2927
import { writeSecretFileAtomic } from "./secret-file.js";
3028
import { getFsSafeTestHooks } from "./test-hooks.js";
3129

@@ -113,7 +111,7 @@ function assertRelativePath(relativePath: string): string {
113111
if (!raw) {
114112
throw new FsSafeError("invalid-path", "relative path must be non-empty");
115113
}
116-
return raw.replaceAll("\\", "/");
114+
return assertNoDriveRelativePathSegments(raw.replaceAll("\\", "/"), "store key");
117115
}
118116

119117
function resolveStorePath(rootDir: string, relativePath: string): string {

‎src/path.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from "node:fs";
22
import path from "node:path";
33

44
import { FsSafeError } from "./errors.js";
5+
import { isDriveRelativePath } from "./safe-path-segment.js";
56

67
export {
78
assertNoUnsafeDeviceReadPath,
@@ -156,6 +157,9 @@ export function splitSafeRelativePath(relativePath: string): string[] {
156157
if (segment === "..") {
157158
throw new FsSafeError("invalid-path", "relative path must not contain '..'");
158159
}
160+
if (isDriveRelativePath(segment)) {
161+
throw new FsSafeError("invalid-path", "relative path must not contain a drive letter");
162+
}
159163
}
160164
return segments;
161165
}

‎src/root-context.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { FsSafeError } from "./errors.js";
55
import { expandHomePrefix } from "./home-dir.js";
66
import { assertNoNulPathInput, isNotFoundPathError, isPathInside } from "./path.js";
77
import { ROOT_PATH_ALIAS_POLICIES, resolveRootPath } from "./root-path.js";
8+
import { isDriveRelativePath } from "./safe-path-segment.js";
89

910
export type RootContext = {
1011
rootDir: string;
@@ -19,6 +20,13 @@ export function assertValidRootRelativePath(relativePath: string): void {
1920
assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
2021
}
2122

23+
export function assertValidRootDestinationPath(relativePath: string): void {
24+
assertValidRootRelativePath(relativePath);
25+
if (isDriveRelativePath(relativePath)) {
26+
throw new FsSafeError("invalid-path", "relative path must not start with a drive letter");
27+
}
28+
}
29+
2230
let cachedHomePath: { raw: string; real: string } | undefined;
2331

2432
export async function expandRelativePathWithHome(relativePath: string): Promise<string> {

‎src/root-impl.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { readOpenedFileSafely, type ReadResult } from "./read-opened-file.js";
3636
import { pathStatFromStats } from "./path-stat.js";
3737
import { resolveRootPath } from "./root-path.js";
3838
import {
39+
assertValidRootDestinationPath,
3940
assertValidRootRelativePath,
4041
ensureTrailingSep,
4142
expandRelativePathWithHome,
@@ -364,6 +365,7 @@ class RootHandle implements Root {
364365
}
365366

366367
async resolve(relativePath: string): Promise<string> {
368+
assertValidRootDestinationPath(relativePath);
367369
return (
368370
await resolvePathInRoot(this.context, relativePath, { allowFinalSymlink: true })
369371
).resolved;
@@ -428,6 +430,7 @@ class RootHandle implements Root {
428430
relativePath: string,
429431
options: RootOpenWritableOptions = {},
430432
): Promise<WritableOpenResult> {
433+
assertValidRootDestinationPath(relativePath);
431434
const writeMode = options.writeMode ?? "replace";
432435
return await openWritableFileInRoot(this.context, {
433436
relativePath,
@@ -441,6 +444,7 @@ class RootHandle implements Root {
441444
}
442445

443446
async append(relativePath: string, data: string | Buffer, options: RootAppendOptions = {}): Promise<void> {
447+
assertValidRootDestinationPath(relativePath);
444448
await appendFileInRoot(this.context, {
445449
relativePath,
446450
data,
@@ -460,7 +464,7 @@ class RootHandle implements Root {
460464
}
461465

462466
async mkdir(relativePath: string, options: RootMkdirOptions = {}): Promise<void> {
463-
assertValidRootRelativePath(relativePath);
467+
assertValidRootDestinationPath(relativePath);
464468
await mkdirPathInRoot(this.context, {
465469
relativePath,
466470
denyMutations: mergeDenyMutationPolicies(this.defaults.denyMutations, options.denyMutations),
@@ -480,6 +484,7 @@ class RootHandle implements Root {
480484
data: string | Buffer,
481485
options: RootWriteOptions = {},
482486
): Promise<void> {
487+
assertValidRootDestinationPath(relativePath);
483488
await writeFileInRoot(this.context, {
484489
relativePath,
485490
data,
@@ -496,6 +501,7 @@ class RootHandle implements Root {
496501
data: string | Buffer,
497502
options: RootCreateOptions = {},
498503
): Promise<void> {
504+
assertValidRootDestinationPath(relativePath);
499505
await writeFileInRoot(this.context, {
500506
relativePath,
501507
data,
@@ -532,7 +538,7 @@ class RootHandle implements Root {
532538
sourcePath: string,
533539
options: RootCopyOptions = {},
534540
): Promise<void> {
535-
assertValidRootRelativePath(relativePath);
541+
assertValidRootDestinationPath(relativePath);
536542
await copyFileInRoot(this.context, {
537543
sourcePath,
538544
relativePath,
@@ -579,7 +585,7 @@ class RootHandle implements Root {
579585
options: RootMoveOptions = {},
580586
): Promise<void> {
581587
assertValidRootRelativePath(fromRelative);
582-
assertValidRootRelativePath(toRelative);
588+
assertValidRootDestinationPath(toRelative);
583589
validatePinnedOperationPayload({ from: fromRelative, to: toRelative });
584590
const denyMutations = mergeDenyMutationPolicies(
585591
this.defaults.denyMutations,

‎src/safe-path-segment.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,27 @@ import { FsSafeError } from "./errors.js";
22

33
const SAFE_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
44
const SAFE_DOT_PREFIX_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
5+
// Windows treats "C:name" as relative to the drive's current directory even
6+
// though path.win32.isAbsolute() reports false.
7+
const DRIVE_RELATIVE_PREFIX = /^[A-Za-z]:(?![\\/])/;
58
const HYPHEN_CHAR_CODE = 0x2d;
69

710
export type SafePathSegmentOptions = {
811
allowDotPrefix?: boolean;
912
label?: string;
1013
};
1114

15+
export function isDriveRelativePath(value: string): boolean {
16+
return DRIVE_RELATIVE_PREFIX.test(value);
17+
}
18+
19+
export function assertNoDriveRelativePathSegments(value: string, label: string): string {
20+
if (value.split("/").some(isDriveRelativePath)) {
21+
throw new FsSafeError("invalid-path", `${label} must not contain a drive letter`);
22+
}
23+
return value;
24+
}
25+
1226
function trimHyphenEdges(value: string): string {
1327
let start = 0;
1428
let end = value.length;

‎test/api-coverage.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ describe("path helpers", () => {
257257
expect(safeStatSync(path.join(root, "missing"))).toBeNull();
258258
expect(() => assertNoNulPathInput("a\0b")).toThrow("NUL");
259259
expect(splitSafeRelativePath("./a//b")).toEqual(["a", "b"]);
260-
for (const bad of ["../x", "/x", "C:\\x", "a\\b", "a\0b"]) {
260+
for (const bad of ["../x", "/x", "C:\\x", "C:evil", "C:..", "a/C:b", "a\\b", "a\0b"]) {
261261
expect(() => splitSafeRelativePath(bad)).toThrow();
262262
}
263263
expect(resolveSafeRelativePath(root, "a/b")).toBe(path.join(root, "a", "b"));

0 commit comments

Comments
 (0)