fix(process): harden filesystem snapshot identity and cancellation (#956)

* fix(process): bind snapshots to captured file identity

* fix(process): honor snapshot cancellation for empty files

* test(process): verify snapshot descriptor cleanup

* fix(process): preserve snapshot cancellation results

* fix(process): preserve non-cancellation capture failures

* test(process): verify descriptor cleanup with fstat

* fix(process): detect snapshot changes by ctime

* test(process): prove snapshot ctime invalidation
This commit is contained in:
morluto
2026-10-07 23:45:23 +08:00
committed by GitHub
parent d76f7d1508
commit 93aa9eb5c2
8 changed files with 377 additions and 13 deletions
+122
View File
@@ -0,0 +1,122 @@
import { fstatSync } from "node:fs";
import {
mkdtemp,
lstat,
open,
readdir,
rm,
utimes,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import { hashFile } from "./FilesystemSnapshot.js";
const countOpenDescriptorsFor = async (path: string): Promise<number> => {
const directory = process.platform === "linux" ? "/proc/self/fd" : "/dev/fd";
const expected = await lstat(path);
const descriptors = await readdir(directory);
const matches = await Promise.all(
descriptors.map(async (descriptor) => {
if (!/^\d+$/u.test(descriptor)) return false;
try {
const stats = fstatSync(Number(descriptor));
return stats.dev === expected.dev && stats.ino === expected.ino;
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "EBADF")
return false;
throw cause;
}
}),
);
return matches.filter(Boolean).length;
};
it("does not hash a replacement file using the earlier path metadata", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-identity-"));
const path = join(directory, "observed-file");
try {
await writeFile(path, "captured file\n");
const expected = await lstat(path);
await rm(path);
await writeFile(path, "replacement with a different identity and size\n");
await expect(hashFile(path, expected, 1_000)).resolves.toBeNull();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects a same-size rewrite even when its modification time is restored", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-ctime-"));
const path = join(directory, "observed-file");
try {
const fixedMtime = new Date("2020-01-02T03:04:05.000Z");
await writeFile(path, "before\n");
await utimes(path, fixedMtime, fixedMtime);
const expected = await lstat(path);
await writeFile(path, "after!\n");
await utimes(path, fixedMtime, fixedMtime);
const rewritten = await lstat(path);
expect(rewritten).toMatchObject({
dev: expected.dev,
ino: expected.ino,
mode: expected.mode,
size: expected.size,
mtimeMs: expected.mtimeMs,
});
expect(rewritten.ctimeMs).not.toBe(expected.ctimeMs);
await expect(hashFile(path, expected, 1_000)).resolves.toBeNull();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects cancellation for an empty file before returning its digest", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-empty-cancel-"));
const path = join(directory, "observed-file");
try {
await writeFile(path, "");
const expected = await lstat(path);
const controller = new AbortController();
controller.abort();
await expect(
hashFile(path, expected, 1_000, controller.signal),
).rejects.toMatchObject({ name: "AbortError" });
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.skipIf(process.platform === "win32")(
"closes the opened file when cancellation arrives during open",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-snapshot-cancel-"));
const path = join(directory, "observed-file");
try {
await writeFile(path, "captured file\n");
const expected = await lstat(path);
const controller = new AbortController();
const held = await open(path, "r");
expect(await countOpenDescriptorsFor(path)).toBe(1);
await held.close();
expect(await countOpenDescriptorsFor(path)).toBe(0);
const hashing = hashFile(path, expected, 1_000, controller.signal);
// hashFile reaches `open` synchronously before its first suspension, so
// this abort is observed after the descriptor is acquired and is handled
// by the `finally` close path.
controller.abort();
await expect(hashing).rejects.toMatchObject({ name: "AbortError" });
expect(await countOpenDescriptorsFor(path)).toBe(0);
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
+24 -6
View File
@@ -19,6 +19,16 @@ const hasSameIdentity = (
before.ino === after.ino &&
(expected === "directory" ? after.isDirectory() : after.isSymbolicLink());
const hasSameFileState = (before: Stats, after: Stats): boolean =>
before.dev === after.dev &&
before.ino === after.ino &&
before.isFile() &&
after.isFile() &&
before.mode === after.mode &&
before.size === after.size &&
before.mtimeMs === after.mtimeMs &&
before.ctimeMs === after.ctimeMs;
const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
try {
return await lstat(path);
@@ -29,18 +39,26 @@ const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
}
};
const hashFile = async (
/** Hash a file only when its opened descriptor still matches the captured path state. */
export const hashFile = async (
path: string,
expected: Stats,
maxBytes: number,
signal?: AbortSignal,
): Promise<string | null> => {
signal?.throwIfAborted();
const handle = await open(
path,
fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0),
fsConstants.O_RDONLY |
(fsConstants.O_NOFOLLOW ?? 0) |
(fsConstants.O_NONBLOCK ?? 0),
);
try {
signal?.throwIfAborted();
const stats = await handle.stat();
if (!stats.isFile() || stats.size > maxBytes) return null;
signal?.throwIfAborted();
if (!hasSameFileState(expected, stats) || stats.size > maxBytes)
return null;
const hash = createHash("sha256");
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes));
let position = 0;
@@ -57,8 +75,8 @@ const hashFile = async (
position += bytesRead;
}
const after = await handle.stat();
if (after.size !== stats.size || after.mtimeMs !== stats.mtimeMs)
return null;
signal?.throwIfAborted();
if (!hasSameFileState(stats, after)) return null;
return hash.digest("hex");
} finally {
await handle.close();
@@ -110,7 +128,7 @@ export const snapshotRoots = async (
if (stats.isFile()) {
const sha256 =
remainingBytes >= stats.size
? await hashFile(path, remainingBytes, signal)
? await hashFile(path, stats, remainingBytes, signal)
: null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
+2 -1
View File
@@ -449,6 +449,7 @@ export const resolveProcessResult = (
export const prepareProcessCapture = async (
scenario: ProcessScenario,
signal: AbortSignal | undefined,
captureSnapshot: typeof snapshotRoots = snapshotRoots,
host: ProcessPreparationHost = systemProcessPreparationHost,
): Promise<{
readonly temporaryRoot: string;
@@ -456,7 +457,7 @@ export const prepareProcessCapture = async (
readonly before: SnapshotResult;
}> => {
assertNotCancelled(signal);
const before = await snapshotRoots(scenario, signal);
const before = await captureSnapshot(scenario, signal);
const temporaryRoot = await host.createTemporaryRoot();
try {
const runId = randomUUID();
+31 -5
View File
@@ -233,6 +233,20 @@ const finishProcessRun = async (options: {
);
};
const normalizeCaptureFailure = (
cause: unknown,
signal: AbortSignal | undefined,
): unknown => {
if (cause instanceof ProcessCaptureError) return cause;
if (
signal?.aborted === true &&
(cause === signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
)
return processCaptureCancelled();
return cause;
};
const completeCapture = async (options: {
readonly scenario: ProcessScenario;
readonly hostPlatform: NodeJS.Platform;
@@ -245,6 +259,7 @@ const completeCapture = async (options: {
readonly interactions: readonly InteractionEvent[];
readonly exit: Awaited<ReturnType<typeof awaitTerminalExit>>;
readonly signal?: AbortSignal;
readonly captureSnapshot: typeof snapshotRoots;
readonly initiallyTruncated: boolean;
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
readonly recordEvent: RecordProcessCaptureEvent;
@@ -262,7 +277,7 @@ const completeCapture = async (options: {
const samplingPartial = (await runtime.stopSampler()).partial;
await settleProcessCaptureJournal(options.eventJournal);
assertNotCancelled(options.signal);
const after = await snapshotRoots(scenario, options.signal);
const after = await options.captureSnapshot(scenario, options.signal);
options.recordEvent("filesystem_checkpoints", 1);
const renderedFrames = await runtime.renderer.frames();
const checkpoints: UnverifiedProcessCapture["filesystem_checkpoints"] = [
@@ -319,10 +334,12 @@ const runProcessScenario = async (
signal?: AbortSignal,
hostEnvironment: Readonly<Record<string, string | undefined>> = process.env,
hostPlatform: NodeJS.Platform = process.platform,
captureSnapshot: typeof snapshotRoots = snapshotRoots,
): Promise<ProcessCapture> => {
const { temporaryRoot, runId, before } = await prepareProcessCapture(
scenario,
signal,
captureSnapshot,
);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
@@ -377,11 +394,12 @@ const runProcessScenario = async (
initiallyTruncated: before.truncated,
eventJournal,
recordEvent,
captureSnapshot,
...(signal === undefined ? {} : { signal }),
});
} catch (cause: unknown) {
runtime?.terminal.kill("SIGKILL");
executionFailure = cause;
executionFailure = normalizeCaptureFailure(cause, signal);
}
return finishProcessRun({
runtime,
@@ -401,6 +419,7 @@ export const captureProcessScenario = async (
signal?: AbortSignal,
platform: NodeJS.Platform = process.platform,
environment: Readonly<Record<string, string | undefined>> = process.env,
captureSnapshot: typeof snapshotRoots = snapshotRoots,
): Promise<Result<ProcessCapture, ProcessCaptureError | AnalysisError>> => {
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
if (ownershipReason !== undefined)
@@ -419,12 +438,19 @@ export const captureProcessScenario = async (
environment,
);
return ok(
await runProcessScenario(resolvedScenario, signal, environment, platform),
await runProcessScenario(
resolvedScenario,
signal,
environment,
platform,
captureSnapshot,
),
);
} catch (cause: unknown) {
const failure = normalizeCaptureFailure(cause, signal);
return err(
cause instanceof ProcessCaptureError
? cause
failure instanceof ProcessCaptureError
? failure
: new ProcessCaptureError("process capture failed", { cause }),
);
}