fix: consolidate boundary ownership and cleanup failure paths (#477)

This commit is contained in:
morluto
2026-09-08 10:59:13 +08:00
committed by GitHub
parent c490d85045
commit 2160d4fae5
138 changed files with 2220 additions and 1781 deletions
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import { assertLinuxPackageProviderFailure } from "../../../scripts/verify-package-platform.mjs";
const missingDisplay = {
code: "provider_unavailable",
details: {
failure_code: "runtime_dependency_unavailable",
exit_code: 79,
diagnostics: {
component: "hopper_private_display",
operation: "probe",
reason: "missing_xvfb",
status: "error",
failure_code: "runtime_dependency_unavailable",
strategy: "unavailable",
},
},
};
const execution = (failure: unknown, status = 1) => ({
status,
stdout: JSON.stringify(failure),
});
describe("packaged Linux failure verification", () => {
it("accepts the unsupported fixture build or an exact missing display dependency", () => {
expect(() =>
assertLinuxPackageProviderFailure(execution(missingDisplay)),
).not.toThrow();
expect(() =>
assertLinuxPackageProviderFailure(
execution({
code: "provider_unavailable",
details: { failure_code: "unsupported_hopper_build", exit_code: 72 },
}),
),
).not.toThrow();
});
it.each([
execution(missingDisplay, 0),
execution({ code: "provider_unavailable" }),
execution({
...missingDisplay,
details: {
failure_code: "runtime_dependency_unavailable",
exit_code: 79,
},
}),
execution({
...missingDisplay,
details: {
...missingDisplay.details,
diagnostics: {
...missingDisplay.details.diagnostics,
reason: "ownership_mismatch",
},
},
}),
execution({
...missingDisplay,
details: { failure_code: "unsupported_hopper_build", exit_code: 75 },
}),
execution({ ...missingDisplay, code: "internal_error" }),
])(
"rejects success, unrelated failures, and incomplete diagnostics: %j",
(result) => {
expect(() => assertLinuxPackageProviderFailure(result)).toThrow(
"did not fail closed",
);
},
);
});
@@ -130,6 +130,24 @@ describe("policy revocation approval", () => {
}, 40_000);
});
describe("policy capability coverage", () => {
it.each(["v8_inspector_observe", "javascript_replay", "managed_runtime"])(
"explains %s without granting disabled authority",
async (capability) => {
const result = await runCli(["policy", "explain", capability, "--json"], {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "false",
REA_JAVASCRIPT_REPLAY_ENABLED: "false",
REA_MANAGED_RUNTIME_ENABLED: "false",
});
expect(result.output).toMatchObject({
allowed: false,
error: { code: "permission_required" },
});
},
);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parseBinaryTarget } from "../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { pe, thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -0,0 +1,42 @@
import { appendFile, open, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { readBoundedFileBytes } from "../../../src/process/BoundedFileBytes.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("bounded file byte reads", () => {
it.each([0, 1, 65_536, 65_537])(
"accepts a file exactly at the %i byte limit",
async (limit) => {
const root = await createTestTempDirectory("rea-bounded-bytes-");
const path = join(root, "input");
const content = Buffer.alloc(limit, 0x61);
await writeFile(path, content);
const handle = await open(path, "r");
try {
expect(await readBoundedFileBytes(handle, limit)).toEqual(content);
} finally {
await handle.close();
}
},
);
it("stops after one overflow byte when a file grows beyond its admitted size", async () => {
const root = await createTestTempDirectory("rea-growing-bytes-");
const path = join(root, "input");
await writeFile(path, "0123456789");
const handle = await open(path, "r");
try {
expect((await handle.stat()).size).toBeLessThan(12);
await appendFile(path, "abcdefghijklmnopqrstuvwxyz");
expect(await readBoundedFileBytes(handle, 12)).toBeUndefined();
const next = Buffer.alloc(1);
expect((await handle.read(next, 0, 1, null)).bytesRead).toBe(1);
expect(next.toString()).toBe("d");
} finally {
await handle.close();
}
});
});
@@ -0,0 +1,45 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const MAX_BYTES = 64 * 1_024 * 1_024;
describe("bounded CLI JSON input", () => {
it("rejects oversized inline UTF-8 before returning or echoing its content", async () => {
const input = `"${"é".repeat(MAX_BYTES / 2)}"`;
expect(input.length).toBeLessThan(MAX_BYTES);
const result = await parseCliJsonInput(input, "test-input");
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
input_reason: "too-large",
maximum_input_bytes: MAX_BYTES,
});
expect(JSON.stringify(result.error).length).toBeLessThan(1_024);
});
it("preserves JSON scalars and distinguishes malformed inline text from files", async () => {
for (const value of [null, false, 0, "text", [], {}])
expect(
await parseCliJsonInput(JSON.stringify(value), "test-input"),
).toEqual({ ok: true, value });
expect(await parseCliJsonInput("{", "test-input")).toMatchObject({
ok: false,
});
const root = await createTestTempDirectory("rea-json-input-");
const path = join(root, "input.json");
await writeFile(path, '{"value":1}');
expect(await parseCliJsonInput(path, "test-input")).toEqual({
ok: true,
value: { value: 1 },
});
expect(await parseCliJsonInput(root, "test-input")).toMatchObject({
ok: false,
error: { input_reason: "not-file" },
});
});
});
@@ -0,0 +1,58 @@
import { chmod, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
configureJsonClient,
configureTomlClient,
} from "../../../src/application/SetupClientConfiguration.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("client configuration write failures", () => {
it.skipIf(process.platform === "win32" || process.getuid?.() === 0).each([
["json", configureJsonClient],
["toml", configureTomlClient],
] as const)(
"classifies a denied %s write as a write failure",
async (format, configure) => {
const root = await createTestTempDirectory("rea-client-unwritable-");
await chmod(root, 0o500);
try {
expect(
await configure({
name: format === "toml" ? "codex" : "cursor",
format,
configPath: join(root, `config.${format}`),
}),
).toEqual({ status: "failed", reason: "write" });
} finally {
await chmod(root, 0o700);
}
},
);
});
describe("TOML client configuration comparison", () => {
it.each(["nan", "inf", "-inf"])(
"replaces a registration containing %s and preserves unrelated settings",
async (value) => {
const root = await createTestTempDirectory("rea-client-toml-");
const configPath = join(root, "config.toml");
const original = `unrelated = ${value}\n[mcp_servers.rea]\ncommand = "old"\nstartup_timeout_sec = ${value}\n`;
await writeFile(configPath, original);
const client = { name: "codex", format: "toml", configPath } as const;
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "configured",
backupPath: `${configPath}.rea.backup`,
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(configPath, "utf8")).toContain(
`unrelated = ${value}`,
);
expect(await configureTomlClient(client, {}, ["rea", "mcp"])).toEqual({
status: "unchanged",
});
},
);
});
@@ -62,6 +62,25 @@ describe("client registration status", () => {
expect(JSON.stringify(statuses)).not.toContain("SECRET");
});
it.each([null, [], "invalid"])(
"reports a malformed server table %j as invalid",
async (servers) => {
const home = await createTestTempDirectory("rea-registration-shape-");
await mkdir(join(home, ".cursor"));
await writeFile(
join(home, ".cursor/mcp.json"),
JSON.stringify({ mcpServers: servers }),
);
expect(await readClientRegistrationStatuses(home)).toEqual([
expect.objectContaining({
client: "cursor",
state: "invalid",
command: [],
}),
]);
},
);
it("reports an unversioned npx registration as stale", async () => {
const home = await createTestTempDirectory("rea-registrations-");
await mkdir(join(home, ".codex"));
@@ -12,7 +12,7 @@ import {
snapshotBinding,
snapshotTarget,
} from "../../../src/domain/analysisSnapshot.js";
import { parseBinaryTarget } from "../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
@@ -12,6 +12,18 @@ import {
} from "../../../src/browser/ElectronFileScope.js";
describe("Electron file scope", () => {
it("accepts dot-prefixed child names beneath a canonical root", async () => {
const root = await createTestTempDirectory("rea-electron-dot-child-");
const directory = join(root, "..cache");
await mkdir(directory);
const path = join(directory, "index.html");
await writeFile(path, "allowed");
const roots = await canonicalElectronRoots([root]);
expect(await authorizedElectronFile(pathToFileURL(path).href, roots)).toBe(
path,
);
});
it("accepts canonical files within a root and rejects escape forms", async () => {
const base = await createTestTempDirectory("rea-electron-scope-");
const root = join(base, "root");
@@ -1,4 +1,4 @@
import { mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { mkdir, readdir, readFile, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -17,12 +17,12 @@ import {
type EvidenceFilePolicy,
} from "../../../src/domain/evidenceBundle.js";
const bundle = () =>
const bundle = (result = true) =>
createEvidenceBundle([
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "health", parameters: {}, result: true },
{ operation: "health", parameters: {}, result },
),
]);
@@ -34,6 +34,44 @@ const policy = (root: string): EvidenceFilePolicy => ({
maxNodes: 10_000,
});
describe("evidence bundle publication", () => {
it("allows only one simultaneous export without overwrite approval", async () => {
const root = await createTestTempDirectory("rea-evidence-exclusive-");
const path = join(root, "bundle.json");
const candidates = [bundle(), bundle(false)];
const results = await Promise.all(
candidates.map((value) =>
writeEvidenceBundle(value, path, false, policy(root)),
),
);
expect(results.filter(({ ok }) => ok)).toHaveLength(1);
expect(results.filter(({ ok }) => !ok)).toMatchObject([
{ ok: false, error: { _tag: "EvidenceFileError", reason: "exists" } },
]);
const winner = candidates[results.findIndex(({ ok }) => ok)];
expect(await readEvidenceBundle(path, policy(root))).toEqual({
ok: true,
value: winner,
});
expect(await readdir(root)).toEqual(["bundle.json"]);
});
it("round trips dot-prefixed child names beneath an approved root", async () => {
const root = await createTestTempDirectory("rea-evidence-dot-child-");
const directory = join(root, "..cache");
await mkdir(directory);
const path = join(directory, "bundle.json");
const value = bundle();
expect(
await writeEvidenceBundle(value, path, false, policy(root)),
).toMatchObject({ ok: true });
expect(await readEvidenceBundle(path, policy(root))).toEqual({
ok: true,
value,
});
});
});
describe("evidence bundle filesystem adapter", () => {
it("round trips canonical bytes and requires explicit overwrite", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
@@ -51,6 +51,46 @@ const fixture = async () => {
};
describe("persistent cross-version investigation workspace", () => {
it("uses valid workspace roots when another configured root is missing", async () => {
const root = await createTestTempDirectory("rea-workspace-stale-root-");
const path = join(root, "workspace.json");
const workspace = createInvestigationWorkspace(
"stale-root",
createEvidenceBundle([]),
[],
);
const configured = {
...policy(root),
roots: [join(root, "missing"), root],
};
expect(
await writeInvestigationWorkspace(workspace, path, null, configured),
).toMatchObject({ ok: true });
expect(await readInvestigationWorkspace(path, configured)).toEqual({
ok: true,
value: workspace,
});
});
it("stores workspaces in dot-prefixed child directories", async () => {
const root = await createTestTempDirectory("rea-workspace-dot-child-");
const directory = join(root, "..cache");
await mkdir(directory);
const path = join(directory, "workspace.json");
const workspace = createInvestigationWorkspace(
"dot-child",
createEvidenceBundle([]),
[],
);
expect(
await writeInvestigationWorkspace(workspace, path, null, policy(root)),
).toMatchObject({ ok: true });
expect(await readInvestigationWorkspace(path, policy(root))).toEqual({
ok: true,
value: workspace,
});
});
it("enforces shared JSON depth limits while reading workspaces", async () => {
const { directory, path, input } = await fixture();
const completed = await runCrossVersionInvestigation(
@@ -78,30 +78,33 @@ describe("project permission store", () => {
});
});
it("round-trips managed runtime project grants", async () => {
const project = await createTestTempDirectory("rea-policy-managed-");
const path = join(project, "permissions.json");
const grant = {
grant_id: "project:managed-runtime",
capability: "managed_runtime" as const,
roots: [project],
executables: [process.execPath],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
};
it.each(["managed_runtime", "v8_inspector_observe"] as const)(
"round-trips %s project grants",
async (capability) => {
const project = await createTestTempDirectory("rea-policy-managed-");
const path = join(project, "permissions.json");
const grant = {
grant_id: "project:managed-runtime",
capability,
roots: [project],
executables: [process.execPath],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
};
expect(
await writeProjectPermissionStore(path, project, [grant]),
).toMatchObject({ ok: true, value: { grants: [grant] } });
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: true,
value: { grants: [grant] },
});
});
expect(
await writeProjectPermissionStore(path, project, [grant]),
).toMatchObject({ ok: true, value: { grants: [grant] } });
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: true,
value: { grants: [grant] },
});
},
);
it("classifies malformed JSON as an invalid store", async () => {
const project = await createTestTempDirectory("rea-policy-invalid-");
@@ -0,0 +1,38 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { writeProjectPermissionStore } from "../../../src/application/ProjectPermissionStore.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("permission store write ownership", () => {
it("preserves the store and live owner when replacement cannot acquire the transaction lock", async () => {
const project = await createTestTempDirectory("rea-policy-locked-write-");
const path = join(project, "permissions.json");
expect((await writeProjectPermissionStore(path, project, [])).ok).toBe(
true,
);
const before = await readFile(path);
const lockPath = `${path}.lock`;
const owner = `${process.pid}\n`;
await writeFile(lockPath, owner, { mode: 0o600 });
const result = await writeProjectPermissionStore(path, project, [
{
grant_id: "project:new",
capability: "evidence_read",
roots: [project],
executables: [],
environment_names: [],
network: "none",
mount: false,
lifetime: "project",
operation_identity: null,
expires_at: null,
},
]);
expect(result).toMatchObject({ ok: false, error: { reason: "locked" } });
expect(await readFile(path)).toEqual(before);
expect(await readFile(lockPath, "utf8")).toBe(owner);
});
});
@@ -125,6 +125,26 @@ describe("reference source import error projection", () => {
});
describe("reference source import behavior", () => {
it("imports BMP and supplementary filenames in Unicode code point order", async () => {
const root = await createTestTempDirectory("reference-unicode-");
try {
const paths = ["\uE000.ts", "\u{10000}.ts"];
await Promise.all(
paths.map((path) =>
writeFile(join(root, path), "export const value = 1;\n"),
),
);
const result = await importTree(root, root);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries.map(({ path }) => path)).toEqual(paths);
const repeated = await importTree(root, root);
expect(repeated).toEqual(result);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("is relocation-stable, resolves imports, and excludes secrets before capture", async () => {
const parent = await createTestTempDirectory("rea-reference-import-");
try {
@@ -0,0 +1,44 @@
import { access, readFile } from "node:fs/promises";
import { dirname } from "node:path";
import { describe, expect, it } from "vitest";
import { buildLinuxX64ReplaySeccomp } from "../../../src/replay/LinuxSeccompPolicy.js";
import { temporaryFilterHandle } from "../../../src/replay/ReplaySeccompFile.js";
describe("replay seccomp file ownership", () => {
it("writes the policy bytes and removes its private directory on close", async () => {
const filter = await temporaryFilterHandle();
try {
expect(await readFile(filter.path)).toEqual(
Buffer.from(buildLinuxX64ReplaySeccomp()),
);
expect(await filter.handle.readFile()).toEqual(
Buffer.from(buildLinuxX64ReplaySeccomp()),
);
} finally {
await filter.close();
}
await expect(access(dirname(filter.path))).rejects.toThrow();
await filter.close();
});
it.skipIf(process.platform !== "linux")(
"removes the directory even when descriptor cleanup rejects",
async () => {
const filter = await temporaryFilterHandle();
const close = filter.handle.close.bind(filter.handle);
const failure = new Error("injected descriptor cleanup failure");
filter.handle.close = async () => {
throw failure;
};
try {
await expect(filter.close()).rejects.toBe(failure);
await expect(access(dirname(filter.path))).rejects.toThrow();
} finally {
filter.handle.close = close;
await filter.close();
}
},
);
});
@@ -0,0 +1,81 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { prepareReplayPlan } from "../../../src/application/JavaScriptReplayPlanning.js";
import { controlledReplayInputSchema } from "../../../src/domain/javascriptReplay.js";
import { SystemJavaScriptReplayHost } from "../../../src/replay/SystemJavaScriptReplayHost.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("replay source byte admission", () => {
it.each([0, 16, 65_537])("reads exactly %i admitted bytes", async (limit) => {
const root = await createTestTempDirectory("rea-replay-source-");
const path = join(root, "module.mjs");
const bytes = Buffer.alloc(limit, 0x61);
await writeFile(path, bytes);
expect(
await new SystemJavaScriptReplayHost().readSource(path, limit),
).toEqual({
canonicalPath: path,
bytes,
});
});
it("rejects an oversized source and a directory", async () => {
const root = await createTestTempDirectory("rea-replay-source-");
const path = join(root, "module.mjs");
await writeFile(path, "oversized");
const host = new SystemJavaScriptReplayHost();
await expect(host.readSource(path, 1)).rejects.toThrow("declared limit");
await expect(host.readSource(root, 1)).rejects.toThrow();
});
});
it("rejects a host result larger than the remaining module budget", async () => {
const path = process.execPath;
const identity = { path, version: "fixture", sha256: "1".repeat(64) };
const input = controlledReplayInputSchema.parse({
mode: "plan",
left: {
modules: [
{
alias: "entry",
path,
format: "esm",
role: "module",
dependencies: {},
},
],
entry_alias: "entry",
entry_export: "default",
},
cases: [{ case_id: "one", arguments: [] }],
limits: { module_bytes: 16 },
});
await expect(
prepareReplayPlan(
input,
{
status: "enabled",
roots: [path],
nodePath: path,
bubblewrapPath: path,
systemdRunPath: path,
systemctlPath: path,
shellPath: path,
},
{
readSource: async (canonicalPath, maximumBytes) => ({
canonicalPath,
bytes: Buffer.alloc(maximumBytes + 1),
}),
identifyExecutable: async () => identity,
identifyWorker: async () => identity,
identifyRuntimeClosure: async () => [],
seccompDigest: () => "2".repeat(64),
probe: async () => undefined,
},
),
).rejects.toThrow("Replay module bytes exceed the aggregate limit");
});
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
import { access, readFile, readdir } from "node:fs/promises";
import { access, readFile, readdir, readlink, rm } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
@@ -19,6 +19,26 @@ const LIMITS = {
} as const;
describe("safe artifact output tree", () => {
it.skipIf(process.platform !== "linux")(
"closes the parent descriptor when the output disappears before commit",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output, LIMITS);
await rm(output, { recursive: true });
await expect(tree.commit()).rejects.toThrow();
const targets = await Promise.all(
(await readdir("/proc/self/fd")).map((fd) =>
readlink(`/proc/self/fd/${fd}`).catch(() => undefined),
),
);
expect(targets.filter((target) => target === parent)).toEqual([]);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
},
);
it("removes only its owned tree after digest failure and proves absence", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
@@ -174,7 +174,9 @@ describe("JSON client configuration migration and provider paths", () => {
const client = { name: "cursor", configPath };
const original = "{}\n";
await writeFile(configPath, original);
expect(await configureJsonClient(client, hopperPath)).toMatchObject({
expect(
await configureJsonClient(client, { HOPPER_LAUNCHER_PATH: hopperPath }),
).toMatchObject({
status: "configured",
});
expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
@@ -186,11 +188,15 @@ describe("JSON client configuration migration and provider paths", () => {
},
},
});
expect(await configureJsonClient(client, hopperPath)).toEqual({
expect(
await configureJsonClient(client, { HOPPER_LAUNCHER_PATH: hopperPath }),
).toEqual({
status: "unchanged",
});
expect(
await configureJsonClient(client, "/opt/hopper/bin/Hopper"),
await configureJsonClient(client, {
HOPPER_LAUNCHER_PATH: "/opt/hopper/bin/Hopper",
}),
).toMatchObject({ status: "configured" });
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
});
@@ -0,0 +1,81 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { lstat, readdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
createStoreFileLock,
removeStaleStoreFileLock,
} from "../../../src/application/StoreFileLock.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("store lock cleanup ownership", () => {
it.each(["released", "replaced"] as const)(
"preserves a successor lock when an old %s owner cleans up",
async (state) => {
const root = await createTestTempDirectory("rea-store-lock-owner-");
const path = join(root, "transaction.lock");
const previous = await createStoreFileLock(path);
if (state === "released") await previous.release();
else await rm(path, { recursive: true });
const successor = await createStoreFileLock(path);
try {
await previous.release();
await expect(lstat(path)).resolves.toBeDefined();
await expect(createStoreFileLock(path)).rejects.toMatchObject({
code: "EEXIST",
});
} finally {
await successor.release();
}
},
);
});
describe("store lock acquisition and recovery", () => {
it("admits one concurrent owner and removes all preparation directories", async () => {
const root = await createTestTempDirectory("rea-store-lock-contenders-");
const path = join(root, "transaction.lock");
const results = await Promise.allSettled(
Array.from({ length: 8 }, () => createStoreFileLock(path)),
);
try {
expect(
results.filter((result) => result.status === "fulfilled"),
).toHaveLength(1);
for (const result of results)
if (result.status === "rejected")
expect(result.reason).toMatchObject({ code: "EEXIST" });
expect(await readdir(root)).toEqual(["transaction.lock"]);
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await Promise.all(
results.map((result) =>
result.status === "fulfilled" ? result.value.release() : undefined,
),
);
}
expect(await readdir(root)).toEqual([]);
});
it("recovers a directory lock abandoned by an exited process", async () => {
const root = await createTestTempDirectory("rea-store-lock-exited-");
const path = join(root, "transaction.lock");
await promisify(execFile)(
process.execPath,
["tests/fixtures/abandonStoreFileLock.mjs", path],
{ timeout: 5_000 },
);
expect((await lstat(path)).isDirectory()).toBe(true);
expect(await removeStaleStoreFileLock(path)).toBe(true);
const successor = await createStoreFileLock(path);
try {
expect(await removeStaleStoreFileLock(path)).toBe(false);
} finally {
await successor.release();
}
expect(await readdir(root)).toEqual([]);
});
});
@@ -0,0 +1,49 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { classifyRoot } from "../../../src/application/ArtifactInventory/classify.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("ZIP signature detection", () => {
it.each([
[0x03, 0x04, true],
[0x05, 0x06, true],
[0x07, 0x08, true],
[0x03, 0x06, false],
[0x03, 0x08, false],
[0x05, 0x04, false],
[0x05, 0x08, false],
[0x07, 0x04, false],
[0x07, 0x06, false],
] as const)(
"classifies PK %i %i with archive signature %s",
async (third, fourth, archive) => {
const root = await createTestTempDirectory("rea-zip-signature-");
const path = join(root, "input");
await writeFile(path, Buffer.from([0x50, 0x4b, third, fourth]));
expect(await classifyRoot(path, false)).toBe(archive ? "zip" : "file");
const target = await parseBinaryTarget(path);
if (archive)
expect(target).toMatchObject({ ok: true, value: { format: "zip" } });
else
expect(target).toMatchObject({
ok: false,
error: { _tag: "BinaryTargetError" },
});
},
);
it.each([[], [0x50], [0x50, 0x4b], [0x50, 0x4b, 0x03]])(
"rejects an incomplete signature %j",
async (...bytes) => {
const root = await createTestTempDirectory("rea-zip-short-");
const path = join(root, "input");
await writeFile(path, Buffer.from(bytes));
expect(await classifyRoot(path, false)).toBe("file");
expect((await parseBinaryTarget(path)).ok).toBe(false);
},
);
});
@@ -6,7 +6,7 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import type { AnalysisExecution } from "../../../../src/application/AnalysisProvider.js";
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
@@ -16,7 +16,7 @@ import {
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../../../src/domain/artifactInspection.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
describe("artifact archive inventory", () => {
@@ -18,7 +18,7 @@ import {
} from "../../../../src/contracts/artifactToolContracts.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
describe("artifact archive safety", () => {
@@ -12,6 +12,30 @@ import { err } from "../../../src/domain/result.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
describe("binary session", () => {
it("owns provider rejection when profile resolution synchronously cancels opening", async () => {
const [first] = await createBinarySessionTargets();
const provider = createCacheProvider([]);
const controller = new AbortController();
provider.resolveAnalysisProfile = () => {
controller.abort();
return Promise.reject(new Error("Profile resolution cancelled"));
};
const session = createTestBinarySession(provider);
try {
await expect(
session.open(first, { signal: controller.signal }),
).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
});
// Allow Node to report any rejection abandoned by the cancellation path.
await new Promise<void>((resolve) => setImmediate(resolve));
expect(session.activeTarget()).toBeUndefined();
} finally {
await session.close();
}
});
it("cancels legacy profile resolution even when the provider ignores its signal", async () => {
const [first] = await createBinarySessionTargets();
const provider = createCacheProvider([]);
@@ -18,6 +18,32 @@ import { createElectronActiveObservationFixtureResult } from "../../../src/domai
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
it("reconciles runtime scripts inside dot-prefixed child directories", async () => {
const root = await applicationFixture();
await mkdir(join(root, "..cache"));
await writeFile(join(root, "..cache", "app.js"), SOURCE);
const result = reconcileJavaScriptRuntime({
static_layers: [
{ role: "application", analysis: await analyzeFixture(root) },
],
runtime_observations: [
electronRuntimeEvidence(root, SOURCE, {
scriptFile: "..cache/app.js",
includeWorker: false,
}),
],
});
expect(result.reconciliations).toEqual(
expect.arrayContaining([
expect.objectContaining({
entity_kind: "script",
status: "matched",
basis: "content-and-location",
}),
]),
);
});
it("matches renderer, frame, script bytes, and worker without claiming execution", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { buildManagedPeFixture } from "../../../../scripts/lib/managed-pe-fixture.mjs";
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
const workspaces: string[] = [];
+6
View File
@@ -0,0 +1,6 @@
import { createStoreFileLock } from "../../dist/application/StoreFileLock.js";
const path = process.argv[2];
if (path === undefined) throw new Error("A lock path is required");
await createStoreFileLock(path);
// Exit without invoking release so the parent can exercise dead-owner recovery.