Skip to content

Commit 64f7742

Browse files
steipeteYigtwxx
andauthored
fix(permissions): bound Windows ACL commands (#89)
defaultPermissionExec spawned icacls.exe and powershell.exe with no timeout, so a wedged helper hung inspectPathPermissions() indefinitely for any consumer, not just in tests. Built-in Windows permission commands are now bounded to 10s with hard termination. The bound fails closed: an owner query that cannot complete yields source "unknown", the ACL query is skipped, and readSecureFile() refuses the read with permission-unverified rather than returning a permissive answer. Also removes a redundant permission inspection in the tests, dropping the affected Windows tests from six spawns to four. Ordinary Windows CI keeps exercising the real command fallback; native coverage stays in the native job. Supersedes #88. Diagnosis by @Yigtwxx. Co-authored-by: Yigtwxx <[email protected]>
1 parent da387a7 commit 64f7742

7 files changed

Lines changed: 175 additions & 45 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,9 @@ jobs:
5656
- name: Install dependencies
5757
run: pnpm install --frozen-lockfile
5858

59-
- name: Check
59+
# Deliberately do not build a host binding here. On Windows this exercises
60+
# the shipping command fallback; native-check covers the bundled binding.
61+
- name: Check JavaScript fallback
6062
run: pnpm check
6163

6264
native-check:

‎CHANGELOG.md‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,18 @@
55
### Security and Correctness
66

77
- 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.
8-
- Report access-denied failures from native Windows operations as `EPERM` rather than `EACCES`, matching Node/libuv and the JavaScript fallback. Consumers that matched the previous native-only `EACCES` code should accept `EPERM` as well when supporting older package versions.
9-
10-
### Features
11-
12-
- Suffix Windows reserved basenames with `_` in `sanitizeUntrustedFileName()` while preserving case and extensions on every platform, including dollar names and superscript COM/LPT variants; thanks @SebTardif (#67).
13-
14-
### Security and Correctness
15-
168
- 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).
9+
- Bound fallback Windows owner and ACL command execution to 10 seconds per process and report owner-query failures as unverified instead of returning a partial permission classification; thanks @Yigtwxx for the diagnosis.
1710

1811
### Compatibility
1912

13+
- Report access-denied failures from native Windows operations as `EPERM` rather than `EACCES`, matching Node/libuv and the JavaScript fallback. Consumers that matched the previous native-only `EACCES` code should accept `EPERM` as well when supporting older package versions.
2014
- Add an optional `fchmodSync` operation to the injectable synchronous atomic-replacement filesystem type. Async adapters need no new member because their required `open()` returns a mode-capable `FileHandle`; custom sync adapters that pass `mode` or `preserveExistingMode` now fail before mutation when `fchmodSync` is absent, while adapters that request neither option remain compatible.
2115

16+
### Features
17+
18+
- Suffix Windows reserved basenames with `_` in `sanitizeUntrustedFileName()` while preserving case and extensions on every platform, including dollar names and superscript COM/LPT variants; thanks @SebTardif (#67).
19+
2220
## 0.5.1 - 2026-08-01
2321

2422
### Security and Correctness

‎docs/permissions.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ resolveWindowsUserPrincipal(env);
6767
The fallback Windows inspector calls `icacls.exe <path>` using its supported
6868
path-only inspection syntax and classifies principals as trusted, world, or
6969
group. Trusted defaults include the current user, SYSTEM, and Administrators.
70+
Built-in PowerShell, `icacls.exe`, and `whoami.exe` invocations have a fixed
71+
10-second per-process deadline. A command failure or timeout returns an
72+
unverified result (`source: "unknown"`) so callers fail closed. Advanced callers
73+
that inject a custom `exec` implementation own that executor's deadline.
7074
The parser is on the advanced surface so tests and CLIs can process captured
7175
`icacls` output without spawning a process.
7276

‎src/permission-exec.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { execFile } from "node:child_process";
2+
import { promisify } from "node:util";
3+
4+
const execFileAsync = promisify(execFile);
5+
6+
export const DEFAULT_PERMISSION_EXEC_TIMEOUT_MS = 10_000;
7+
8+
export async function executePermissionCommand(
9+
command: string,
10+
args: string[],
11+
timeoutMs = DEFAULT_PERMISSION_EXEC_TIMEOUT_MS,
12+
): Promise<{ stdout: string; stderr: string }> {
13+
try {
14+
return (await execFileAsync(command, args, {
15+
encoding: "utf8",
16+
windowsHide: true,
17+
maxBuffer: 1024 * 1024,
18+
timeout: timeoutMs,
19+
killSignal: "SIGKILL",
20+
})) as { stdout: string; stderr: string };
21+
} catch (err) {
22+
if (
23+
err &&
24+
typeof err === "object" &&
25+
"killed" in err &&
26+
err.killed === true &&
27+
"signal" in err &&
28+
err.signal === "SIGKILL"
29+
) {
30+
throw new Error(`Windows permission inspection timed out after ${timeoutMs}ms`, {
31+
cause: err,
32+
});
33+
}
34+
throw err;
35+
}
36+
}

‎src/permissions.ts‎

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import { execFile } from "node:child_process";
21
import fs from "node:fs/promises";
32
import os from "node:os";
43
import path from "node:path";
5-
import { promisify } from "node:util";
4+
import { executePermissionCommand } from "./permission-exec.js";
65
import { normalizeLowercaseStringOrEmpty } from "./string-coerce.js";
76
import { inspectWindowsPermissionsNative } from "./windows-permissions-native.js";
87
import { resolveWindowsSystemCommand } from "./windows-command.js";
@@ -11,7 +10,6 @@ import {
1110
resolveWindowsCurrentUserSid,
1211
resolveWindowsPrincipalSids,
1312
} from "./windows-owner.js";
14-
const execFileAsync = promisify(execFile);
1513
export type PermissionExec = (
1614
command: string,
1715
args: string[],
@@ -116,13 +114,7 @@ const TRUSTED_BASE_ASCII = new Set([...TRUSTED_BASE].map(stripDiacritics));
116114
const normalize = (value: string) => normalizeLowercaseStringOrEmpty(value);
117115
const defaultWindowsUserInfo: WindowsUserInfoProvider = () => os.userInfo();
118116

119-
function defaultPermissionExec(command: string, args: string[]) {
120-
return execFileAsync(command, args, {
121-
encoding: "utf8",
122-
windowsHide: true,
123-
maxBuffer: 1024 * 1024,
124-
}) as Promise<{ stdout: string; stderr: string }>;
125-
}
117+
const defaultPermissionExec: PermissionExec = executePermissionCommand;
126118

127119
export async function safeStat(targetPath: string): Promise<SafeStatResult> {
128120
try {
@@ -188,11 +180,27 @@ export async function inspectPathPermissions(
188180
targetPath, stat: st, effectiveIsDir, effectiveMode, bits,
189181
});
190182
if (native) return native;
183+
const unverified: PermissionCheck = {
184+
ok: true,
185+
isSymlink: st.isSymlink,
186+
isDir: effectiveIsDir,
187+
mode: effectiveMode,
188+
bits,
189+
source: "unknown",
190+
worldWritable: false,
191+
groupWritable: false,
192+
worldReadable: false,
193+
groupReadable: false,
194+
};
191195
const owner = await inspectWindowsOwner({
192196
targetPath,
193197
env: opts?.env,
194198
exec: opts?.exec ?? defaultPermissionExec,
195199
});
200+
if (owner.error) {
201+
const error = `Windows owner inspection failed: ${owner.error}`;
202+
return { ...unverified, ownerError: owner.error, error };
203+
}
196204
const acl = await inspectWindowsAcl(targetPath, {
197205
env: opts?.env,
198206
exec: opts?.exec,
@@ -207,16 +215,7 @@ export async function inspectPathPermissions(
207215
};
208216
if (!acl.ok) {
209217
return {
210-
ok: true,
211-
isSymlink: st.isSymlink,
212-
isDir: effectiveIsDir,
213-
mode: effectiveMode,
214-
bits,
215-
source: "unknown",
216-
worldWritable: false,
217-
groupWritable: false,
218-
worldReadable: false,
219-
groupReadable: false,
218+
...unverified,
220219
...ownerFields,
221220
error: acl.error,
222221
};

‎test/new-primitives.test.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -221,12 +221,6 @@ describe("secure file reads", () => {
221221
await fs.writeFile(filePath, '{"token":"ok"}', { mode: 0o600 });
222222
await secureWindowsTestFile(filePath);
223223

224-
const permissions = await inspectPathPermissions(filePath);
225-
expect(permissions, permissions.ownerError ?? JSON.stringify(permissions)).toMatchObject({
226-
source: "windows-acl",
227-
ownerTrusted: true,
228-
});
229-
230224
const result = await readSecureFile({
231225
filePath,
232226
label: "test secret",
@@ -250,12 +244,6 @@ describe("secure file reads", () => {
250244
await secureWindowsTestFile(filePath);
251245
const extendedPath = `\\\\?\\${path.resolve(filePath)}`;
252246

253-
const permissions = await inspectPathPermissions(extendedPath);
254-
expect(permissions, permissions.ownerError ?? JSON.stringify(permissions)).toMatchObject({
255-
source: "windows-acl",
256-
ownerTrusted: true,
257-
});
258-
259247
const result = await readSecureFile({
260248
filePath: extendedPath,
261249
label: "extended-path secret",
@@ -559,9 +547,20 @@ describe("secure file reads", () => {
559547
it("reports broad Windows SID writes as world-writable", async () => {
560548
const target = path.join(root, "windows-acl-token.txt");
561549
await fs.writeFile(target, "secret", { mode: 0o600 });
562-
const exec = vi.fn().mockResolvedValue({
563-
stdout: `${target} *S-1-5-18:(F)\n *S-1-5-7:(F)\n`,
564-
stderr: "",
550+
const exec = vi.fn(async (command: string) => {
551+
if (command.toLowerCase().endsWith("powershell.exe")) {
552+
return {
553+
stdout: JSON.stringify({
554+
ownerSid: "S-1-5-7",
555+
currentUserSid: "S-1-5-7",
556+
}),
557+
stderr: "",
558+
};
559+
}
560+
return {
561+
stdout: `${target} *S-1-5-18:(F)\n *S-1-5-7:(F)\n`,
562+
stderr: "",
563+
};
565564
});
566565

567566
const result = await inspectPathPermissions(target, {
@@ -696,10 +695,12 @@ describe("secure file reads", () => {
696695
exec,
697696
});
698697

699-
expect(result.source).toBe("windows-acl");
698+
expect(result.source).toBe("unknown");
700699
expect(result.ownerSid).toBeUndefined();
701700
expect(result.ownerTrusted).toBeUndefined();
702701
expect(result.ownerError).toContain("owner lookup failed");
702+
expect(result.error).toContain("Windows owner inspection failed");
703+
expect(exec).toHaveBeenCalledTimes(1);
703704
});
704705

705706
it("fails Windows ACL verification closed when a principal SID cannot be translated", async () => {

‎test/permissions-exec.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
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 {
6+
DEFAULT_PERMISSION_EXEC_TIMEOUT_MS,
7+
executePermissionCommand,
8+
} from "../src/permission-exec.js";
9+
import { inspectPathPermissions } from "../src/permissions.js";
10+
import { readSecureFile } from "../src/secure-file.js";
11+
12+
const tempDirs: string[] = [];
13+
14+
afterEach(async () => {
15+
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));
16+
});
17+
18+
describe("Windows permission command execution", () => {
19+
it("terminates a wedged child process on a deterministic deadline", async () => {
20+
const timeoutMs = 100;
21+
const startedAt = performance.now();
22+
23+
await expect(
24+
executePermissionCommand(process.execPath, ["-e", "setInterval(() => {}, 1_000)"], timeoutMs),
25+
).rejects.toThrow(`Windows permission inspection timed out after ${timeoutMs}ms`);
26+
27+
expect(performance.now() - startedAt).toBeLessThan(3_000);
28+
expect(DEFAULT_PERMISSION_EXEC_TIMEOUT_MS).toBe(10_000);
29+
});
30+
31+
it("fails closed without starting an ACL query when owner inspection fails", async () => {
32+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "fs-safe-permission-timeout-"));
33+
tempDirs.push(dir);
34+
const target = path.join(dir, "secret.json");
35+
await fs.writeFile(target, "{}", { mode: 0o600 });
36+
const exec = vi.fn().mockRejectedValue(new Error("owner query timed out"));
37+
38+
const result = await inspectPathPermissions(target, {
39+
platform: "win32",
40+
env: { SystemRoot: "C:\\Windows" },
41+
exec,
42+
});
43+
44+
expect(result).toMatchObject({
45+
ok: true,
46+
source: "unknown",
47+
ownerError: "Error: owner query timed out",
48+
error: expect.stringContaining("Windows owner inspection failed"),
49+
});
50+
expect(exec).toHaveBeenCalledTimes(1);
51+
});
52+
53+
it("inspects permissions once for one secure read", async () => {
54+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "fs-safe-permission-count-"));
55+
tempDirs.push(dir);
56+
const target = path.join(dir, "secret.json");
57+
await fs.writeFile(target, "{}", { mode: 0o600 });
58+
const exec = vi.fn(async (command: string, args: string[]) => {
59+
if (command.toLowerCase().endsWith("powershell.exe")) {
60+
return {
61+
stdout: JSON.stringify({
62+
ownerSid: "S-1-5-21-42",
63+
currentUserSid: "S-1-5-21-42",
64+
principalSids: [{ name: "S-1-5-21-42", sid: "S-1-5-21-42" }],
65+
principalTranslationFailed: false,
66+
remote: false,
67+
}),
68+
stderr: "",
69+
};
70+
}
71+
return { stdout: `${args[0]} *S-1-5-21-42:(F)\n`, stderr: "" };
72+
});
73+
74+
const result = await readSecureFile({
75+
filePath: target,
76+
inject: {
77+
platform: "win32",
78+
env: { SystemRoot: "C:\\Windows" },
79+
exec,
80+
},
81+
});
82+
83+
expect(result.permissions).toMatchObject({ source: "windows-acl", ownerTrusted: true });
84+
expect(exec).toHaveBeenCalledTimes(2);
85+
expect(exec.mock.calls.map(([command]) => path.win32.basename(command))).toEqual([
86+
"powershell.exe",
87+
"icacls.exe",
88+
]);
89+
});
90+
});

0 commit comments

Comments
 (0)