Skip to content

Commit 4600240

Browse files
steipeteYigtwxx
andcommitted
fix(lock): cover native Windows teardown denials
Co-authored-by: Yigtwxx <[email protected]>
1 parent 4603817 commit 4600240

9 files changed

Lines changed: 601 additions & 447 deletions

‎CHANGELOG.md‎

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

55
### Security and Correctness
66

7-
- Retry a contended file-lock acquisition when Windows denies access to a lock file whose directory entry is still being torn down. 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.
7+
- 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.
88

99
### Features
1010

‎native/src/windows.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,10 @@ fn win_error(code: u32, operation: &str) -> napi::Error<String> {
226226
let typed = match code {
227227
ERROR_FILE_EXISTS | ERROR_ALREADY_EXISTS => "EEXIST",
228228
ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => "ENOENT",
229-
ERROR_ACCESS_DENIED => "EACCES",
229+
// Node/libuv reports Windows ERROR_ACCESS_DENIED from filesystem opens
230+
// as EPERM. Keep the native path aligned so callers can apply the same
231+
// operation-specific policy after adding their own path provenance.
232+
ERROR_ACCESS_DENIED => "EPERM",
230233
_ => "EIO",
231234
};
232235
native_error(
@@ -654,6 +657,11 @@ mod tests {
654657

655658
use super::*;
656659

660+
#[test]
661+
fn maps_access_denied_to_node_filesystem_eperm() {
662+
assert_eq!(win_error(ERROR_ACCESS_DENIED, "test").status, "EPERM");
663+
}
664+
657665
#[test]
658666
fn rejects_reparse_points_and_preserves_existing_rename_target() {
659667
let nonce = SystemTime::now()

‎scripts/check-file-size.mjs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@ const LINE_BUDGETS = new Map([
77
["src/permissions.ts", 566],
88
["src/root-impl.ts", 1750],
99
["src/root-path.ts", 862],
10-
["src/sidecar-lock.ts", 540],
1110
["test/api-coverage.test.ts", 983],
1211
["test/new-primitives.test.ts", 1500],
13-
["test/sidecar-lock-regression.test.ts", 540],
1412
]);
1513

1614
function walk(dir) {

‎src/native-operations.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -101,13 +101,25 @@ export async function createNativeExclusiveFile(
101101
let fd: number | undefined;
102102
let created: Stats | undefined;
103103
try {
104-
const opened = binding.openBeneath(
105-
parent.fd,
106-
basename,
107-
nativeOpenFlags(
108-
fsSync.constants.O_WRONLY | fsSync.constants.O_CREAT | fsSync.constants.O_EXCL,
109-
),
110-
);
104+
let opened: ReturnType<NativeBinding["openBeneath"]>;
105+
try {
106+
opened = binding.openBeneath(
107+
parent.fd,
108+
basename,
109+
nativeOpenFlags(
110+
fsSync.constants.O_WRONLY | fsSync.constants.O_CREAT | fsSync.constants.O_EXCL,
111+
),
112+
);
113+
} catch (error) {
114+
// The parent open above and every post-create operation remain untagged.
115+
// Only this exclusive-open failure has enough provenance for a caller to
116+
// classify a Windows lock-file denial without swallowing setup failures.
117+
const openError = error as NodeJS.ErrnoException;
118+
if (process.platform === "win32" && openError.code === "EPERM") {
119+
openError.path = targetPath;
120+
}
121+
throw error;
122+
}
111123
fd = opened.fd;
112124
fsSync.fchmodSync(fd, mode);
113125
created = fsSync.fstatSync(fd);

‎src/sidecar-lock-acquire.ts‎

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import { FsSafeError } from "./errors.js";
4+
import { createNativeExclusiveFile, type NativeFileHandle } from "./native-operations.js";
5+
import type { Root } from "./root-impl.js";
6+
import {
7+
computeSidecarLockDelayMs,
8+
defaultSidecarLockShouldReclaim,
9+
isTransientLockFileDenial,
10+
maxTransientLockDenials,
11+
} from "./sidecar-lock-policy.js";
12+
import {
13+
readSidecarLockSnapshot,
14+
relativeSidecarLockPath,
15+
releaseSidecarReclaimGuard,
16+
removeSidecarLockIfUnchanged,
17+
removeStaleSidecarLockIfAllowed,
18+
serializeSidecarLockPayload,
19+
sidecarLockSnapshotStillPresent,
20+
sidecarReclaimGuardExists,
21+
tryAcquireSidecarReclaimGuard,
22+
type SidecarLockSnapshot,
23+
} from "./sidecar-lock-reclaim.js";
24+
import type { SidecarLockAcquireOptions, SidecarLockHandle } from "./sidecar-lock-types.js";
25+
26+
type SidecarFileHandle = Pick<NativeFileHandle, "close" | "stat" | "writeFile">;
27+
28+
export type HeldSidecarLock = {
29+
refCount: number;
30+
reentrantOwner?: string;
31+
handle: SidecarFileHandle;
32+
lockPath: string;
33+
snapshot: SidecarLockSnapshot;
34+
acquiredAt: number;
35+
metadata: Record<string, unknown>;
36+
releasePromise?: Promise<void>;
37+
lockRoot?: Root;
38+
parsePayload?: (raw: string) => unknown;
39+
compromiseTimer?: NodeJS.Timeout;
40+
};
41+
42+
type SidecarLockAcquisitionContext = {
43+
held: Map<string, HeldSidecarLock>;
44+
reclaimGuards: Set<string>;
45+
ensureExitCleanupRegistered(): void;
46+
handleForHeldLock(normalizedTargetPath: string, held: HeldSidecarLock): SidecarLockHandle;
47+
releaseHeldLock(
48+
normalizedTargetPath: string,
49+
held: HeldSidecarLock,
50+
options?: { force?: boolean },
51+
): Promise<boolean>;
52+
};
53+
54+
async function resolveNormalizedTargetPath(targetPath: string): Promise<string> {
55+
const resolved = path.resolve(targetPath);
56+
const dir = path.dirname(resolved);
57+
await fs.mkdir(dir, { recursive: true });
58+
try {
59+
return path.join(await fs.realpath(dir), path.basename(resolved));
60+
} catch {
61+
return resolved;
62+
}
63+
}
64+
65+
export async function acquireSidecarLock<TPayload extends Record<string, unknown>>(
66+
options: SidecarLockAcquireOptions<TPayload>,
67+
context: SidecarLockAcquisitionContext,
68+
): Promise<SidecarLockHandle> {
69+
context.ensureExitCleanupRegistered();
70+
const normalizedTargetPath = await resolveNormalizedTargetPath(options.targetPath);
71+
const lockPath = options.lockPath ?? `${normalizedTargetPath}.lock`;
72+
const held = context.held.get(normalizedTargetPath);
73+
if (
74+
held &&
75+
options.reentrantOwner !== undefined &&
76+
held.reentrantOwner !== undefined &&
77+
options.reentrantOwner === held.reentrantOwner
78+
) {
79+
held.refCount += 1;
80+
return context.handleForHeldLock(normalizedTargetPath, held);
81+
}
82+
83+
const startedAt = Date.now();
84+
const retry = options.retry ?? {};
85+
const maxRetries = options.timeoutMs === Number.POSITIVE_INFINITY ? undefined : retry.retries;
86+
const reclaimGuardPath = `${lockPath}.reclaim`;
87+
let ownsReclaimGuard = false;
88+
let attempt = 0;
89+
// Bounded so a genuine denial still surfaces as EPERM, not a lock timeout.
90+
let transientDenials = 0;
91+
const withinDenialBudget = (): boolean => ++transientDenials <= maxTransientLockDenials;
92+
const waitForRetry = async (): Promise<void> => {
93+
const elapsed = Date.now() - startedAt;
94+
if (
95+
(options.timeoutMs !== undefined &&
96+
options.timeoutMs !== Number.POSITIVE_INFINITY &&
97+
elapsed >= options.timeoutMs) ||
98+
(maxRetries !== undefined && attempt >= maxRetries)
99+
) {
100+
throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), {
101+
code: "file_lock_timeout",
102+
lockPath,
103+
normalizedTargetPath,
104+
});
105+
}
106+
const remaining =
107+
options.timeoutMs === undefined || options.timeoutMs === Number.POSITIVE_INFINITY
108+
? Number.POSITIVE_INFINITY
109+
: Math.max(0, options.timeoutMs - elapsed);
110+
const delay = Math.min(computeSidecarLockDelayMs(retry, attempt), remaining);
111+
attempt += 1;
112+
await new Promise((resolve) => setTimeout(resolve, delay));
113+
};
114+
// Waiting can fail on the caller's own retry or deadline limits. Classifying
115+
// a denial as contention must not cost them the original diagnosis, so hand
116+
// the denial back when no further attempt can be scheduled.
117+
const retryOrRethrowDenial = async (denial: unknown): Promise<void> => {
118+
try {
119+
await waitForRetry();
120+
} catch (waitError) {
121+
if ((waitError as NodeJS.ErrnoException).code === "file_lock_timeout") throw denial;
122+
throw waitError;
123+
}
124+
};
125+
126+
try {
127+
while (true) {
128+
if (!ownsReclaimGuard && (await sidecarReclaimGuardExists(reclaimGuardPath))) {
129+
await waitForRetry();
130+
continue;
131+
}
132+
let handle: SidecarFileHandle | null = null;
133+
let lockFileCreateDenied = false;
134+
try {
135+
const payload = await options.payload();
136+
const { raw, ownershipToken } = serializeSidecarLockPayload(payload);
137+
if (options.lockRoot) {
138+
const relativeLockPath = relativeSidecarLockPath(options.lockRoot, lockPath);
139+
try {
140+
await options.lockRoot.create(relativeLockPath, raw, { mkdir: true, mode: 0o600 });
141+
} catch (error) {
142+
if (error instanceof FsSafeError && error.code === "already-exists") {
143+
throw Object.assign(new Error("sidecar lock exists"), { code: "EEXIST" });
144+
}
145+
throw error;
146+
}
147+
handle = (await options.lockRoot.open(relativeLockPath)).handle;
148+
} else {
149+
try {
150+
handle =
151+
(await createNativeExclusiveFile(lockPath, 0o600)) ??
152+
(await fs.open(lockPath, "wx"));
153+
} catch (createError) {
154+
lockFileCreateDenied = isTransientLockFileDenial(createError, lockPath);
155+
throw createError;
156+
}
157+
await handle.writeFile(raw, "utf8");
158+
}
159+
const snapshot = { raw, payload, stat: await handle.stat(), ownershipToken };
160+
const createdHeld: HeldSidecarLock = {
161+
refCount: 1,
162+
reentrantOwner: options.reentrantOwner,
163+
handle,
164+
lockPath,
165+
snapshot,
166+
acquiredAt: Date.now(),
167+
metadata: options.metadata ?? {},
168+
lockRoot: options.lockRoot,
169+
parsePayload: options.parsePayload,
170+
};
171+
context.held.set(normalizedTargetPath, createdHeld);
172+
if (ownsReclaimGuard) {
173+
try {
174+
await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath);
175+
ownsReclaimGuard = false;
176+
} catch (err) {
177+
await context.releaseHeldLock(normalizedTargetPath, createdHeld, { force: true });
178+
throw err;
179+
}
180+
}
181+
const returnedHandle = context.handleForHeldLock(normalizedTargetPath, createdHeld);
182+
const interval = options.compromiseCheckIntervalMs;
183+
if (options.onCompromised && interval !== undefined && interval > 0) {
184+
createdHeld.compromiseTimer = setInterval(() => {
185+
void returnedHandle.verifyStillHeld().then((stillHeld) => {
186+
if (!stillHeld && createdHeld.compromiseTimer) {
187+
clearInterval(createdHeld.compromiseTimer);
188+
createdHeld.compromiseTimer = undefined;
189+
options.onCompromised?.({ lockPath, normalizedTargetPath });
190+
}
191+
});
192+
}, interval);
193+
createdHeld.compromiseTimer.unref();
194+
}
195+
return returnedHandle;
196+
} catch (err) {
197+
if (handle) {
198+
const failedSnapshot: SidecarLockSnapshot = { payload: null };
199+
try {
200+
failedSnapshot.stat = await handle.stat();
201+
} catch {
202+
// Best-effort cleanup of a failed exclusive create.
203+
}
204+
const current = context.held.get(normalizedTargetPath);
205+
if (current?.handle === handle) {
206+
context.held.delete(normalizedTargetPath);
207+
}
208+
// If payload serialization/write fails, the file may be empty or
209+
// partial JSON, so remove while our exclusive handle is still open.
210+
if (!options.lockRoot) {
211+
await fs.rm(lockPath, { force: true }).catch(() => undefined);
212+
}
213+
await handle.close().catch(() => undefined);
214+
// Windows can refuse removing an open file; retry after close but
215+
// only if the path still points at the file identity we created.
216+
await removeSidecarLockIfUnchanged(lockPath, failedSnapshot, {
217+
lockRoot: options.lockRoot,
218+
parsePayload: options.parsePayload,
219+
});
220+
}
221+
if (lockFileCreateDenied && withinDenialBudget()) {
222+
await retryOrRethrowDenial(err);
223+
continue;
224+
}
225+
if ((err as { code?: unknown }).code !== "EEXIST") {
226+
throw err;
227+
}
228+
if (ownsReclaimGuard) {
229+
await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath);
230+
ownsReclaimGuard = false;
231+
continue;
232+
}
233+
const nowMs = Date.now();
234+
let snapshot: SidecarLockSnapshot | null;
235+
try {
236+
snapshot = await readSidecarLockSnapshot(lockPath, {
237+
lockRoot: options.lockRoot,
238+
parsePayload: options.parsePayload,
239+
});
240+
} catch (readErr) {
241+
if (!isTransientLockFileDenial(readErr, lockPath) || !withinDenialBudget()) throw readErr;
242+
await retryOrRethrowDenial(readErr);
243+
continue;
244+
}
245+
if (!snapshot) {
246+
continue;
247+
}
248+
if (context.held.has(normalizedTargetPath)) {
249+
await waitForRetry();
250+
continue;
251+
}
252+
const shouldReclaim = options.shouldReclaim ?? defaultSidecarLockShouldReclaim;
253+
if (
254+
await shouldReclaim({
255+
lockPath,
256+
normalizedTargetPath,
257+
payload: snapshot?.payload ?? null,
258+
staleMs: options.staleMs,
259+
nowMs,
260+
heldByThisProcess: context.held.has(normalizedTargetPath),
261+
})
262+
) {
263+
if (
264+
!(await sidecarLockSnapshotStillPresent(lockPath, snapshot, {
265+
lockRoot: options.lockRoot,
266+
parsePayload: options.parsePayload,
267+
}))
268+
) {
269+
continue;
270+
}
271+
const staleRecovery = options.staleRecovery ?? "fail-closed";
272+
if (staleRecovery === "remove-if-unchanged") {
273+
if (!(await tryAcquireSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath))) {
274+
await waitForRetry();
275+
continue;
276+
}
277+
ownsReclaimGuard = true;
278+
const removal = await removeStaleSidecarLockIfAllowed({
279+
lockPath,
280+
normalizedTargetPath,
281+
snapshot,
282+
shouldRemoveStaleLock: options.shouldRemoveStaleLock,
283+
lockRoot: options.lockRoot,
284+
parsePayload: options.parsePayload,
285+
});
286+
if (removal === "removed" || removal === "changed") {
287+
continue;
288+
}
289+
await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath);
290+
ownsReclaimGuard = false;
291+
}
292+
throw Object.assign(new Error(`file lock stale for ${normalizedTargetPath}`), {
293+
code: "file_lock_stale",
294+
lockPath,
295+
normalizedTargetPath,
296+
});
297+
}
298+
await waitForRetry();
299+
}
300+
}
301+
} finally {
302+
if (ownsReclaimGuard) {
303+
await releaseSidecarReclaimGuard(context.reclaimGuards, reclaimGuardPath).catch(
304+
() => undefined,
305+
);
306+
}
307+
}
308+
}

0 commit comments

Comments
 (0)