Files
openclaw/src/plugin-sdk/file-lock.ts
Peter Steinberger 9b1c36d23c fix: prevent exec approval revocation races (#103515)
* fix(security): serialize exec approval mutations

* fix(security): preserve additive approval writes

* test(cli): expect normalized approval shape

* fix(security): preserve exec approval compatibility

* test(security): exercise locked approval initialization

* test(security): mock serialized approval helpers

* test(exec): derive enforced command path from plan

* fix(gateway): always return approval CAS conflicts

* fix(macos): serialize exec approvals writes

* fix(security): repair approval build errors

* fix(security): serialize exec approval mutations

* fix(security): fail closed on approval persistence errors

* test(security): cover detached approval persistence failures

* fix(security): harden exec approval state

* style(macos): format exec approval sources

* fix(security): complete exec approval hardening

Co-authored-by: Coy Geek <65363919+coygeek@users.noreply.github.com>

* fix(macos): preserve approved login-shell semantics

* fix(macos): keep login shell approvals one-shot

* fix(security): linearize exec authorization

Co-authored-by: Coy Geek <65363919+coygeek@users.noreply.github.com>

* fix(security): preserve durable approval basis

Co-authored-by: Coy Geek <65363919+coygeek@users.noreply.github.com>

* fix(security): bind exec grants to current policy

Co-authored-by: Coy Geek <65363919+coygeek@users.noreply.github.com>

* test(security): fix exec revocation fixtures

* test(security): align gateway approval fixtures

* fix(macos): return approval decisions

* chore(i18n): sync native approval strings

* test(security): align approval hardening fixtures

* test(node): authorize completed event fixture

* test(security): fix approval decision fixtures

* test(security): await durable approval visibility

* fix(exec): preserve concurrent approval grants

* fix(exec): address exact-head CI failures

* fix(exec): preserve concurrent approval promotions

* fix(exec): make Swift shutdown state explicit

* test(macos): handle approval read failures

* fix(macos): harden approval socket paths

* fix(macos): preserve exact shell payload bytes

* test(macos): make approval fixtures explicit

* test(macos): fix approval suite compilation

* fix(macos): bound approval socket JSONL reads

* chore: move exec approval note to release process

* chore: move exec approval note to release process

---------

Co-authored-by: Coy Geek <65363919+coygeek@users.noreply.github.com>
2026-07-10 21:35:05 +01:00

156 lines
5.5 KiB
TypeScript

// File lock helpers serialize plugin writes that share a filesystem-backed state file.
import "../infra/fs-safe-defaults.js";
import {
acquireFileLock as acquireFsSafeFileLock,
drainFileLockManagerForTest,
resetFileLockManagerForTest,
} from "@openclaw/fs-safe/file-lock";
import {
isLockOwnerDefinitelyStale,
shouldRemoveDeadOwnerOrExpiredLock,
} from "../infra/stale-lock-file.js";
import { getFileLockProcessStartTime } from "../shared/pid-alive.js";
/** Retry and stale-recovery policy for acquiring a filesystem lock. */
export type FileLockOptions = {
/** Retry policy used while waiting for another process or re-entrant holder to release. */
retries: {
retries: number;
factor: number;
minTimeout: number;
maxTimeout: number;
randomize?: boolean;
};
/** Milliseconds used to classify contended sidecars as stale. */
stale: number;
/** Fail closed for security-sensitive state; generic locks retain shipped stale recovery. */
staleRecovery?: "fail-closed" | "remove-if-unchanged";
};
/** Live file-lock handle returned after successful acquisition. */
export type FileLockHandle = {
/** Absolute path to the `.lock` sidecar held for this file path. */
lockPath: string;
/** Releases one held reference; callers must await it before assuming peers can proceed. */
release: () => Promise<void>;
};
/** Stable error code used when lock acquisition retries are exhausted. */
export const FILE_LOCK_TIMEOUT_ERROR_CODE = "file_lock_timeout";
/** Stable error code used when stale lock recovery cannot proceed safely. */
export const FILE_LOCK_STALE_ERROR_CODE = "file_lock_stale";
/** Typed error thrown when a lock cannot be acquired before timeout. */
export type FileLockTimeoutError = Error & {
/** Stable error discriminator for lock acquisition timeout handling. */
code: typeof FILE_LOCK_TIMEOUT_ERROR_CODE;
/** Lock sidecar path that could not be acquired before retries were exhausted. */
lockPath: string;
};
/** Typed error thrown when a stale lock sidecar cannot be reclaimed safely. */
export type FileLockStaleError = Error & {
/** Stable error discriminator for stale-lock reclaim failures. */
code: typeof FILE_LOCK_STALE_ERROR_CODE;
/** Lock sidecar path that could not be safely reclaimed. */
lockPath: string;
};
const FILE_LOCK_MANAGER_KEY = "openclaw.plugin-sdk.file-lock";
let currentProcessStartTime: number | null | undefined;
function getCurrentProcessStartTime(): number | null {
if (currentProcessStartTime === undefined) {
currentProcessStartTime = getFileLockProcessStartTime(process.pid);
}
return currentProcessStartTime;
}
function normalizeLockError(err: unknown): never {
if ((err as { code?: unknown }).code === FILE_LOCK_TIMEOUT_ERROR_CODE) {
throw Object.assign(new Error((err as Error).message), {
code: FILE_LOCK_TIMEOUT_ERROR_CODE,
lockPath: (err as { lockPath?: string }).lockPath ?? "",
}) as FileLockTimeoutError;
}
if ((err as { code?: unknown }).code === FILE_LOCK_STALE_ERROR_CODE) {
throw Object.assign(new Error((err as Error).message), {
code: FILE_LOCK_STALE_ERROR_CODE,
lockPath: (err as { lockPath?: string }).lockPath ?? "",
}) as FileLockStaleError;
}
throw err;
}
/** Reset process-local file-lock state for tests that isolate lock managers. */
export function resetFileLockStateForTest(): void {
resetFileLockManagerForTest(FILE_LOCK_MANAGER_KEY, FILE_LOCK_MANAGER_KEY);
}
/** Wait for process-local file-lock state to drain before test teardown. */
export async function drainFileLockStateForTest(): Promise<void> {
await drainFileLockManagerForTest(FILE_LOCK_MANAGER_KEY, FILE_LOCK_MANAGER_KEY);
}
/** Acquire a re-entrant process-local file lock backed by a `.lock` sidecar file. */
export async function acquireFileLock(
filePath: string,
options: FileLockOptions,
): Promise<FileLockHandle> {
const staleRecovery = options.staleRecovery ?? "remove-if-unchanged";
try {
const lock = await acquireFsSafeFileLock(filePath, {
managerKey: FILE_LOCK_MANAGER_KEY,
staleMs: options.stale,
retry: options.retries,
staleRecovery,
allowReentrant: true,
payload: () => {
const payload: Record<string, unknown> = {
pid: process.pid,
createdAt: new Date().toISOString(),
};
const starttime = getCurrentProcessStartTime();
if (starttime !== null) {
payload.starttime = starttime;
}
return payload;
},
shouldReclaim: (params) =>
staleRecovery === "fail-closed"
? isLockOwnerDefinitelyStale({ payload: params.payload })
: shouldRemoveDeadOwnerOrExpiredLock({
payload: params.payload,
staleMs: params.staleMs,
nowMs: params.nowMs,
}),
...(staleRecovery === "remove-if-unchanged"
? {
shouldRemoveStaleLock: (snapshot: { payload: Record<string, unknown> | null }) =>
shouldRemoveDeadOwnerOrExpiredLock({
payload: snapshot.payload,
staleMs: options.stale,
}),
}
: {}),
});
return { lockPath: lock.lockPath, release: lock.release };
} catch (err) {
return normalizeLockError(err);
}
}
/** Run an async callback while holding a file lock, always releasing the lock afterward. */
export async function withFileLock<T>(
filePath: string,
options: FileLockOptions,
fn: () => Promise<T>,
): Promise<T> {
const lock = await acquireFileLock(filePath, options);
try {
return await fn();
} finally {
await lock.release();
}
}