Files
rea/tests/process-global/filesystemSnapshotFallbackCancellation.test.ts
ShuaixinHuang e9fc8fb30c fix(javascript): preserve runtime path bytes and Electron ownership (#4941)
* fix(javascript): preserve literal percent runtime paths

* fix(javascript): ignore resolve prefixes before the final anchor

* fix(electron): retain application roots for loadFile declarations

* fix(electron): resolve loadFile from enclosing application package

* fix(electron): retain outer application root across package scopes

* fix(electron): derive application ownership from inventoried packages

* fix(electron): retain resolved package entrypoint ownership

* fix(electron): preserve competing application ownership

* fix(electron): retain invalid and omitted runtime ownership

* fix(electron): preserve omitted module ownership and runtime paths

* fix(electron): preserve proven roots before confining page paths

* fix(electron): retain possible owners behind missing imports

* fix(electron): distinguish absent imports and owned page candidates

* fix(electron): keep unavailable JSON out of owner gaps

* fix(electron): retain exact loader formats and default entry status

* fix(electron): retain unavailable entrypoint ownership candidates

* test(ghidra): preserve Windows Node probe prerequisites

* test(ghidra): assert cancellation during profile shutdown

* fix(electron): separate examined imports from frontend ownership

* fix(electron): retain unavailable directory entrypoint owners

* test(jeb): retain Linux ownership prerequisite in isolation

* fix(javascript): retain unchecked loader ownership and literal main paths

* fix(javascript): preserve runtime paths and call-site module aliases

* fix(javascript): bound module alias traversal and preserve projections

* fix(javascript): retain host module and nested artifact path boundaries

* fix(javascript): preserve ESM and archive module loader provenance

* test(javascript): distinguish unmapped containers from missing exports

* fix: retain default module aliases and Electron builtin imports

* fix: preserve host file URL and inward ASAR ownership

* fix: preserve CommonJS file URL classification in CI fixtures

* fix: retain bound module loaders and Windows entrypoint uncertainty

* fix: retain ASAR uncertainty and invalidate changed Electron app roots

* fix(javascript): retain ownership uncertainty across loader boundaries

* fix(javascript): preserve loader sources and bound alias queries

* fix(javascript): retain destructured loader sources

* fix(javascript): preserve loader uncertainty at resolution boundaries

* fix(javascript): preserve callable and package launch ownership

* fix(javascript): preserve captured values across member reads

* test(process): assert tagged filesystem cancellation failures

* fix(javascript): preserve inventory bases and invocation read timing

* fix(javascript): preserve ownership across indirect and unread loads

* test(javascript): order fixture directory creation on Windows

* test(javascript): share ordered filesystem fixture writer

* fix(javascript): unify loader provenance and package validation

* fix(javascript): preserve captured Node require loader values

* fix(javascript): preserve loader invocation authority

* fix(javascript): verify generic loader invocation authority

* fix(javascript): preserve conditional loader method alternatives

* fix(javascript): require proven factories for source association

* fix(javascript): honor replaced Electron app path setters

* fix(javascript): prove path and assignment source ownership

* fix(javascript): retain native delegate eligibility through shared writes

* fix(process): settle stale baseline errors after confirmed absence

* fix(javascript): preserve assignment and path boundary evidence

* fix(javascript): prove source-directory resolve anchors

* fix: preserve application path provenance and portable schemas

* fix(javascript): retain CommonJS exported setter effects

* fix: isolate Linux identity observations and retain native module exports

* fix(javascript): preserve published app and helper provenance

* fix(javascript): normalize typed stores and native path fixtures
2026-10-20 17:25:19 +08:00

157 lines
5.7 KiB
TypeScript

import { createHash } from "node:crypto";
import { lstat, writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
const observation = vi.hoisted(() => ({
path: "",
cancelAfterDescriptorInspection: false,
descriptorInspected: false,
controller: undefined as AbortController | undefined,
reason: undefined as Error | undefined,
handles: [] as FileHandle[],
}));
// Force the capability fallback while keeping actual filesystem IO. These
// cases establish cancellation semantics, not native Windows compatibility.
vi.mock("node:fs", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs")>();
return {
...original,
constants: { ...original.constants, O_NOFOLLOW: 0 },
};
});
vi.mock("node:fs/promises", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs/promises")>();
return {
...original,
open: async (...args: Parameters<typeof original.open>) => {
const handle = await original.open(...args);
if (args[0] === observation.path) {
observation.handles.push(handle);
const stat = handle.stat.bind(handle);
vi.spyOn(handle, "stat").mockImplementation(async (options) => {
const stats = await stat(options);
observation.descriptorInspected = true;
return stats;
});
}
return handle;
},
lstat: async (...args: Parameters<typeof original.lstat>) => {
const stats = await original.lstat(...args);
if (
args[0] === observation.path &&
observation.cancelAfterDescriptorInspection &&
observation.descriptorInspected
)
observation.controller?.abort(observation.reason);
return stats;
},
};
});
import { parseProcessScenario } from "../../src/domain/process/processScenario.js";
import {
hashFile,
snapshotRoots,
ProcessCaptureSnapshotFailure,
} from "../../src/process/capture/FilesystemSnapshot.js";
import { ProcessCaptureReadFailure } from "../../src/process/capture/ProcessCaptureRead.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
afterEach(() => {
observation.path = "";
observation.cancelAfterDescriptorInspection = false;
observation.descriptorInspected = false;
observation.controller = undefined;
observation.reason = undefined;
observation.handles.length = 0;
});
it.each(["hash", "snapshot"] as const)(
"rejects cancellation during the final %s fallback inspection and closes the descriptor",
async (operation) => {
const directory = await createTestTempDirectory("rea-fs-fallback-cancel-");
const path = join(directory, "observed-file");
await writeFile(path, "captured bytes");
const expected = await lstat(path);
const controller = new AbortController();
const reason = Object.assign(
new Error("cancelled during final named-file inspection"),
{ code: "EACCES" },
);
observation.path = path;
observation.controller = controller;
observation.reason = reason;
// The final fallback inspection is the named lookup after the opened
// descriptor was inspected. Admission may perform other named lookups.
observation.cancelAfterDescriptorInspection = true;
const result =
operation === "hash"
? hashFile(path, expected, 1_000, controller.signal)
: snapshotRoots(
parseProcessScenario({
executable: process.execPath,
working_directory: directory,
filesystem_observation_paths: [path],
}),
controller.signal,
);
const failure: unknown = await result.catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "ProcessCaptureError",
reason: "cancelled",
userCategory: "cancelled",
});
if (operation === "hash") {
expect(failure).toBeInstanceOf(ProcessCaptureReadFailure);
const read = failure as ProcessCaptureReadFailure;
expect(read.cause).toBe(reason);
expect(read.userCategory).toBe("cancelled");
expect(read.outcome).toMatchObject({ kind: "failed", cause: reason });
expect(read.cleanupLeases).toEqual([]);
expect(read.cleanupIncomplete).toBe(false);
} else {
expect(failure).toBeInstanceOf(ProcessCaptureSnapshotFailure);
const snapshot = failure as ProcessCaptureSnapshotFailure;
expect(snapshot.cause).toBe(reason);
expect(snapshot.userCategory).toBe("cancelled");
expect(snapshot.snapshot).toMatchObject({
files: [],
completeRoots: [],
truncated: true,
coverage: { enumeration_truncated: true },
});
expect(snapshot.cleanupLeases).toEqual([]);
expect(snapshot.cleanupIncomplete).toBe(false);
}
expect(controller.signal.aborted).toBe(true);
expect(observation.handles).toHaveLength(1);
await expect(observation.handles[0]?.stat()).rejects.toMatchObject({
code: "EBADF",
});
},
);
it("keeps an unchanged fallback digest and closes its descriptor", async () => {
const directory = await createTestTempDirectory("rea-fs-fallback-digest-");
const path = join(directory, "observed-file");
const bytes = Buffer.from("captured bytes");
await writeFile(path, bytes);
const expected = await lstat(path);
observation.path = path;
await expect(hashFile(path, expected, 1_000)).resolves.toEqual({
state: "hashed",
sha256: createHash("sha256").update(bytes).digest("hex"),
});
expect(observation.descriptorInspected).toBe(true);
expect(observation.handles).toHaveLength(1);
await expect(observation.handles[0]?.stat()).rejects.toMatchObject({
code: "EBADF",
});
});