Skip to content

Commit 396504b

Browse files
authored
fix: harden lock contention and permission verification (#101)
Stress testing the locking and permission surfaces found seven defects. Empty icacls output was accepted as verified ACL data, so an inspection that returned nothing parseable produced a permissive answer instead of failing closed. Sidecar inspection could follow a pathname swapped to a symlink, and both the async and sync sidecar reads were unbounded. Foreign synchronous .reclaim guards could be deleted after mkdir reported EEXIST. An old mtime overrode a valid future createdAt, falsely marking live locks stale. Sync acquisition spun forever on dangling-symlink sidecars, ignoring timeoutMs: 0. Every lock-manager domain permanently added another exit listener. Mutual exclusion itself held: forty in-process contenders and eight real child processes never overlapped. Reentrant-owner isolation, double release, throw cleanup, the eight-retry Windows boundary, durability semantics, and descriptor and process-handle accounting all verified clean. PID reuse remains application-owned through shouldReclaim, and corrupt or truncated lock files remain fail-closed.
1 parent 91e000f commit 396504b

15 files changed

Lines changed: 573 additions & 81 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 non-file sidecars without spinning, and read contended async and synchronous sidecar locks through bounded, no-follow, identity-checked descriptors; keep valid `createdAt` timestamps authoritative under filesystem clock skew; fail closed when fallback Windows ACL inspection returns no verifiable access entries; preserve synchronous stale-reclaim guards owned by another acquirer; and share one process-exit cleanup listener across file-lock manager domains.
8+
79
- Route `Root.copyIn()` and overwrite-capable `Root.write()` commits through a new descriptor-relative native replace rename, closing a parent-symlink swap that could create a missing destination directory outside the root before the JavaScript fallback detected the escape. Native `auto` and `require` mode now protect both create-only and replacing pinned writes; the explicitly best-effort JavaScript fallback remains available in `off` mode or when `auto` cannot load a binding.
810

911
- 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.

‎docs/sidecar-lock.md‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,12 @@ type FileLockRetryOptions = {
9696
result is passed to `shouldReclaim` and `shouldRemoveStaleLock`, allowing PID,
9797
process-start, argv, or role schemas to remain application-owned.
9898

99+
On Windows, a pathed `EPERM` from creating or opening the lock file can be a
100+
short teardown race after another holder unlinks it. The async lock retries that
101+
specific denial at most eight times. A parent-directory denial, a denial from a
102+
callback, or a ninth consecutive lock-file denial surfaces as the original
103+
`EPERM`; it is not converted to `file_lock_timeout`.
104+
99105
## Owner-scoped reentrancy
100106

101107
Version 0.5 removes the unsound process-scoped `allowReentrant` boolean and
@@ -167,10 +173,10 @@ progress.
167173
## Synchronous locks
168174

169175
`acquireFileLockSync()` and `withFileLockSync()` mirror filesystem arbitration,
170-
retry, payload parsing, stale policy, guarded identity-conditioned reclaim,
171-
verification, and compromise monitoring. They do not use the async manager
172-
queue, support async callbacks, or provide same-process reentrancy. Retry waits
173-
block the calling thread; use the async API in request-serving code.
176+
retry, payload parsing, stale policy, owner-scoped reentrancy, guarded
177+
identity-conditioned reclaim, verification, and compromise monitoring. They do
178+
not use the async manager queue or support async callbacks. Retry waits block
179+
the calling thread; use the async API in request-serving code.
174180

175181
Always release in a `finally`:
176182

@@ -236,7 +242,11 @@ await locks.drain();
236242

237243
## Stale policy: `shouldReclaim`
238244

239-
The default policy treats locks whose `createdAt` is older than `staleMs` as stale. Pass a custom callback when you want a richer notion of "is the holder still alive":
245+
The default policy treats locks whose valid `createdAt` is older than `staleMs`
246+
as stale. A valid current or future timestamp remains authoritative under
247+
filesystem clock skew; only absent or malformed timestamps fall back to the
248+
sidecar `mtime`. Pass a custom callback when you want a richer notion of "is the
249+
holder still alive":
240250

241251
```ts
242252
import { kill } from "node:process";

‎docs/test-hooks.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ type FsSafeTestHooks = {
3737
beforeRootFallbackMutation?: (operation: "mkdir" | "move" | "remove", targetPath: string) => Promise<void> | void;
3838
afterPinnedWriteFallbackRename?: (targetPath: string) => Promise<void> | void;
3939
beforeSiblingTempWrite?: (tempPath: string) => Promise<void> | void;
40+
beforeSidecarLockSnapshotOpen?: (lockPath: string) => Promise<void> | void;
4041
beforeTrashMove?: (targetPath: string, destPath: string) => void;
4142
afterPublishTargetCreated?: (method, targetPath, identity) => Promise<void> | void;
4243
beforePublishDirectorySync?: (method, targetPath, identity) => Promise<void> | void;
@@ -54,6 +55,7 @@ type FsSafeTestHooks = {
5455
| `beforeRootFallbackMutation` | A guarded JS root fallback is about to mkdir, move, or remove. |
5556
| `afterPinnedWriteFallbackRename` | A fallback rename committed and post-commit identity checks have not run yet. |
5657
| `beforeSiblingTempWrite` | A sibling temp file exists and its writer is about to run. |
58+
| `beforeSidecarLockSnapshotOpen` | A sidecar lock was inspected and is about to be opened for a bounded snapshot read. |
5759
| `beforeTrashMove` | Trash handling is about to move the target. |
5860
| `afterPublishTargetCreated` | Exclusive publication created its target and final fences have not run yet. |
5961
| `beforePublishDirectorySync` | Publication verified the target and is about to sync its parent directory. |

‎src/file-lock-sync.ts‎

Lines changed: 51 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
} from "./sidecar-lock-reclaim.js";
1414
import {
1515
computeSidecarLockDelayMs,
16-
sidecarLockPayloadIsStale,
16+
sidecarLockPayloadCreatedAtMs,
1717
} from "./sidecar-lock-policy.js";
1818
import type {
1919
SidecarLockCompromisedInfo,
@@ -135,7 +135,8 @@ function boundedLockPath(lockPath: string, lockRoot?: Root): string {
135135
}
136136

137137
function defaultShouldReclaim(payload: unknown, lockPath: string, staleMs: number, nowMs: number): boolean {
138-
if (sidecarLockPayloadIsStale(payload, staleMs, nowMs)) return true;
138+
const createdAtMs = sidecarLockPayloadCreatedAtMs(payload);
139+
if (createdAtMs !== null) return nowMs - createdAtMs > staleMs;
139140
try {
140141
return nowMs - fs.statSync(lockPath).mtimeMs > staleMs;
141142
} catch {
@@ -147,6 +148,16 @@ function sleep(milliseconds: number): void {
147148
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
148149
}
149150

151+
function reclaimGuardExists(reclaimGuardPath: string): boolean {
152+
try {
153+
fs.lstatSync(reclaimGuardPath);
154+
return true;
155+
} catch (error) {
156+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
157+
throw error;
158+
}
159+
}
160+
150161
export function acquireFileLockSync<TPayload extends Record<string, unknown>>(
151162
targetPath: string,
152163
options: FileLockSyncAcquireOptions<TPayload>,
@@ -168,8 +179,26 @@ export function acquireFileLockSync<TPayload extends Record<string, unknown>>(
168179
const retry = options.retry ?? {};
169180
const startedAt = Date.now();
170181
let attempt = 0;
182+
const reclaimGuardPath = `${lockPath}.reclaim`;
183+
const waitForRetry = (): void => {
184+
const elapsed = Date.now() - startedAt;
185+
const timedOut = options.timeoutMs !== undefined && elapsed >= options.timeoutMs;
186+
if (timedOut || (retry.retries !== undefined && attempt >= retry.retries)) {
187+
throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), {
188+
code: "file_lock_timeout",
189+
lockPath,
190+
normalizedTargetPath,
191+
});
192+
}
193+
sleep(computeSidecarLockDelayMs(retry, attempt));
194+
attempt += 1;
195+
};
171196

172197
while (true) {
198+
if (reclaimGuardExists(reclaimGuardPath)) {
199+
waitForRetry();
200+
continue;
201+
}
173202
let fd: number | undefined;
174203
try {
175204
const payload = options.payload();
@@ -223,20 +252,12 @@ export function acquireFileLockSync<TPayload extends Record<string, unknown>>(
223252
}
224253
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
225254
if (heldLocks.has(normalizedTargetPath)) {
226-
const elapsed = Date.now() - startedAt;
227-
const timedOut = options.timeoutMs !== undefined && elapsed >= options.timeoutMs;
228-
if (timedOut || (retry.retries !== undefined && attempt >= retry.retries)) {
229-
throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), {
230-
code: "file_lock_timeout",
231-
lockPath,
232-
normalizedTargetPath,
233-
});
234-
}
235-
sleep(computeSidecarLockDelayMs(retry, attempt));
236-
attempt += 1;
255+
waitForRetry();
237256
continue;
238257
}
239-
const snapshot = readSidecarLockSnapshotSync(lockPath, options.parsePayload);
258+
const snapshot = readSidecarLockSnapshotSync(lockPath, options.parsePayload, {
259+
rejectNonFile: true,
260+
});
240261
if (!snapshot) continue;
241262
const nowMs = Date.now();
242263
const reclaim = options.shouldReclaim
@@ -260,15 +281,24 @@ export function acquireFileLockSync<TPayload extends Record<string, unknown>>(
260281
payload: snapshot.payload,
261282
})
262283
) {
263-
const reclaimGuard = `${lockPath}.reclaim`;
284+
let ownsReclaimGuard = false;
264285
try {
265-
fs.mkdirSync(reclaimGuard);
286+
fs.mkdirSync(reclaimGuardPath);
287+
ownsReclaimGuard = true;
266288
if (removeSidecarLockIfUnchangedSync(lockPath, snapshot)) continue;
289+
} catch (reclaimError) {
290+
if ((reclaimError as NodeJS.ErrnoException).code !== "EEXIST") {
291+
throw reclaimError;
292+
}
293+
waitForRetry();
294+
continue;
267295
} finally {
268-
try {
269-
fs.rmdirSync(reclaimGuard);
270-
} catch {
271-
// A surviving reclaim guard fails closed.
296+
if (ownsReclaimGuard) {
297+
try {
298+
fs.rmdirSync(reclaimGuardPath);
299+
} catch {
300+
// A surviving reclaim guard fails closed.
301+
}
272302
}
273303
}
274304
}
@@ -278,17 +308,7 @@ export function acquireFileLockSync<TPayload extends Record<string, unknown>>(
278308
normalizedTargetPath,
279309
});
280310
}
281-
const elapsed = Date.now() - startedAt;
282-
const timedOut = options.timeoutMs !== undefined && elapsed >= options.timeoutMs;
283-
if (timedOut || (retry.retries !== undefined && attempt >= retry.retries)) {
284-
throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), {
285-
code: "file_lock_timeout",
286-
lockPath,
287-
normalizedTargetPath,
288-
});
289-
}
290-
sleep(computeSidecarLockDelayMs(retry, attempt));
291-
attempt += 1;
311+
waitForRetry();
292312
}
293313
}
294314
}

‎src/permissions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,7 @@ export async function inspectWindowsAcl(
471471
targetPath,
472472
]);
473473
let entries = parseIcaclsOutput(`${stdout}\n${stderr}`.trim(), targetPath);
474+
if (!entries.length) throw new Error("Windows ACL output could not be verified");
474475
const unresolvedPrincipals = entries
475476
.filter((entry) => !entry.sid)
476477
.map((entry) => entry.principal);

‎src/sidecar-lock-acquire.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ export async function acquireSidecarLock<TPayload extends Record<string, unknown
236236
snapshot = await readSidecarLockSnapshot(lockPath, {
237237
lockRoot: options.lockRoot,
238238
parsePayload: options.parsePayload,
239+
rejectNonFile: true,
239240
});
240241
} catch (readErr) {
241242
if (!isTransientLockFileDenial(readErr, lockPath) || !withinDenialBudget()) throw readErr;

‎src/sidecar-lock-policy.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ export function sidecarLockPayloadIsStale(
2929
staleMs: number,
3030
nowMs: number,
3131
): boolean {
32+
const createdAtMs = sidecarLockPayloadCreatedAtMs(payload);
33+
return createdAtMs !== null && nowMs - createdAtMs > staleMs;
34+
}
35+
36+
export function sidecarLockPayloadCreatedAtMs(payload: unknown): number | null {
3237
const createdAt =
3338
payload &&
3439
typeof payload === "object" &&
@@ -37,7 +42,7 @@ export function sidecarLockPayloadIsStale(
3742
? payload.createdAt
3843
: "";
3944
const createdAtMs = Date.parse(createdAt);
40-
return Number.isFinite(createdAtMs) && nowMs - createdAtMs > staleMs;
45+
return Number.isFinite(createdAtMs) ? createdAtMs : null;
4146
}
4247

4348
export async function defaultSidecarLockShouldReclaim(params: {
@@ -46,7 +51,8 @@ export async function defaultSidecarLockShouldReclaim(params: {
4651
staleMs: number;
4752
nowMs: number;
4853
}): Promise<boolean> {
49-
if (sidecarLockPayloadIsStale(params.payload, params.staleMs, params.nowMs)) return true;
54+
const createdAtMs = sidecarLockPayloadCreatedAtMs(params.payload);
55+
if (createdAtMs !== null) return params.nowMs - createdAtMs > params.staleMs;
5056
try {
5157
return params.nowMs - (await fs.stat(params.lockPath)).mtimeMs > params.staleMs;
5258
} catch {

‎src/sidecar-lock-reclaim.ts‎

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@ import { randomBytes } from "node:crypto";
22
import fsSync, { type Stats } from "node:fs";
33
import fs from "node:fs/promises";
44
import path from "node:path";
5-
import { readFileHandleBounded } from "./bounded-read.js";
5+
import { readFileDescriptorBoundedSync, readFileHandleBounded } from "./bounded-read.js";
66
import { FsSafeError } from "./errors.js";
77
import { sameFileIdentity } from "./file-identity.js";
88
import type { Root } from "./root-impl.js";
9+
import { getFsSafeTestHooks } from "./test-hooks.js";
910

1011
const MAX_LOCK_PAYLOAD_BYTES = 1024 * 1024;
1112

@@ -87,8 +88,14 @@ export function parseSidecarLockPayload(
8788

8889
export async function readSidecarLockSnapshot(
8990
lockPath: string,
90-
options: { lockRoot?: Root; parsePayload?: (raw: string) => unknown } = {},
91+
options: {
92+
lockRoot?: Root;
93+
parsePayload?: (raw: string) => unknown;
94+
rejectNonFile?: boolean;
95+
allowDescriptorIdentityDrift?: boolean;
96+
} = {},
9197
): Promise<SidecarLockSnapshot | null> {
98+
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
9299
try {
93100
if (options.lockRoot) {
94101
const opened = await options.lockRoot.open(relativeSidecarLockPath(options.lockRoot, lockPath));
@@ -103,9 +110,45 @@ export async function readSidecarLockSnapshot(
103110
await opened.handle.close().catch(() => undefined);
104111
}
105112
}
106-
const stat = await fs.lstat(lockPath);
107-
const raw = await fs.readFile(lockPath, "utf8");
108-
return { raw, payload: parseSidecarLockPayload(raw, options.parsePayload), stat };
113+
const before = await fs.lstat(lockPath);
114+
if (!before.isFile() || before.isSymbolicLink()) {
115+
if (options.rejectNonFile) {
116+
throw new FsSafeError("not-file", `sidecar lock is not a regular file: ${lockPath}`);
117+
}
118+
return null;
119+
}
120+
await getFsSafeTestHooks()?.beforeSidecarLockSnapshotOpen?.(lockPath);
121+
const noFollow =
122+
process.platform !== "win32" && typeof fsSync.constants.O_NOFOLLOW === "number"
123+
? fsSync.constants.O_NOFOLLOW
124+
: 0;
125+
try {
126+
handle = await fs.open(
127+
lockPath,
128+
fsSync.constants.O_RDONLY |
129+
noFollow |
130+
(typeof fsSync.constants.O_NONBLOCK === "number" ? fsSync.constants.O_NONBLOCK : 0),
131+
);
132+
} catch (error) {
133+
if (options.rejectNonFile && (error as NodeJS.ErrnoException).code === "ELOOP") {
134+
throw new FsSafeError("not-file", `sidecar lock is not a regular file: ${lockPath}`, {
135+
cause: error,
136+
});
137+
}
138+
throw error;
139+
}
140+
const opened = await handle.stat();
141+
if (!opened.isFile()) {
142+
if (options.rejectNonFile) {
143+
throw new FsSafeError("not-file", `sidecar lock is not a regular file: ${lockPath}`);
144+
}
145+
return null;
146+
}
147+
if (!options.allowDescriptorIdentityDrift && !sameFileIdentity(before, opened)) return null;
148+
const raw = (await readFileHandleBounded(handle, MAX_LOCK_PAYLOAD_BYTES)).toString("utf8");
149+
const after = await fs.lstat(lockPath);
150+
if (!after.isFile() || !sameFileIdentity(before, after)) return null;
151+
return { raw, payload: parseSidecarLockPayload(raw, options.parsePayload), stat: after };
109152
} catch (err) {
110153
if (
111154
(err as NodeJS.ErrnoException).code === "ENOENT" ||
@@ -114,24 +157,32 @@ export async function readSidecarLockSnapshot(
114157
return null;
115158
}
116159
throw err;
160+
} finally {
161+
await handle?.close().catch(() => undefined);
117162
}
118163
}
119164

120165
export function readSidecarLockSnapshotSync(
121166
lockPath: string,
122167
parsePayload?: (raw: string) => unknown,
168+
options: { rejectNonFile?: boolean } = {},
123169
): SidecarLockSnapshot | null {
124170
let fd: number | undefined;
125171
try {
126172
const before = fsSync.lstatSync(lockPath);
127-
if (!before.isFile() || before.isSymbolicLink()) return null;
173+
if (!before.isFile() || before.isSymbolicLink()) {
174+
if (options.rejectNonFile) {
175+
throw new FsSafeError("not-file", `sidecar lock is not a regular file: ${lockPath}`);
176+
}
177+
return null;
178+
}
128179
const noFollow =
129180
process.platform !== "win32" && typeof fsSync.constants.O_NOFOLLOW === "number"
130181
? fsSync.constants.O_NOFOLLOW
131182
: 0;
132183
fd = fsSync.openSync(lockPath, fsSync.constants.O_RDONLY | noFollow);
133184
const opened = fsSync.fstatSync(fd);
134-
const raw = fsSync.readFileSync(fd, "utf8");
185+
const raw = readFileDescriptorBoundedSync(fd, MAX_LOCK_PAYLOAD_BYTES).toString("utf8");
135186
const after = fsSync.lstatSync(lockPath);
136187
if (!sameFileIdentity(before, opened) || !sameFileIdentity(opened, after)) return null;
137188
return {
@@ -186,7 +237,10 @@ export async function removeSidecarLockIfUnchanged(
186237
observed: SidecarLockSnapshot | null,
187238
options: { lockRoot?: Root; parsePayload?: (raw: string) => unknown } = {},
188239
): Promise<boolean> {
189-
const current = await readSidecarLockSnapshot(lockPath, options);
240+
const current = await readSidecarLockSnapshot(lockPath, {
241+
...options,
242+
allowDescriptorIdentityDrift: observed?.ownershipToken !== undefined,
243+
});
190244
if (!current || !observed || !sidecarLockSnapshotMatches(current, observed)) {
191245
return false;
192246
}
@@ -203,7 +257,10 @@ export async function sidecarLockSnapshotStillPresent(
203257
observed: SidecarLockSnapshot | null,
204258
options: { lockRoot?: Root; parsePayload?: (raw: string) => unknown } = {},
205259
): Promise<boolean> {
206-
const current = await readSidecarLockSnapshot(lockPath, options);
260+
const current = await readSidecarLockSnapshot(lockPath, {
261+
...options,
262+
allowDescriptorIdentityDrift: observed?.ownershipToken !== undefined,
263+
});
207264
return !!current && !!observed && sidecarLockSnapshotMatches(current, observed);
208265
}
209266

0 commit comments

Comments
 (0)