Skip to content

Commit a4a3726

Browse files
committed
Reject unsafe device read paths
1 parent 6a0236b commit a4a3726

17 files changed

Lines changed: 330 additions & 19 deletions

‎CHANGELOG.md‎

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

33
## Unreleased
44

5+
### Security and Correctness
6+
7+
- Reject known unsafe device and process-fd read paths before opening files, including `/dev/zero`, `/dev/random`, `/dev/fd/*`, `/proc/*/fd/*`, and Windows reserved device names.
8+
59
## 0.3.0 - 2026-05-21
610

711
### Features

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -439,12 +439,12 @@ if (err instanceof FsSafeError) {
439439
}
440440
```
441441

442-
Current `FsSafeErrorCode` values are `already-exists`, `hardlink`, `helper-failed`, `helper-unavailable`, `invalid-path`, `insecure-permissions`, `not-empty`, `not-file`, `not-found`, `not-owned`, `not-removable`, `outside-workspace`, `path-alias`, `path-mismatch`, `permission-unverified`, `symlink`, `timeout`, `too-large`, and `unsupported-platform`.
442+
Current `FsSafeErrorCode` values are `already-exists`, `denied-path`, `device-path`, `hardlink`, `helper-failed`, `helper-unavailable`, `invalid-path`, `insecure-permissions`, `not-empty`, `not-file`, `not-found`, `not-owned`, `not-removable`, `outside-workspace`, `path-alias`, `path-mismatch`, `permission-unverified`, `symlink`, `timeout`, `too-large`, and `unsupported-platform`.
443443

444444
## Safety model
445445

446446
- root-bounded APIs resolve paths against a configured root and reject canonical escapes
447-
- reads open with `O_NOFOLLOW` where available, then verify fd identity matches the path identity before returning the buffer or handle
447+
- reads reject known unsafe device paths, open with `O_NOFOLLOW` where available, then verify fd identity matches the path identity before returning the buffer or handle
448448
- writes use pinned parent-directory helpers and atomic replacement on POSIX, with verified post-write identity
449449
- `remove`, `mkdir`, `move`, `stat`, `list`, and parent-fd writes use one persistent fd-relative Python helper on POSIX, with Node fallbacks when the helper is disabled or unavailable
450450
- archive extraction stages into a private directory and merges through the same boundary checks used by direct writes

‎docs/errors.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class FsSafeError extends Error {
3131
type FsSafeErrorCode =
3232
| "already-exists"
3333
| "denied-path"
34+
| "device-path"
3435
| "hardlink"
3536
| "helper-failed"
3637
| "helper-unavailable"
@@ -57,6 +58,7 @@ type FsSafeErrorCode =
5758
|---|---|---|
5859
| `already-exists` | `create()`, `createJson()`, `move({ overwrite: false })`. | Target file or directory already at the destination. |
5960
| `denied-path` | A root mutation matched `denyMutations.paths` or `denyMutations.prefixes`. | Caller configured application-sensitive paths that must not be written, removed, moved, or created. |
61+
| `device-path` | A read/open target is a known unsafe device or process-fd path. | `/dev/zero`, `/dev/random`, `/dev/stdin`, `/dev/fd/*`, `/proc/*/fd/*`, or a Windows reserved device name. |
6062
| `hardlink` | Read or copy with `hardlinks: "reject"` saw `nlink > 1`. | File is hardlinked — possibly an alias of an out-of-tree inode. |
6163
| `helper-failed` | Internal POSIX helper failed after startup. | Inspect `cause`; retrying may be unsafe if the operation may have partially completed. |
6264
| `helper-unavailable` | Persistent Python helper was disabled or could not be spawned. | `FS_SAFE_PYTHON_MODE=off`, Python missing in PATH, restricted sandbox. `auto` falls back where possible; `require` fails closed. |
@@ -95,6 +97,7 @@ try {
9597
case "not-found":
9698
return reply(404, "missing");
9799
case "symlink":
100+
case "device-path":
98101
case "hardlink":
99102
case "path-mismatch":
100103
case "path-alias":

‎docs/path.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
safeRealpathSync,
1212
safeStatSync,
1313
assertNoNulPathInput,
14+
assertNoUnsafeDeviceReadPath,
15+
isUnsafeDeviceReadPath,
1416
isNotFoundPathError,
1517
isSymlinkOpenError,
1618
hasNodeErrorCode,
@@ -89,6 +91,17 @@ if (!stat?.isFile()) return notFound();
8991

9092
Throws `FsSafeError` with code `invalid-path` when a path string contains an embedded NUL byte. Use it before calling Node `fs` APIs directly; Node's native error can include raw path text in the message.
9193

94+
### `assertNoUnsafeDeviceReadPath(filePath, options?)`
95+
96+
Throws `FsSafeError` with code `device-path` when a read target is a known unsafe device or process-fd path. The built-in read/open helpers call this automatically before opening files; use it only when you are building your own read primitive.
97+
98+
```ts
99+
assertNoUnsafeDeviceReadPath("/dev/zero"); // throws on POSIX
100+
isUnsafeDeviceReadPath("/dev/fd/0"); // true on POSIX
101+
```
102+
103+
The check is intentionally not a normal consumer policy knob. Safe read APIs reject these targets by default because they can block forever, stream indefinitely, or alias process file descriptors.
104+
92105
## Error inspection
93106

94107
### `isNotFoundPathError(err)`

‎docs/reading.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@ Regardless of shape, every read goes through the same boundary checks:
1717
1. Resolve the relative path against the canonical real root.
1818
2. Reject anything that escapes the root (`outside-workspace`).
1919
3. Reject `..` segments and absolute inputs (unless via `readAbsolute` with an in-root absolute path).
20-
4. Open with `O_NOFOLLOW` where available. A symlink in the path triggers `symlink` unless the call's `symlinks` policy is `follow-within-root`.
21-
5. Stat the open fd and compare to the resolved path's identity (`sameFileIdentity`). A swap mid-call triggers `path-mismatch`.
22-
6. If `hardlinks: "reject"`, refuse files with `nlink > 1` (`hardlink`).
23-
7. If `maxBytes` is set, refuse reads larger than the cap (`too-large`).
20+
4. Reject known unsafe device and process-fd paths before opening (`device-path`).
21+
5. Open with `O_NOFOLLOW` where available. A symlink in the path triggers `symlink` unless the call's `symlinks` policy is `follow-within-root`.
22+
6. Stat the open fd and compare to the resolved path's identity (`sameFileIdentity`). A swap mid-call triggers `path-mismatch`.
23+
7. If `hardlinks: "reject"`, refuse files with `nlink > 1` (`hardlink`).
24+
8. If `maxBytes` is set, refuse reads larger than the cap (`too-large`).
2425

2526
## Read shapes
2627

@@ -160,6 +161,7 @@ try {
160161
- **`outside-workspace`** — relative path escaped the root, or `readAbsolute` got an absolute path outside.
161162
- **`not-found`** — the file is gone.
162163
- **`not-file`** — you read a directory or a non-regular file (FIFO, socket, …).
164+
- **`device-path`** — the path targets a known unsafe device or process fd path.
163165
- **`symlink`** — a path component is a symlink and the policy is `reject`.
164166
- **`path-mismatch`** — opened fd identity did not match the resolved path. Almost always a TOCTOU swap by something else.
165167
- **`hardlink`** — `hardlinks: "reject"` saw `nlink > 1`.

‎docs/root.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ Every method throws `FsSafeError` with a `code`. Branch on `err.code`, not messa
139139
| `outside-workspace` | The input resolves outside the root, or contains a `..` segment that would escape it. |
140140
| `not-found` | The target does not exist (or its parent does not, with `mkdir: false`). |
141141
| `not-file` | A read or copy targeted a non-regular file (directory, FIFO, socket, …). |
142+
| `device-path` | A read/open target is a known unsafe device or process-fd path. |
142143
| `already-exists` | `create()` or `move()` without `overwrite` hit an existing target. |
143144
| `denied-path` | A mutation target matched `denyMutations.paths` or `denyMutations.prefixes`. |
144145
| `symlink` | A path component is a symlink, and the call's `symlinks` policy is `reject`. |

‎docs/security-model.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ You hand a `root()` boundary to a piece of code that takes caller-controlled rel
1313
- replaces a path component with a symlink between check and use (TOCTOU)
1414
- replaces the destination directory with a symlink right before a write
1515
- creates a hardlink that aliases an out-of-tree inode and asks you to read or replace it
16+
- asks a read/open primitive to target a known unsafe device or process-fd path
1617
- triggers a partial write that leaves a half-written file at the destination
1718
- ships an archive with `..` paths, absolute paths, or symlinks pointing outside the destination
1819

1920
It does **not** defend against:
2021

2122
- a process running with permissions to write anywhere on the filesystem and choosing to ignore the library
2223
- another process with the same UID racing to mutate the same directory between two separate `fs-safe` calls — the boundary is per-call, not per-session
23-
- traversal across filesystem boundaries, bind mounts, device files, `/proc`-style virtual filesystems, or any other path your process can normally access from inside the root
24+
- arbitrary traversal across filesystem boundaries, bind mounts, or virtual filesystems beyond the known unsafe read device paths
2425
- container escape, TOCTOU between fork and exec of helpers, or kernel-level vulnerabilities
2526
- semantic content checks: file types, archive payload schemas, signature verification
2627

@@ -83,7 +84,7 @@ The library does not advertise different security guarantees per platform — it
8384
|---|---|
8485
| Not ambient authority removal | Code that can import `node:fs` can still bypass the handle. Keep caller-controlled path operations behind `root()` by convention, review, and tests. |
8586
| Absolute paths are escape hatches | APIs that accept or return absolute paths exist for audit, ingest, and advanced composition. Prefer root-relative names in normal application flow. |
86-
| Not a mount/device boundary | `root()` keeps path traversal inside the directory tree; it does not make device files, bind mounts, or virtual filesystems safe to expose. |
87+
| Not a mount boundary | `root()` keeps path traversal inside the directory tree and blocks known unsafe read device paths, but it does not make bind mounts or virtual filesystems safe to expose wholesale. |
8788
| Per-call, not per-session | Another process with the same privileges can still mutate the tree between two separate calls. Use one verb method for the operation you need to make race-resistant. |
8889
| Hardlink rejection is best-effort | Link-count checks depend on platform metadata. Treat `hardlinks: "reject"` as a tripwire, not an authorization primitive. |
8990
| Mode bits are not a full policy engine | `replaceFileAtomic` and secret-file helpers set requested modes, but you should still set umask and inspect modes when policy requires it. |

‎docs/types.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,8 @@ The two policy unions you'll see throughout. `"reject"` is conservative; `"follo
148148

149149
```ts
150150
type FsSafeErrorCode =
151-
| "already-exists" | "denied-path" | "hardlink" | "helper-failed"
151+
| "already-exists" | "denied-path" | "device-path" | "hardlink"
152+
| "helper-failed"
152153
| "helper-unavailable" | "insecure-permissions" | "invalid-path"
153154
| "not-empty" | "not-file" | "not-found" | "not-owned"
154155
| "not-removable" | "outside-workspace" | "path-alias"

‎src/advanced.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@
22
// public subpaths; prefer root/json/store/temp/archive unless you are building a
33
// higher-level primitive.
44
export { createAsyncLock } from "./async-lock.js";
5+
export {
6+
assertNoUnsafeDeviceReadPath,
7+
isUnsafeDeviceReadPath,
8+
matchUnsafeDeviceReadPath,
9+
type UnsafeDeviceReadPathMatch,
10+
type UnsafeDeviceReadPathOptions,
11+
type UnsafeDeviceReadPathReason,
12+
} from "./device-path.js";
513
export {
614
assertAbsolutePathInput,
715
canonicalPathFromExistingAncestor,

‎src/device-path.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import path from "node:path";
2+
import { FsSafeError } from "./errors.js";
3+
import { trySafeFileURLToPath } from "./local-file-access.js";
4+
5+
export type UnsafeDeviceReadPathReason =
6+
| "posix-device"
7+
| "posix-fd"
8+
| "windows-device";
9+
10+
export type UnsafeDeviceReadPathMatch = {
11+
path: string;
12+
reason: UnsafeDeviceReadPathReason;
13+
};
14+
15+
export type UnsafeDeviceReadPathOptions = {
16+
cwd?: string;
17+
platform?: NodeJS.Platform;
18+
};
19+
20+
const POSIX_BLOCKED_DEVICE_PATHS = new Set([
21+
"/dev/zero",
22+
"/dev/random",
23+
"/dev/urandom",
24+
"/dev/full",
25+
"/dev/stdin",
26+
"/dev/stdout",
27+
"/dev/stderr",
28+
"/dev/tty",
29+
"/dev/console",
30+
]);
31+
32+
const WINDOWS_RESERVED_DEVICE_NAMES = new Set([
33+
"CON",
34+
"PRN",
35+
"AUX",
36+
"NUL",
37+
"CLOCK$",
38+
"CONIN$",
39+
"CONOUT$",
40+
"COM1",
41+
"COM2",
42+
"COM3",
43+
"COM4",
44+
"COM5",
45+
"COM6",
46+
"COM7",
47+
"COM8",
48+
"COM9",
49+
"LPT1",
50+
"LPT2",
51+
"LPT3",
52+
"LPT4",
53+
"LPT5",
54+
"LPT6",
55+
"LPT7",
56+
"LPT8",
57+
"LPT9",
58+
]);
59+
60+
function candidateReadPaths(filePath: string): string[] {
61+
if (!filePath.startsWith("file://")) {
62+
return [filePath];
63+
}
64+
const parsed = trySafeFileURLToPath(filePath);
65+
return parsed === undefined ? [filePath] : [filePath, parsed];
66+
}
67+
68+
function normalizePosixPath(filePath: string, cwd?: string): string {
69+
if (path.posix.isAbsolute(filePath)) {
70+
return path.posix.normalize(filePath);
71+
}
72+
const base = cwd && path.posix.isAbsolute(cwd) ? cwd : process.cwd();
73+
return path.posix.resolve(base, filePath);
74+
}
75+
76+
function matchPosixDeviceReadPath(
77+
filePath: string,
78+
cwd?: string,
79+
): UnsafeDeviceReadPathMatch | undefined {
80+
const normalized = normalizePosixPath(filePath, cwd);
81+
if (POSIX_BLOCKED_DEVICE_PATHS.has(normalized)) {
82+
return { path: normalized, reason: "posix-device" };
83+
}
84+
if (normalized === "/dev/fd" || normalized.startsWith("/dev/fd/")) {
85+
return { path: normalized, reason: "posix-fd" };
86+
}
87+
if (/^\/proc\/(?:self|thread-self|\d+)\/fd(?:\/|$)/.test(normalized)) {
88+
return { path: normalized, reason: "posix-fd" };
89+
}
90+
return undefined;
91+
}
92+
93+
function normalizeWindowsDeviceBaseName(filePath: string): string {
94+
const normalized = filePath.replace(/\//g, "\\").replace(/[\\]+$/g, "");
95+
const lastSegment = normalized.split("\\").filter(Boolean).at(-1) ?? normalized;
96+
const withoutStream = lastSegment.split(":")[0] ?? lastSegment;
97+
const withoutTrailingIgnoredChars = withoutStream.replace(/[ .]+$/g, "");
98+
return (withoutTrailingIgnoredChars.split(".")[0] ?? withoutTrailingIgnoredChars).toUpperCase();
99+
}
100+
101+
function matchWindowsDeviceReadPath(filePath: string): UnsafeDeviceReadPathMatch | undefined {
102+
const normalized = filePath.replace(/\//g, "\\");
103+
if (/^\\\\\.\\/.test(normalized) || /^\\\\\?\\GLOBALROOT\\Device\\/i.test(normalized)) {
104+
return { path: normalized, reason: "windows-device" };
105+
}
106+
const baseName = normalizeWindowsDeviceBaseName(filePath);
107+
if (WINDOWS_RESERVED_DEVICE_NAMES.has(baseName)) {
108+
return { path: normalized, reason: "windows-device" };
109+
}
110+
return undefined;
111+
}
112+
113+
export function matchUnsafeDeviceReadPath(
114+
filePath: string,
115+
options: UnsafeDeviceReadPathOptions = {},
116+
): UnsafeDeviceReadPathMatch | undefined {
117+
const platform = options.platform ?? process.platform;
118+
for (const candidate of candidateReadPaths(filePath)) {
119+
const match = platform === "win32"
120+
? matchWindowsDeviceReadPath(candidate)
121+
: matchPosixDeviceReadPath(candidate, options.cwd);
122+
if (match) {
123+
return match;
124+
}
125+
}
126+
return undefined;
127+
}
128+
129+
export function isUnsafeDeviceReadPath(
130+
filePath: string,
131+
options?: UnsafeDeviceReadPathOptions,
132+
): boolean {
133+
return matchUnsafeDeviceReadPath(filePath, options) !== undefined;
134+
}
135+
136+
export function assertNoUnsafeDeviceReadPath(
137+
filePath: string,
138+
options?: UnsafeDeviceReadPathOptions,
139+
): void {
140+
if (matchUnsafeDeviceReadPath(filePath, options)) {
141+
throw new FsSafeError(
142+
"device-path",
143+
`file reads from unsafe device paths are not allowed: ${filePath}`,
144+
);
145+
}
146+
}

0 commit comments

Comments
 (0)