Merge branch 'main' into cursor/browser-cancellation-after-cleanup-1ffc

This commit is contained in:
morluto
2026-10-14 03:06:36 +08:00
committed by GitHub
149 changed files with 8310 additions and 563 deletions
@@ -0,0 +1,98 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { applicationVersionComparisonResultSchema } from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"pairs repeated factory bodies by identity when application versions retain a shared bundle",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-version-matching-");
const factoryCount = 32;
const factories = Array.from(
{ length: factoryCount },
(_, index) => `${index}: function() {}`,
).join(",");
const bundle = `globalThis.webpackChunkApp.push([[1], {${factories}}]);`;
const versions = await Promise.all(
[1, 2].map(async (version) => {
const application = join(root, String(version));
await mkdir(application);
await writeFile(
join(application, "package.json"),
JSON.stringify({ name: "shared-bundle", version: `${version}.0.0` }),
);
await writeFile(join(application, "chunk.js"), bundle);
const response = await cli.run({
arguments: ["analyze-javascript-application", application, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
return parseEvidence(response.json);
}),
);
const [left, right] = versions;
if (left === undefined || right === undefined)
throw new Error("Missing application version Evidence");
const analyses = versions.map(({ normalized_result }) =>
javascriptApplicationAnalysisResultSchema.parse(normalized_result),
);
const factoryNodes = analyses.map(({ graph }) => {
expect(graph.coverage.status).toBe("complete");
const nodes = graph.nodes.filter(
({ kind, observations }) =>
kind === "javascript-module" &&
observations.some(
({ properties }) => properties.module_key !== undefined,
),
);
expect(nodes).toHaveLength(factoryCount);
const sourceDigests = nodes.flatMap(({ observations }) =>
observations.map(({ properties }) => properties.source_sha256),
);
expect(sourceDigests.every((digest) => typeof digest === "string")).toBe(
true,
);
expect(new Set(sourceDigests).size).toBe(1);
return nodes;
});
const inputPath = join(root, "comparison.json");
await writeFile(inputPath, JSON.stringify({ left, right }));
const response = await cli.run({
arguments: ["compare-application-versions", inputPath, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
const result = applicationVersionComparisonResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
expect(result.left.root_artifact_sha256).not.toBe(
result.right.root_artifact_sha256,
);
expect(result.matching.ambiguous).toBe(0);
expect(result.coverage.status).toBe("complete-within-inputs");
expect(factoryNodes[0]?.map(({ node_id }) => node_id)).toEqual(
factoryNodes[1]?.map(({ node_id }) => node_id),
);
for (const node of factoryNodes[0] ?? []) {
expect(
result.items.find(({ left_node_id }) => left_node_id === node.node_id),
).toMatchObject({
status: "unchanged",
right_node_id: node.node_id,
match: {
status: "matched",
basis: "exact-node-identity",
candidate_left_node_ids: [],
candidate_right_node_ids: [],
},
});
}
},
);
@@ -0,0 +1,432 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect } from "vitest";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "../../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
const plist = (message: string) =>
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict><key>message</key><string>${message}</string></dict></plist>\n`;
const inventoryEvidence = (input: unknown): Evidence => {
const inspection = parseEvidence(input);
const inventory = artifactInspectionResultSchema
.parse(inspection.normalized_result)
.substeps.find(
({ evidence }) => evidence.operation === "inventory_artifact",
)?.evidence;
if (inventory === undefined) throw new Error("Expected inventory Evidence");
return parseEvidence(inventory);
};
const inspectPair = async (
cli: TestCli,
leftPath: string,
rightPath: string,
) => {
const result = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(result.exitCode, `${result.stderr}\n${result.stdout}`).toBe(0);
const left = inventoryEvidence(result.json);
const { call } = await connectLocalToolsMcp();
const opened = await call("open_binary", { path: rightPath });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const inspected = await call("inspect_artifact", {});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
return { left, right: inventoryEvidence(inspected.structuredContent), call };
};
const assertCoverageControls = async ({
left,
right,
inventory,
compare,
}: {
left: Evidence;
right: Evidence;
inventory: ArtifactInventoryResult;
compare: (left: Evidence, right: Evidence) => Promise<Evidence>;
}) => {
// Authenticated derived controls isolate missing members and genuine coverage
// gaps; they do not claim that the complete plist producer omitted children.
const derive = (result: unknown) =>
createEvidence(
{
path: right.subject?.local_path ?? "",
sha256: inventory.manifest.root_sha256,
format: "plist",
},
right.provider,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(result),
confidence: "derived",
authority: "shipped-artifact",
},
);
const partial = await compare(left, derive({ ...inventory, nodes: [] }));
expect(partial.normalized_result).toMatchObject({
status: "truncated",
summary: { unchanged: 0, unknown: 1 },
});
const reworded = await compare(
left,
derive({
...inventory,
coverage: { scope: "root", status: "complete" },
limitations: ["Root bytes observed; no container children are modeled."],
}),
);
expect(reworded.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
limitations: expect.arrayContaining([
"Right: Root bytes observed; no container children are modeled.",
]),
});
const gap = await compare(
left,
derive({
...inventory,
coverage: { scope: "root", status: "unknown" },
coverage_status: "partial",
limitations: [],
}),
);
expect(gap.normalized_result).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
const differentScope = await compare(
left,
derive({
...inventory,
coverage: { scope: "container-entries", status: "complete" },
}),
);
expect(differentScope.normalized_result).toMatchObject({
status: "unknown",
limitations: expect.arrayContaining(["Artifact inventory scopes differ."]),
});
const { coverage, coverage_status: _coverageStatus, ...legacy } = inventory;
expect(coverage).toBeDefined();
const retained = await compare(left, derive(legacy));
expect(retained.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
});
for (const limitation of [
"Child inventory is unavailable.",
"Missing child observations; 1 integrity contradiction(s) were recorded.",
]) {
const unfamiliarLegacy = await compare(
left,
derive({ ...legacy, limitations: [limitation] }),
);
expect(unfamiliarLegacy.normalized_result).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
}
};
cliTest(
"compares fully observed roots without inventing coverage gaps through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-artifact-coverage-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
await Promise.all([
writeFile(leftPath, plist("hello")),
writeFile(rightPath, plist("hello")),
]);
const leftResult = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(leftResult.exitCode, leftResult.stderr).toBe(0);
const left = inventoryEvidence(leftResult.json);
const { call } = await connectLocalToolsMcp();
const inspect = async (path: string) => {
const opened = await call("open_binary", { path });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const result = await call("inspect_artifact", {});
expect(result.isError, JSON.stringify(result)).not.toBe(true);
return inventoryEvidence(result.structuredContent);
};
const compare = async (left: Evidence, right: Evidence) => {
const result = await call("compare_artifacts", { left, right });
expect(result.isError, JSON.stringify(result)).not.toBe(true);
return parseEvidence(result.structuredContent);
};
const right = await inspect(rightPath);
const inventory = artifactInventoryResultSchema.parse(
right.normalized_result,
);
expect(inventory.coverage).toEqual({ scope: "root", status: "complete" });
expect(inventory.manifest).toMatchObject({
root_format: "plist",
node_count: 1,
occurrence_count: 1,
edge_count: 0,
});
expect(inventory.limitations).toEqual([
"Artifact has no child container entries.",
]);
const equal = await compare(left, right);
expect(equal.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
changes: [],
limitations: [
"Left: Artifact has no child container entries.",
"Right: Artifact has no child container entries.",
],
});
const behavior = await call("find_changed_behavior", {
comparisons: [equal],
});
expect(behavior.isError, JSON.stringify(behavior)).not.toBe(true);
expect(behavior.structuredContent).toMatchObject({
normalized_result: {
behavior_status: "unknown",
summary: { unresolved: 0 },
findings: { items: [] },
limitations: expect.arrayContaining([
"No process comparison Evidence was supplied.",
]),
},
});
const unknowns = await call("list_unknowns", {
domain: "artifact-comparison",
});
expect(unknowns.isError, JSON.stringify(unknowns)).not.toBe(true);
expect(unknowns.structuredContent).toMatchObject({
result: { items: [], total: 0 },
});
await writeFile(rightPath, plist("world"));
const changed = await compare(left, await inspect(rightPath));
expect(changed.normalized_result).toMatchObject({
status: "changed",
summary: { unchanged: 0, changed: 1, unknown: 0 },
changes: [
expect.objectContaining({ logical_path: ".", dimensions: ["content"] }),
],
});
const zipPaths = [join(root, "left.zip"), join(root, "right.zip")] as const;
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("same.txt", new TextReader("same"));
const bytes = await writer.close();
await Promise.all(zipPaths.map((path) => writeFile(path, bytes)));
const zip = await compare(
await inspect(zipPaths[0]),
await inspect(zipPaths[1]),
);
expect(zip.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 2, unknown: 0 },
changes: [],
});
await assertCoverageControls({ left, right, inventory, compare });
},
30_000,
);
cliTest.skipIf(process.platform === "win32")(
"preserves executable metadata changes for fully observed plist roots",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-artifact-mode-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
await Promise.all([
writeFile(leftPath, plist("hello")),
writeFile(rightPath, plist("hello")),
]);
await Promise.all([chmod(leftPath, 0o644), chmod(rightPath, 0o755)]);
const result = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const left = inventoryEvidence(result.json);
const { call } = await connectLocalToolsMcp();
const opened = await call("open_binary", { path: rightPath });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const inspected = await call("inspect_artifact", {});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
const right = inventoryEvidence(inspected.structuredContent);
expect(right.subject?.digest.sha256).toBe(left.subject?.digest.sha256);
const comparison = await call("compare_artifacts", { left, right });
expect(comparison.isError, JSON.stringify(comparison)).not.toBe(true);
expect(
parseEvidence(comparison.structuredContent).normalized_result,
).toMatchObject({
status: "changed",
summary: { unchanged: 0, changed: 1, unknown: 0 },
changes: [
expect.objectContaining({
logical_path: ".",
dimensions: ["executable"],
}),
],
});
},
30_000,
);
cliTest.skipIf(process.platform === "win32")(
"retains traversal uncertainty when a directory omits special filesystem entries",
async ({ cli, processes }) => {
const root = await createTestTempDirectory("rea-gap-");
const leftPath = join(root, "l.app"),
rightPath = join(root, "r.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "same.txt"), "same"),
]);
await Promise.all(
[leftPath, rightPath].flatMap((path) => [
writeFile(
join(path, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>main.js</string></dict></plist>",
),
writeFile(join(path, "main.js"), "export const value = 1;"),
]),
);
const fifo = await processes.run("mkfifo", [join(leftPath, "p")]);
expect(fifo.exitCode, fifo.stderr).toBe(0);
const socket = createServer();
await new Promise<void>((resolve, reject) => {
socket.once("error", reject);
socket.listen(join(leftPath, "s"), resolve);
});
try {
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "unknown",
});
expect(inventory.limitations).toEqual(
expect.arrayContaining([
'Artifact traversal omitted fifo at "p".',
'Artifact traversal omitted socket at "s".',
]),
);
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(
parseEvidence(compared.structuredContent).normalized_result,
).toMatchObject({ status: "unknown", summary: { unchanged: 0 } });
} finally {
await new Promise<void>((resolve, reject) =>
socket.close((cause) =>
cause === undefined ? resolve() : reject(cause),
),
);
}
},
30_000,
);
cliTest(
"compares fully traversed case-distinct ZIP entries while retaining materialization limits",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-case-coverage-");
const leftPath = join(root, "left.zip"),
rightPath = join(root, "right.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("A", new TextReader("upper"));
await writer.add("a", new TextReader("lower"));
const bytes = await writer.close();
await Promise.all([
writeFile(leftPath, bytes),
writeFile(rightPath, bytes),
]);
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "complete",
});
expect(
inventory.occurrences.map(({ logical_path }) => logical_path).sort(),
).toEqual([".", "A", "a"]);
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(
parseEvidence(compared.structuredContent).normalized_result,
).toMatchObject({
status: "unchanged",
summary: { unchanged: 3, unknown: 0 },
changes: [],
limitations: expect.arrayContaining([
expect.stringContaining("case-insensitive destination"),
]),
});
},
30_000,
);
cliTest(
"keeps unreadable encrypted ZIP content unknown with complete traversal",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-encrypted-comparison-");
const leftPath = join(root, "left.zip");
const rightPath = join(root, "right.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("secret.txt", new TextReader("secret bytes"), {
password: "fixture-password",
});
const bytes = await writer.close();
await Promise.all([
writeFile(leftPath, bytes),
writeFile(rightPath, bytes),
]);
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
for (const evidence of [left, right])
expect(
artifactInventoryResultSchema.parse(evidence.normalized_result),
).toMatchObject({
coverage: { scope: "container-entries", status: "complete" },
occurrences: expect.arrayContaining([
expect.objectContaining({
logical_path: "secret.txt",
hash_status: "unavailable",
encrypted: true,
}),
]),
});
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
const result = parseEvidence(compared.structuredContent).normalized_result;
expect(result).toMatchObject({
status: "unknown",
summary: { unknown: expect.any(Number) },
});
expect(result).toHaveProperty("summary.unknown", 1);
},
);
+71
View File
@@ -0,0 +1,71 @@
import { deflateSync } from "node:zlib";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { createRustImage } from "../fixtures/rust/image.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"reports cargo-auditable packages through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-");
const path = join(root, "sample");
await writeFile(path, createRustImage({ format: "macho" }));
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.auditable_metadata).toMatchObject({
section_name: "__DATA,.dep-v0",
format_version: 1,
root_package_index: 1,
packages: [
{ name: "itoa", version: "1.0.18" },
{ name: "sample", version: "0.1.0", root: true },
],
});
},
);
cliTest("returns null metadata when .dep-v0 is absent", async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-missing-");
const path = join(root, "plain");
await writeFile(path, createRustImage({ format: "elf", omitSection: true }));
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.auditable_metadata).toBeNull();
expect(evidence.normalized_result.limitations.join("\n")).toContain(
"does not mean the binary has no dependencies",
);
});
cliTest("reports malformed zlib as invalid input", async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-zlib-");
const path = join(root, "broken.elf");
await writeFile(
path,
createRustImage({
format: "elf",
payload: deflateSync(Buffer.from("{")),
includeRustc: false,
}),
);
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_rust_binary" },
});
});
@@ -0,0 +1,355 @@
import { expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import type { WebPageInspection } from "../../../src/domain/browserObservationSchemas.js";
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";
import {
startFakeCdpBrowser,
type FakeOptions,
} from "../../fixtures/fakeCdpBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const inspect = async (options: FakeOptions, includeFingerprints = true) => {
const browser = await startFakeCdpBrowser(options);
trackBrowser(browser);
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_storage_keys: true,
include_storage_fingerprints: includeFingerprints,
});
const capture = async () => {
const result = await new CdpBrowserProvider().inspectPage(input);
if (!result.ok) throw result.error;
return result.value;
};
return { capture };
};
const compareStorage = (before: WebPageInspection, after: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: before },
after: { inspection: after },
}),
).dimensions.storage;
it.each([
["CacheStorage.requestCacheNames", {}],
["CacheStorage.requestCacheNames", { caches: null }],
["CacheStorage.requestCacheNames", { caches: [null] }],
[
"CacheStorage.requestCacheNames",
{ caches: [{ cacheName: "assets-v1", cacheId: "secret-id" }, null] },
],
["CacheStorage.requestCacheNames", { caches: [{ cacheName: "assets-v1" }] }],
["IndexedDB.requestDatabaseNames", { databaseNames: [null] }],
["DOMStorage.getDOMStorageItems", { entries: [null] }],
] as const)(
"preserves unknown inventory coverage from %s: %j",
async (method, reply) => {
let malformed = false;
const { capture } = await inspect({
commandResult: (command) =>
malformed && command.method === method ? reply : undefined,
});
const before = await capture();
malformed = true;
const after = await capture();
expect(after.storage.fingerprints_complete).toBe(false);
expect(after.completeness.unavailable_sections).toContain("storage_keys");
expect(after.completeness.excluded).toContainEqual({
section: "storage_keys",
reason: "invalid_protocol_value",
count: null,
});
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
},
);
it("preserves unavailable storage-key coverage without requesting fingerprints", async () => {
const { capture } = await inspect(
{ unsupportedMethods: ["CacheStorage.requestCacheNames"] },
false,
);
const captured = await capture();
expect(captured.completeness.excluded).toContainEqual({
section: "storage_keys",
reason: "provider_unavailable",
count: null,
});
expect(captured.storage.local_storage_keys).toEqual(["public-key"]);
});
const validKey = { type: "string", value: "row-1" };
it.each(["unavailable", "malformed"] as const)(
"compares shared complete values with %s cache inventory",
async (inventory) => {
let entries: unknown[][] = [["shared-key", "before"]];
const { capture } = await inspect({
...(inventory === "unavailable"
? { unsupportedMethods: ["CacheStorage.requestCacheNames"] }
: {}),
commandResult: (command) => {
if (command.method === "CacheStorage.requestCacheNames")
return { caches: [null] };
if (command.method === "DOMStorage.getDOMStorageItems")
return { entries };
return undefined;
},
});
const before = await capture();
expect(before.completeness.unavailable_sections).toContain("storage_keys");
expect(before.storage.fingerprints_complete).toBe(false);
expect(compareStorage(before, await capture())).toMatchObject({
status: "unknown",
total_changes: 0,
});
entries = [["shared-key", "after"]];
const changed = await capture();
expect(changed.storage.usage_bytes).toBe(before.storage.usage_bytes);
expect(changed.storage.quota_bytes).toBe(before.storage.quota_bytes);
for (const [left, right] of [
[before, changed],
[changed, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 2,
changes: [
expect.objectContaining({ change: "modified" }),
expect.objectContaining({ change: "modified" }),
],
});
const incompleteValues = structuredClone(changed);
for (const fingerprint of incompleteValues.storage.content_fingerprints)
if (["local_storage", "session_storage"].includes(fingerprint.scope))
fingerprint.complete = false;
expect(compareStorage(before, incompleteValues)).toMatchObject({
status: "unknown",
total_changes: 0,
});
// Missing or invalid peer values establish neither removal nor addition.
for (const partial of [[], [["shared-key", null]]]) {
entries = partial;
const incomplete = await capture();
for (const [left, right] of [
[before, incomplete],
[incomplete, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
}
},
);
it.each(["key", "primaryKey"])(
"requires IndexedDB %s identity evidence",
async (field) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestData"
? {
objectStoreDataEntries: [
{
key: validKey,
primaryKey: validKey,
value: validKey,
[field]: {},
},
],
hasMore: false,
}
: undefined,
});
const captured = await capture();
expect(captured.storage.fingerprints_complete).toBe(false);
expect(
captured.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_record",
)?.complete,
).toBe(false);
},
);
it("does not fingerprint a filtered partial object-store schema as complete", async () => {
let malformed = false;
const store = {
name: "records",
keyPath: { type: "string", string: "id" },
autoIncrement: false,
indexes: [],
};
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestDatabase"
? {
databaseWithObjectStores: {
name: "app-db",
version: 1,
objectStores: [
store,
malformed ? null : { ...store, name: "other" },
],
},
}
: undefined,
});
const before = await capture();
malformed = true;
const after = await capture();
expect(
after.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_schema",
)?.complete,
).toBe(false);
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
const incompleteRemoteObjects = [
undefined,
null,
"raw",
{},
{ type: "string" },
{ type: "string", value: 1 },
{ type: "boolean", value: "false" },
{ type: "number" },
{ type: "number", unserializableValue: "invalid" },
{ type: "number", unserializableValue: ["NaN"] },
{ type: "function", description: "function f() {}" },
{ type: "symbol", description: "Symbol(x)" },
{ type: "object", subtype: "null" },
{ type: "bigint", unserializableValue: "broken" },
] as const;
const completeRemoteObjects = [
{ type: "string", value: "" },
{ type: "boolean", value: false },
{ type: "number", value: 0 },
{ type: "undefined" },
{ type: "number", unserializableValue: "NaN" },
{ type: "number", unserializableValue: "-0" },
{ type: "bigint", unserializableValue: "-42n" },
{ type: "object", subtype: "null", value: null },
{ type: "object", value: { nested: [false, null, 0] } },
] as const;
it.each([
...incompleteRemoteObjects.map((value) => [value, false] as const),
...completeRemoteObjects.map((value) => [value, true] as const),
])(
"validates IndexedDB RemoteObject completeness: %j => %s",
async (value, complete) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestData"
? {
objectStoreDataEntries: [
{ key: validKey, primaryKey: validKey, value },
],
hasMore: false,
}
: undefined,
});
const before = await capture();
const after = await capture();
const records = before.storage.content_fingerprints.filter(
({ scope }) => scope === "indexed_db_record",
);
expect(records).toHaveLength(1);
expect(records[0]?.complete).toBe(complete);
expect(before.storage.fingerprints_complete).toBe(complete);
expect(compareStorage(before, after)).toMatchObject({
status: complete ? "unchanged" : "unknown",
total_changes: 0,
});
},
);
it.each([
[undefined, false],
[{}, false],
[{ type: "string" }, false],
[{ type: "array", array: [null] }, false],
[{ type: "null" }, true],
[{ type: "string", string: "id" }, true],
[{ type: "array", array: ["id", "name"] }, true],
] as const)(
"requires complete IndexedDB key paths: %j",
async (keyPath, complete) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestDatabase"
? {
databaseWithObjectStores: {
name: "app-db",
version: 1,
objectStores: [
{
name: "records",
keyPath,
autoIncrement: false,
indexes: [
{
name: "by-id",
keyPath,
unique: false,
multiEntry: false,
},
],
},
],
},
}
: undefined,
});
const captured = await capture();
expect(
captured.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_schema",
)?.complete,
).toBe(complete);
expect(captured.storage.fingerprints_complete).toBe(complete);
},
);
it("accepts genuinely empty inventories as complete", async () => {
const { capture } = await inspect({
commandResult: (command) => {
switch (command.method) {
case "CacheStorage.requestCacheNames":
return { caches: [] };
case "IndexedDB.requestDatabaseNames":
return { databaseNames: [] };
case "DOMStorage.getDOMStorageItems":
return { entries: [] };
case "Network.getCookies":
return { cookies: [] };
default:
return undefined;
}
},
});
const before = await capture();
const after = await capture();
expect(before.storage.fingerprints_complete).toBe(true);
expect(compareStorage(before, after).status).toBe("unchanged");
});
@@ -14,6 +14,185 @@ import {
} from "../../fixtures/fakeCdpBrowser.js";
const browsers: FakeCdpBrowser[] = [];
const inspectStorage = async (
browser: FakeCdpBrowser,
fingerprints = false,
) => {
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_storage_keys: true,
include_storage_fingerprints: fingerprints,
}),
);
if (!captured.ok) throw captured.error;
return captured.value;
};
const compareStorage = (left: WebPageInspection, right: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: left },
after: { inspection: right },
}),
).dimensions.storage;
it.each([
["local", "DOMStorage.getDOMStorageItems", { entries: [null] }],
[
"session",
"DOMStorage.getDOMStorageItems",
{ entries: [["known", "value"], null] },
],
["indexed", "IndexedDB.requestDatabaseNames", { databaseNames: [null] }],
["cache", "CacheStorage.requestCacheNames", { caches: [null] }],
] as const)(
"does not invent membership changes after an incomplete %s inventory",
async (kind, method, malformed) => {
let failure: "unsupported" | "malformed" | undefined;
const matches = (command: {
method: string;
params: Record<string, unknown>;
}) => {
if (command.method !== method) return false;
if (kind !== "local" && kind !== "session") return true;
return (
(command.params.storageId as { isLocalStorage: boolean })
.isLocalStorage ===
(kind === "local")
);
};
const browser = await startFakeCdpBrowser({
commandError: (command) =>
failure === "unsupported" && matches(command)
? { code: -32601, message: "Method not found" }
: undefined,
commandResult: (command) =>
failure === "malformed" && matches(command) ? malformed : undefined,
});
browsers.push(browser);
const before = await inspectStorage(browser);
expect(before.completeness.unavailable_sections).not.toContain(
"storage_keys",
);
for (const [mode, reason] of [
["unsupported", "provider_unavailable"],
["malformed", "invalid_protocol_value"],
] as const) {
failure = mode;
const after = await inspectStorage(browser);
expect(after.completeness.excluded).toContainEqual({
section: "storage_keys",
reason,
count: null,
});
expect(after.completeness.unavailable_sections).toContain("storage_keys");
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
if (kind === "session" && mode === "malformed")
expect(after.storage.session_storage_keys).toEqual(["known"]);
}
},
);
it("preserves shared content changes when a peer inventory is unavailable", async () => {
let value = "before";
const browser = await startFakeCdpBrowser({
unsupportedMethods: ["CacheStorage.requestCacheNames"],
commandResult: (command) =>
command.method === "DOMStorage.getDOMStorageItems"
? { entries: [["shared-key", value]] }
: undefined,
});
browsers.push(browser);
const before = await inspectStorage(browser, true);
expect(before.completeness.unavailable_sections).toContain("storage_keys");
expect(compareStorage(before, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
value = "after";
const after = await inspectStorage(browser, true);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 2,
changes: [
expect.objectContaining({ change: "modified" }),
expect.objectContaining({ change: "modified" }),
],
});
for (const fingerprint of after.storage.content_fingerprints)
if (["local_storage", "session_storage"].includes(fingerprint.scope))
fingerprint.complete = false;
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("reports complete storage key additions and removals without content fingerprints", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const before = await inspectStorage(browser);
expect(before.storage.fingerprints_complete).toBe(false);
const after = structuredClone(before);
after.storage.local_storage_keys.push("new-local");
after.storage.session_storage_keys.push("new-session");
after.storage.indexed_db_names.push("new-db");
after.storage.cache_names.push("new-cache");
const identities = [
"storage:cache:new-cache",
"storage:indexed_db:new-db",
"storage:local_storage:new-local",
"storage:session_storage:new-session",
];
for (const [left, right, change] of [
[before, after, "added"],
[after, before, "removed"],
] as const) {
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 4,
changes: identities.map((identity) => ({ identity, change })),
});
}
expect(compareStorage(after, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
const missingQuota = structuredClone(after);
missingQuota.storage.quota_bytes = null;
expect(compareStorage(before, missingQuota)).toMatchObject({
status: "changed",
total_changes: 4,
});
const partialInventory = structuredClone(after);
partialInventory.completeness.unavailable_sections.push("storage_keys");
expect(compareStorage(before, partialInventory)).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(compareStorage(partialInventory, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
const expectInvalidDiff = (input: unknown): void => {
expect(webCaptureDiffSchema.safeParse(input).success).toBe(false);
};
@@ -228,7 +228,7 @@ describe("case-distinct APK resource names", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
@@ -238,11 +238,11 @@ describe("case-distinct APK resource names", () => {
);
expect(projection.root_format).toBe("apk");
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
@@ -75,7 +75,7 @@ async function createCompleteAppleProjection() {
}
describe("Apple application projection", () => {
it("keeps a case-colliding real IPA inventory partial", async () => {
it("retains complete traversal and case-collision limits for a real IPA", async () => {
const root = await createTestTempDirectory("rea-apple-case-collision-");
const path = join(root, "CaseCollision.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
@@ -93,7 +93,7 @@ describe("Apple application projection", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
@@ -103,11 +103,11 @@ describe("Apple application projection", () => {
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
@@ -77,7 +77,11 @@ describe("leaf artifact comparison", () => {
// Persisted inventory Evidence predates coverage_status. The known leaf
// notice remains complete when normalized at the inventory boundary.
const parsed = artifactInventoryResultSchema.parse(left.normalized_result);
const { coverage_status: _coverageStatus, ...legacyInventory } = parsed;
const {
coverage: _coverage,
coverage_status: _coverageStatus,
...legacyInventory
} = parsed;
const legacy = createEvidence(
{
path: left.subject!.local_path,
@@ -157,7 +161,7 @@ describe("artifact inventory coverage", () => {
const graph = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
const partial = createEvidence(
const contradictory = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
@@ -168,6 +172,29 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({ ...graph, coverage_status: "partial" }),
confidence: "derived",
authority: "shipped-artifact",
},
);
expect(() => parseArtifactInventoryEvidence(contradictory)).toThrow(
"Artifact inventory has conflicting coverage declarations",
);
const { coverage: _coverage, ...legacyStatusGraph } = graph;
const partial = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
format: complete.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyStatusGraph,
coverage_status: "partial",
}),
confidence: "observed",
authority: "shipped-artifact",
},
@@ -180,7 +207,8 @@ describe("artifact inventory coverage", () => {
summary: { unchanged: 0, unknown: 1 },
});
const { coverage_status: _coverageStatus, ...legacyGraph } = graph;
const { coverage_status: _coverageStatus, ...legacyGraph } =
legacyStatusGraph;
const unknownLegacy = createEvidence(
{
path: complete.subject!.local_path,
@@ -219,6 +247,7 @@ describe("artifact inventory coverage", () => {
const fragmentGraph = artifactInventoryResultSchema.parse(
fragment.normalized_result,
);
const { coverage: _coverage, ...legacyFragmentGraph } = fragmentGraph;
const mixed = createEvidence(
{
path: fragment.subject!.local_path,
@@ -230,7 +259,7 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: fragment.parameters,
result: jsonValueSchema.parse({
...fragmentGraph,
...legacyFragmentGraph,
coverage_status: "partial",
}),
confidence: "derived",
@@ -239,7 +268,7 @@ describe("artifact inventory coverage", () => {
);
expect(() =>
parseArtifactInventoryEvidence([firstFragment, mixed]),
).toThrow("Artifact inventory pages disagree on coverage status");
).toThrow("Artifact inventory pages do not share one coverage declaration");
});
});
@@ -314,6 +343,61 @@ describe("artifact comparison", () => {
});
describe("artifact comparison completeness", () => {
it("does not infer child changes from root-only coverage", async () => {
const root = await createTestTempDirectory("rea-artifact-root-coverage-");
const leftPath = join(root, "left.app");
const rightPath = join(root, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "left-only.txt"), "left"),
writeFile(join(rightPath, "right-only.txt"), "right"),
]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
const rootOnly = (evidence: Awaited<ReturnType<typeof observe>>) => {
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
return createEvidence(
{
path: evidence.subject?.local_path ?? "",
sha256: inventory.manifest.root_sha256,
format: inventory.manifest.root_format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...inventory,
coverage: { scope: "root", status: "complete" },
}),
confidence: "derived",
authority: "shipped-artifact",
},
);
};
const compared = compareArtifacts(rootOnly(left), rootOnly(right));
expect(compared.status).toBe("unknown");
expect(compared.summary).toMatchObject({ added: 0, removed: 0 });
expect(
compared.changes
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path, classification }) => ({
logical_path,
classification,
})),
).toEqual([
{ logical_path: "left-only.txt", classification: "unknown" },
{ logical_path: "right-only.txt", classification: "unknown" },
]);
expect(compared.limitations).toContain(
"Container entry coverage is unavailable for child paths.",
);
});
it("compares every graph member for inventories larger than 500 entries", async () => {
const root = await createTestTempDirectory("rea-artifact-pages-");
const entryCount = 501;
@@ -415,6 +499,30 @@ describe("artifact comparison completeness", () => {
evidence_links: citations,
})),
});
const fragment = leftFragments[0];
if (fragment === undefined) throw new Error("Expected inventory fragments");
const conflictingScope = createEvidence(
{
path: leftPath,
sha256: left.subject?.digest.sha256 ?? "",
format: "directory",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...artifactInventoryResultSchema.parse(fragment.normalized_result),
coverage: { scope: "root", status: "complete" },
}),
},
);
expect(() =>
compareArtifacts(
[conflictingScope, ...leftFragments.slice(1)],
rightFragments,
),
).toThrow(/coverage declaration/u);
}, 15_000);
it("rejects non-inventory and tampered Evidence", async () => {
@@ -52,3 +52,22 @@ it("rejects a root path replaced between its initial stat and open", async () =>
message: `Root artifact changed before inventory: ${path}`,
});
});
it("keeps unavailable container traversal distinct from observed root bytes", async () => {
const root = await createTestTempDirectory("rea-artifact-root-scope-");
const path = join(root, "fixture.pkg");
// The recognized XAR prefix selects PKG inventory; no child decoder is installed.
await writeFile(path, Buffer.from("xar!fixture"));
const inventory = await inventoryArtifact(path);
expect(inventory.manifest).toMatchObject({
root_format: "pkg",
node_count: 1,
occurrence_count: 1,
edge_count: 0,
});
expect(inventory.occurrences[0]?.hash_status).toBe("verified");
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "unknown",
});
});
@@ -26,6 +26,7 @@ import {
thinMach,
} from "../../../src/domain/binaryTarget.fixture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { parseExecutableHeader } from "../../../src/domain/binaryTarget.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -424,6 +425,65 @@ describe("binary target I/O: explicit kinds and executable headers", () => {
});
});
it("extracts CodeView RSDS debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "symbols.exe");
await writeFile(
path,
pe(0x8664, 64, 0x0002, false, {
type: "RSDS",
pdbPath: "C:\\build\\test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86_64",
codeView: {
pdbPath: "C:\\build\\test.pdb",
pdbFileName: "test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
},
});
});
it("extracts CodeView NB10 debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "legacy.exe");
await writeFile(
path,
pe(0x014c, 64, 0x0002, false, {
type: "NB10",
pdbPath: "D:\\old\\legacy.pdb",
age: 1,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "ia32",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86",
codeView: {
pdbPath: "D:\\old\\legacy.pdb",
pdbFileName: "legacy.pdb",
guid: null,
age: 1,
},
});
});
it("refuses a truncated Mach-O header before any provider sees it", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "truncated");
@@ -884,3 +944,43 @@ it.each([
});
},
);
describe("binary target I/O: PE CodeView header ranges", () => {
it.each(["RSDS", "NB10"] as const)(
"reads bounded %s header debug records and rejects unfinished names",
async (type) => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "header-symbols.exe");
const bytes = pe(0x8664, 64, 0x0002, false, {
type,
pdbPath: "header.pdb",
});
const optionalHeader = 64 + 24;
bytes.writeUInt32LE(512, optionalHeader + 60);
bytes.copy(bytes, 384, 512);
bytes.writeUInt32LE(384, optionalHeader + 112 + 6 * 8);
bytes.writeUInt32LE(412, 384 + 20);
bytes.writeUInt32LE(0, 384 + 24);
for (const complete of [true, false]) {
if (!complete) {
const dataSize = bytes.readUInt32LE(384 + 16);
bytes[412 + dataSize - 1] = 0x61;
}
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path, {
hostArchitecture: "x64",
});
const buffered = parseExecutableHeader(bytes, "x64");
if (!resolved.ok) throw resolved.error;
if (!buffered.ok) throw new Error(buffered.error);
for (const value of [resolved.value, buffered.value]) {
if (complete)
expect(value).toMatchObject({
codeView: { pdbPath: "header.pdb" },
});
else expect(value).not.toHaveProperty("codeView");
}
}
},
);
});
@@ -214,7 +214,7 @@ describe("HarmonyOS packaging boundaries", () => {
});
describe("HarmonyOS inventory coverage", () => {
it("keeps a case-colliding inventory partial in the application projection", async () => {
it("retains complete traversal and case-collision limits in the application projection", async () => {
const path = await writeApplicationZip(
"rea-harmony-case-collision-",
"Fixture.hap",
@@ -225,7 +225,7 @@ describe("HarmonyOS inventory coverage", () => {
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const projection = requireDeterministicProjection(
@@ -234,11 +234,11 @@ describe("HarmonyOS inventory coverage", () => {
harmonyApplicationProjectionResultSchema,
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
+21
View File
@@ -6,6 +6,7 @@ import {
machoImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { readGoBinaryImage } from "../../../src/go/GoBinaryImage.js";
import { readGoMachoImage } from "../../../src/go/GoMachoImage.js";
import {
createGoBinaryFixture,
GO_MODULE_TEXT,
@@ -519,6 +520,26 @@ it("rejects build-info declared inside an unmapped Mach-O segment", () => {
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/unmapped/i);
});
it("does not mark Mach-O section bytes outside their owning segment as read-only", () => {
const fixture = createGoBinaryFixture({ format: "macho" });
const command = 32;
const section = command + 72;
fixture.bytes.write("__TEXT", command + 8, "ascii");
fixture.bytes.writeBigUInt64LE(1024n, command + 48);
fixture.bytes.writeUInt32LE(1, command + 56);
fixture.bytes.writeUInt32LE(1, command + 60);
fixture.bytes.write("__debug_info", section, "ascii");
fixture.bytes.write("__TEXT", section + 16, "ascii");
fixture.bytes.writeBigUInt64LE(0x10c00n, section + 32);
fixture.bytes.writeBigUInt64LE(128n, section + 40);
fixture.bytes.writeUInt32LE(3072, section + 48);
const image = readGoMachoImage(fixture.bytes);
expect(image.sections[0]).toMatchObject({
file_backed: false,
read_only: false,
});
});
it.each(["elf", "pe", "macho"] as const)(
"refuses file aliases overlapping only part of a zero-filled %s module header",
(format) => {
@@ -254,8 +254,11 @@ const assertHistoricalInventory = async (
const { archive, parent, inventoryEvidence, graph } = input;
// Historical records may omit a later inventory field. Input parsing must
// not insert defaults inside that authenticated child Evidence.
const { integrity_contradictions: _contradictions, ...legacyInventory } =
graph;
const {
integrity_contradictions: _contradictions,
coverage: _coverage,
...legacyInventory
} = graph;
const legacyTarget = {
path: archive,
sha256: graph.manifest.root_sha256,
@@ -275,6 +278,9 @@ const assertHistoricalInventory = async (
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("integrity_contradictions");
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("coverage");
const legacyParent = createEvidence(legacyTarget, parent.provider, {
operation: "inspect_artifact",
parameters: {},
+27 -15
View File
@@ -1,5 +1,7 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -98,20 +100,6 @@ it.each([
20_000,
);
const artifactInventoryResultSchema = z.object({
occurrences: z.array(
z.object({ logical_path: z.string(), hash_status: z.string() }),
),
integrity_contradictions: z.array(
z.object({
logical_path: z.string(),
declared_sha256: z.string(),
observed_sha256: z.string(),
trust: z.literal("observed-untrusted"),
}),
),
});
it("extracts an active archive through MCP when requested", async () => {
const root = await createTestTempDirectory("rea-artifact-extract-mcp-");
const archive = join(root, "fixture.zip");
@@ -318,6 +306,30 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
}),
]),
});
const { coverage: _coverage, ...legacyInventory } = inventory;
const historical = createEvidence(
{ path: archive, sha256: inventory.manifest.root_sha256, format: "asar" },
compact.provider,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(legacyInventory),
},
);
const retainedComparison = await client.callTool({
name: "compare_artifacts",
arguments: { left: evidence, right: historical },
});
expect(
retainedComparison.isError,
JSON.stringify(retainedComparison),
).not.toBe(true);
expect(
toolEvidence(retainedComparison.structuredContent).normalized_result,
).toMatchObject({
status: "contradiction",
summary: { unchanged: 2, contradiction: 2, unknown: 0 },
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
@@ -0,0 +1,643 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type {
Device,
DeviceManager,
FridaMessage,
Script,
Session,
} from "frida";
import { expect, it, onTestFinished } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const gate = () => {
let markEntered = () => {};
let release = () => {};
const entered = new Promise<void>((resolve) => {
markEntered = resolve;
});
const released = new Promise<void>((resolve) => {
release = resolve;
});
return {
entered,
release,
async wait() {
markEntered();
await released;
},
};
};
const nativeFixture = () => {
const created: string[] = [];
const loaded: string[] = [];
const unloaded: string[] = [];
const scripts: Script[] = [];
const scriptsAtResume: string[][] = [];
const controls = {
attach: async () => {},
create: async () => {},
load: async () => {},
afterLoad: () => {},
discover: async () => {},
unloadFailures: 0,
detachFailures: 0,
detachCalls: 0,
resumes: 0,
remoteRemovals: 0,
removalFailures: 0,
};
let detached = false;
const nativeSession: Session = {
pid: 512,
detached: { connect() {}, disconnect() {} },
isDetached: () => detached,
async detach() {
controls.detachCalls += 1;
if (controls.detachFailures > 0) {
controls.detachFailures -= 1;
throw new Error("transient detach failure");
}
detached = true;
},
async createScript(source) {
created.push(source);
await controls.create();
let destroyed = false;
let listener:
| ((message: FridaMessage, data: Buffer | null) => void)
| undefined;
const script: Script = {
get isDestroyed() {
return destroyed;
},
message: {
connect(handler) {
listener = handler;
},
disconnect() {
listener = undefined;
},
},
async load() {
await controls.load();
loaded.push(source);
listener?.({ type: "send", payload: source }, null);
controls.afterLoad();
},
async unload() {
unloaded.push(source);
if (controls.unloadFailures > 0) {
controls.unloadFailures -= 1;
throw new Error("transient unload failure");
}
destroyed = true;
},
};
scripts.push(script);
return script;
},
};
const device: Device = {
id: "local",
name: "Local fixture",
type: "local",
async enumerateProcesses() {
await controls.discover();
return [{ pid: 512, name: "fixture" }];
},
async getProcessByPid() {
return { pid: 512, name: "fixture" };
},
async spawn() {
return 512;
},
async resume() {
scriptsAtResume.push(
created.filter((_, index) => scripts[index]?.isDestroyed === false),
);
controls.resumes += 1;
},
async attach() {
await controls.attach();
return nativeSession;
},
};
const deviceManager: DeviceManager = {
async enumerateDevices() {
return [device];
},
async getDeviceById() {
return device;
},
async addRemoteDevice() {
return device;
},
async removeRemoteDevice() {
controls.remoteRemovals += 1;
if (controls.removalFailures > 0) {
controls.removalFailures -= 1;
throw new Error("transient remote removal failure");
}
},
};
return {
controls,
created,
loaded,
unloaded,
scripts,
scriptsAtResume,
deviceManager,
};
};
const connectedFixture = async () => {
const native = nativeFixture();
const manager = new FridaInstrumentationManager({
deviceManager: native.deviceManager,
});
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: manager },
);
const client = new Client({ name: "frida-lifecycle", version: "1" });
onTestFinished(async () => {
native.controls.detachFailures = 0;
native.controls.removalFailures = 0;
await client.close();
await server.close();
await manager.closeAll();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const start = async () => {
const result = await client.callTool({
name: "start_frida_session",
arguments: {
mode: "spawn",
program: "/fixture",
device_id: "local",
},
});
return toolContract("start_frida_session").outputSchema.parse(
result.structuredContent,
).session_id;
};
const load = (sessionId: string, source: string, signal?: AbortSignal) =>
client.callTool(
{
name: "load_frida_script",
arguments: { session_id: sessionId, source_kind: "inline", source },
},
signal === undefined ? undefined : { signal },
);
return { ...native, manager, session, server, client, start, load };
};
const scriptLoadFixture = async (stage: "create" | "load" = "load") => {
const fixture = await connectedFixture();
const id = await fixture.start();
const original = await fixture.load(id, "original");
const held = gate();
onTestFinished(held.release);
fixture.controls[stage] = held.wait;
return { fixture, id, original, held };
};
const pendingShutdown = async (server: { close(): Promise<void> }) => {
let closed = false;
const closing = server
.close()
.then(
() => undefined,
(cause: unknown) => cause,
)
.finally(() => {
closed = true;
});
await setImmediate();
expect(closed).toBe(false);
return { closing };
};
const retryCancelledScriptUnload = async (
fixture: Awaited<ReturnType<typeof connectedFixture>>,
sessionId: string,
scriptId = fixture.manager.status(sessionId)?.scripts[1]?.scriptId,
) => {
if (scriptId === undefined)
throw new Error("Cancelled script was not retained");
const retry = await fixture.client.callTool({
name: "unload_frida_script",
arguments: {
session_id: sessionId,
script_id: scriptId,
},
});
expect(retry.isError).not.toBe(true);
};
const retainedScriptObservation = async (
fixture: Awaited<ReturnType<typeof connectedFixture>>,
sessionId: string,
source: string,
) => {
const response = await fixture.client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const bundle = evidenceBundleSchema.parse(
toolContract("get_evidence_bundle").outputSchema.parse(
response.structuredContent,
).result,
);
const sourceSha256 = createHash("sha256").update(source).digest("hex");
const records = bundle.records.filter((record) => {
const result = record.normalized_result;
return (
record.operation === "load_frida_script" &&
result !== null &&
typeof result === "object" &&
!Array.isArray(result) &&
result.source_sha256 === sourceSha256
);
});
expect(records).toHaveLength(1);
expect(records[0]?.parameters).toEqual({ session_id: sessionId });
const observation = records[0]?.normalized_result;
if (
observation === undefined ||
observation === null ||
typeof observation !== "object" ||
Array.isArray(observation)
)
throw new Error("Missing retained script observation");
expect(observation).toMatchObject({
script_id: expect.any(String),
source_kind: "inline",
source_path: null,
source_sha256: sourceSha256,
messages_truncated: false,
});
return observation;
};
it.each(["load", "resume", "unload"] as const)(
"finishes an earlier MCP %s request before closing its Frida session",
async (operation) => {
const fixture = await connectedFixture();
const id = await fixture.start();
const original = await fixture.load(id, "original");
const scriptId = toolContract("load_frida_script").outputSchema.parse(
original.structuredContent,
).normalized_result.script_id;
const pending = fixture.client.callTool({
name: {
load: "load_frida_script",
resume: "resume_frida_session",
unload: "unload_frida_script",
}[operation],
arguments: {
session_id: id,
...(operation === "load"
? { source_kind: "inline", source: "last-script" }
: {}),
...(operation === "unload" ? { script_id: scriptId } : {}),
},
});
const closing = fixture.client.callTool({
name: "close_frida_session",
arguments: { session_id: id },
});
expect((await pending).isError).not.toBe(true);
expect((await closing).isError).not.toBe(true);
expect(fixture.loaded).toEqual(
operation === "load" ? ["original", "last-script"] : ["original"],
);
expect(fixture.unloaded).toEqual(fixture.loaded);
expect(fixture.controls.detachCalls).toBe(1);
expect(fixture.controls.resumes).toBe(1);
expect(fixture.manager.status(id)).toBeUndefined();
},
);
it.each(["load", "resume", "unload"] as const)(
"does not dispatch a cancelled queued Frida %s through MCP",
async (operation) => {
const { fixture, id, original, held } = await scriptLoadFixture();
const scriptId = toolContract("load_frida_script").outputSchema.parse(
original.structuredContent,
).normalized_result.script_id;
const first = fixture.load(id, "blocking");
await held.entered;
const controller = new AbortController();
const cancelled =
operation === "load"
? fixture.load(id, "cancelled", controller.signal)
: fixture.client.callTool(
{
name:
operation === "resume"
? "resume_frida_session"
: "unload_frida_script",
arguments: {
session_id: id,
...(operation === "unload" ? { script_id: scriptId } : {}),
},
},
{ signal: controller.signal },
);
const rejected = expect(cancelled).rejects.toThrow(
"cancel queued operation",
);
await fixture.client.ping();
controller.abort(new Error("cancel queued operation"));
await fixture.client.ping();
await rejected;
held.release();
await first;
await fixture.load(id, "barrier");
expect(fixture.created).toEqual(["original", "blocking", "barrier"]);
expect(fixture.unloaded).toEqual([]);
expect(fixture.controls.resumes).toBe(0);
expect(fixture.manager.status(id)?.scripts).toHaveLength(3);
},
);
it.each(["create", "load"] as const)(
"releases only the new script when MCP cancellation arrives during native %s",
async (stage) => {
const { fixture, id, held } = await scriptLoadFixture(stage);
const controller = new AbortController();
const cancelled = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(cancelled).rejects.toThrow(
"cancel native operation",
);
await held.entered;
controller.abort(new Error("cancel native operation"));
await fixture.client.ping();
await rejected;
held.release();
await fixture.load(id, "barrier");
await fixture.client.ping();
expect(fixture.unloaded).toEqual(["cancelled-native"]);
expect(fixture.loaded).toEqual(
stage === "create"
? ["original", "barrier"]
: ["original", "cancelled-native", "barrier"],
);
expect(fixture.controls.detachCalls).toBe(0);
expect(fixture.controls.resumes).toBe(0);
expect(fixture.manager.status(id)?.scripts).toHaveLength(2);
const observation = await retainedScriptObservation(
fixture,
id,
"cancelled-native",
);
expect(observation).toMatchObject({
messages:
stage === "create"
? []
: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup: "released",
cleanup_error: null,
});
},
);
it("awaits an admitted attach on server shutdown and retries failed native cleanup", async () => {
const fixture = await connectedFixture();
const held = gate();
onTestFinished(held.release);
fixture.controls.attach = held.wait;
fixture.controls.detachFailures = 1;
const starting = fixture.client
.callTool({
name: "start_frida_session",
arguments: {
mode: "attach",
pid: 512,
device_id: "local",
},
})
.catch(() => undefined);
await held.entered;
const { closing } = await pendingShutdown(fixture.server);
expect(fixture.controls.detachCalls).toBe(0);
held.release();
expect(await closing).toBeInstanceOf(AggregateError);
await starting;
expect(fixture.controls.detachCalls).toBe(1);
await fixture.server.close();
expect(fixture.controls.detachCalls).toBe(2);
await fixture.server.close();
expect(fixture.controls.detachCalls).toBe(2);
const afterClose = await fixture.manager.startSession({
mode: "attach",
pid: 512,
});
expect(afterClose).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
it("drains remote discovery before shutdown and retains failed connection cleanup", async () => {
const fixture = await connectedFixture();
const held = gate();
onTestFinished(held.release);
fixture.controls.discover = held.wait;
fixture.controls.removalFailures = 2;
const discovering = fixture.client
.callTool({
name: "list_frida_processes",
arguments: {
remote: { address: "127.0.0.1:27042" },
},
})
.catch(() => undefined);
await held.entered;
const { closing } = await pendingShutdown(fixture.server);
held.release();
expect(await closing).toBeInstanceOf(AggregateError);
await discovering;
expect(fixture.controls.remoteRemovals).toBe(2);
await fixture.server.close();
expect(fixture.controls.remoteRemovals).toBe(3);
});
it.each(["create", "load"] as const)(
"retains the identity of a cancelled native %s for an explicit MCP unload retry",
async (stage) => {
const { fixture, id, held } = await scriptLoadFixture(stage);
fixture.controls.unloadFailures = 1;
const controller = new AbortController();
const cancelled = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(cancelled).rejects.toThrow(
"cancel retained script",
);
await held.entered;
controller.abort(new Error("cancel retained script"));
await fixture.client.ping();
await rejected;
held.release();
await fixture.load(id, "barrier");
await fixture.client.ping();
expect(fixture.manager.status(id)?.scripts).toHaveLength(3);
const observation = await retainedScriptObservation(
fixture,
id,
"cancelled-native",
);
expect(observation).toMatchObject({
messages:
stage === "create"
? []
: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup: "incomplete_or_unknown",
cleanup_error: expect.stringContaining("transient unload failure"),
});
const scriptId = observation.script_id;
if (typeof scriptId !== "string")
throw new Error("Missing cancelled script identity");
expect(fixture.manager.status(id)?.scripts[1]?.scriptId).toBe(scriptId);
const resuming = await fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
expect(resuming.isError).toBe(true);
expect(fixture.controls.resumes).toBe(0);
await retryCancelledScriptUnload(fixture, id, scriptId);
expect(fixture.unloaded).toEqual(["cancelled-native", "cancelled-native"]);
expect(fixture.loaded).toEqual(
stage === "create"
? ["original", "barrier"]
: ["original", "cancelled-native", "barrier"],
);
expect(fixture.manager.status(id)?.scripts).toHaveLength(2);
expect(fixture.controls.detachCalls).toBe(0);
},
);
it.each([0, 1])(
"settles cancelled native-load cleanup before a queued resume (unload failures: %i)",
async (unloadFailures) => {
const { fixture, id, held } = await scriptLoadFixture();
fixture.controls.unloadFailures = unloadFailures;
const controller = new AbortController();
const loading = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(loading).rejects.toThrow(
"cancel before queued resume",
);
await held.entered;
const resume = () =>
fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
const resuming = resume();
await fixture.client.ping();
controller.abort(new Error("cancel before queued resume"));
await fixture.client.ping();
await rejected;
held.release();
const resumed = await resuming;
await fixture.client.ping();
expect(fixture.unloaded).toEqual(["cancelled-native"]);
expect(fixture.scriptsAtResume).toEqual(
unloadFailures === 0 ? [["original"]] : [],
);
expect(fixture.controls.detachCalls).toBe(0);
expect(fixture.session.exportEvidenceBundle().records).toContainEqual(
expect.objectContaining({
operation: "load_frida_script",
normalized_result: expect.objectContaining({
messages: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup:
unloadFailures === 0 ? "released" : "incomplete_or_unknown",
}),
}),
);
if (unloadFailures === 0) {
expect(resumed.isError).not.toBe(true);
expect(fixture.manager.status(id)?.scripts).toHaveLength(1);
return;
}
expect(resumed.isError).toBe(true);
expect(fixture.manager.status(id)?.state).toBe("paused");
expect((await resume()).isError).toBe(true);
await retryCancelledScriptUnload(fixture, id);
expect((await resume()).isError).not.toBe(true);
expect(fixture.scriptsAtResume).toEqual([["original"]]);
},
);
it.each([0, 1, 2, 3, 4, 8])(
"keeps MCP load Evidence consistent with queued resume across settlement timing %i",
async (microtasks) => {
const { fixture, id, held } = await scriptLoadFixture();
const controller = new AbortController();
fixture.controls.afterLoad = () => {
let remaining = microtasks;
const abort = () => {
if (remaining-- > 0) queueMicrotask(abort);
else controller.abort(new Error("cancel around load completion"));
};
abort();
};
const loading = fixture.load(id, "settling-native", controller.signal);
const observed = loading.catch(() => undefined);
await held.entered;
const resuming = fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
await fixture.client.ping();
held.release();
await observed;
expect((await resuming).isError).not.toBe(true);
fixture.controls.afterLoad = () => {};
await fixture.load(id, "barrier");
await fixture.client.ping();
const records = fixture.session
.exportEvidenceBundle()
.records.filter(
(record) =>
record.operation === "load_frida_script" &&
JSON.stringify(record.normalized_result).includes("settling-native"),
);
expect(records).toHaveLength(1);
const recorded = records[0]?.normalized_result;
if (
recorded === null ||
typeof recorded !== "object" ||
Array.isArray(recorded)
)
throw new Error("Missing script load Evidence");
if (recorded.script_cleanup === "released") {
expect(fixture.scriptsAtResume).toEqual([["original"]]);
expect(fixture.unloaded).toEqual(["settling-native"]);
} else {
expect(recorded.script_cleanup).toBeUndefined();
expect(fixture.scriptsAtResume).toEqual([
["original", "settling-native"],
]);
expect(fixture.unloaded).toEqual([]);
}
},
);
@@ -1,6 +1,6 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
@@ -13,7 +13,6 @@ import {
sessionEvidence,
} from "./ghidraMcpHarness.js";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
+122
View File
@@ -0,0 +1,122 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
createRustImage,
createRustHashOverflowImage,
} from "../../fixtures/rust/image.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";
const connect = async (mcp: TestMcp) => {
const session = createTestBinarySession(() => {
throw new Error("Rust metadata must not start a deep provider");
});
const client = await mcp.connect(createServer({ kind: "session", session }));
return { client, session };
};
mcpTest(
"advertises inspect_rust_binary and reads an embedded dependency list",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_rust_binary",
);
expect(advertised?.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
const root = await createTestTempDirectory("rea-rust-mcp-");
const path = join(root, "sample.elf");
await writeFile(path, createRustImage({ format: "elf" }));
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
response.structuredContent,
);
expect(evidence.normalized_result.auditable_metadata?.packages).toEqual([
expect.objectContaining({ name: "itoa", version: "1.0.18" }),
expect.objectContaining({
name: "sample",
version: "0.1.0",
root: true,
}),
]);
const missing = join(root, "plain.elf");
await writeFile(
missing,
createRustImage({ format: "pe", omitSection: true }),
);
const absent = await client.callTool({
name: "inspect_rust_binary",
arguments: { path: missing },
});
expect(absent.isError).not.toBe(true);
const absentEvidence = toolContract(
"inspect_rust_binary",
).outputSchema.parse(absent.structuredContent);
expect(absentEvidence.normalized_result.auditable_metadata).toBeNull();
} finally {
await session.close();
}
},
);
mcpTest(
"requires an absolute path for inspect_rust_binary",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path: "sample" },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_rust_binary" },
});
} finally {
await session.close();
}
},
);
mcpTest(
"preserves rustc hash capacity units through the public error contract",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const root = await createTestTempDirectory("rea-rust-mcp-");
const path = join(root, "many-hashes.elf");
await writeFile(path, createRustHashOverflowImage());
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "resource_constraint",
details: {
operation: "inspect_rust_binary",
resource: "capacity",
reported_limits: { maximum_rustc_hashes: 64 },
},
});
expect(parseMcpToolError(response).error.details).not.toHaveProperty(
"reported_limits.maximum_bytes",
);
} finally {
await session.close();
}
},
);
@@ -313,6 +313,30 @@ describe("managed member comparison uncertainty", () => {
});
});
describe("managed member comparison beside user strings", () => {
it("keeps member deltas and coverage when only #US literals are nonconforming", () => {
// The method loads "ok", stored with flag 1 where ECMA-335 expects 0.
const options = {
ilBody: Buffer.from([(7 << 2) | 2, 0x72, 1, 0, 0, 0x70, 0x26, 0x2a]),
userStringHeap: Buffer.from([0, 5, 0x6f, 0, 0x6b, 0, 1]),
};
const left = inspect(buildManagedPeFixture(options), "/tmp/left-us.dll");
const right = inspect(buildManagedPeFixture(options), "/tmp/right-us.dll");
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: { ...left.result, fields: [] } },
{
evidenceId: right.evidenceId,
result: { ...right.result, methods: [] },
},
);
expect(left.result.metadata.status).toBe("complete");
expect(left.result.coverage.state).toBe("complete");
expect(left.result.user_strings?.state).toBe("partial");
expect(result.summary).toMatchObject({ added: 1, removed: 1, unknown: 0 });
});
});
describe("managed member comparison of undecoded signatures", () => {
it("remaps renamed methods only when raw signatures and complete normalized IL match", () => {
const signature = Buffer.from([0x00, 0x00, 0x7f]);
@@ -17,6 +17,7 @@ import { execFileOutput } from "../../../../src/process/ExecFileOutput.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
type ArtifactTraversalOmission,
} from "../../../../src/artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
import { DirectoryArtifactReader } from "../../../../src/artifacts/DirectoryArtifactReader.js";
@@ -473,10 +474,10 @@ describe("native DMG traversal shutdown", () => {
.mockImplementation(async function* (
this: DirectoryArtifactReader,
signal?: AbortSignal,
descendInto?: (path: string) => boolean,
selection?: Parameters<DirectoryArtifactReader["entries"]>[1],
) {
const iterator = originalEntries
.call(this, signal, descendInto)
.call(this, signal, selection)
[Symbol.asyncIterator]();
try {
for (;;) {
@@ -606,9 +607,20 @@ describe("native DMG artifact reader", () => {
undefined,
host,
);
if (mountPoint === undefined) throw new Error("expected mounted directory");
if (process.platform !== "win32")
await execFileOutput("mkfifo", [join(mountPoint, "special.pipe")]);
const entries = [];
for await (const entry of reader.entries()) entries.push(entry.path);
const omissions: ArtifactTraversalOmission[] = [];
for await (const entry of reader.entries(undefined, {
onOmission: (omission) => omissions.push(omission),
}))
entries.push(entry.path);
expect(entries).toContain("image.dmg/Fixture/hello.txt");
if (process.platform !== "win32")
expect(omissions).toEqual([
{ path: "image.dmg/Fixture/special.pipe", kind: "fifo" },
]);
const provenance = reader.provenance();
const first = provenance[0];
if (first === undefined) throw new Error("expected attachment provenance");
+141
View File
@@ -0,0 +1,141 @@
import { expect, it } from "vitest";
import { fat } from "../../../src/domain/binaryTarget.fixture.js";
import {
createRustImage,
createRustHashOverflowImage,
RUSTC_HASH,
rustDependencyPayload,
} from "../../fixtures/rust/image.js";
import { readRustBinaryImage } from "../../../src/rust/RustBinaryImage.js";
import { RustAuditableFormatFailure } from "../../../src/rust/RustAuditableReader.js";
const packages = [
{
name: "itoa",
version: "1.0.18",
source: "crates.io",
kind: null,
dependencies: [],
root: false,
},
{
name: "sample",
version: "0.1.0",
source: "local",
kind: null,
dependencies: [0],
root: true,
},
];
it.each(["elf", "pe"] as const)(
"reads a .dep-v0 section and an inferred rustc hash from %s",
(format) => {
const image = readRustBinaryImage(createRustImage({ format }));
expect(image.format).toBe(format);
expect(image.auditable_metadata).toMatchObject({
section_name: ".dep-v0",
file_offset: 1024,
section_bytes: rustDependencyPayload().length,
format_version: 1,
root_package_index: 1,
packages,
dependency_edges: [{ from_index: 1, to_index: 0 }],
});
expect(image.rustc_commit).toEqual({
evidence_kind: "inferred",
hashes: [{ hash: RUSTC_HASH, file_offset: 2048 }],
});
},
);
it("reads a Mach-O __DATA,.dep-v0 section", () => {
const image = readRustBinaryImage(createRustImage({ format: "macho" }));
expect(image).toMatchObject({
format: "macho",
architecture: "arm64",
auditable_metadata: {
section_name: "__DATA,.dep-v0",
file_offset: 1024,
root_package_index: 1,
packages,
},
rustc_commit: {
evidence_kind: "inferred",
hashes: [{ hash: RUSTC_HASH, file_offset: 2048 }],
},
});
});
it("ignores PE file-alignment padding after the dependency content", () => {
const bytes = createRustImage({ format: "pe", includeRustc: false });
const payloadBytes = rustDependencyPayload().length;
const entry = 264;
expect(bytes.readUInt32LE(entry + 8)).toBe(payloadBytes);
bytes.writeUInt32LE(512, entry + 16);
const image = readRustBinaryImage(bytes);
expect(image.auditable_metadata).toMatchObject({
section_name: ".dep-v0",
section_bytes: payloadBytes,
packages,
});
});
it("returns null metadata when the dependency section is absent", () => {
const image = readRustBinaryImage(
createRustImage({ format: "elf", omitSection: true }),
);
expect(image.auditable_metadata).toBeNull();
expect(image.rustc_commit?.hashes).toEqual([
{ hash: RUSTC_HASH, file_offset: 2048 },
]);
});
it("refuses a universal Mach-O container", () => {
expect(() => readRustBinaryImage(fat([0x0100000c]))).toThrow(
RustAuditableFormatFailure,
);
expect(() => readRustBinaryImage(fat([0x0100000c]))).toThrow(/thin slice/);
});
it("does not read SHT_NOBITS dependency sections as stored bytes", () => {
const bytes = createRustImage({ format: "elf" });
// The fixture writes the .dep-v0 section header at byte 384.
bytes.writeUInt32LE(8, 384 + 4);
let metadata: unknown;
try {
metadata = readRustBinaryImage(bytes).auditable_metadata;
} catch (cause: unknown) {
expect(cause).toBeInstanceOf(RustAuditableFormatFailure);
return;
}
expect(metadata).toBeNull();
});
it("reads a rustc path from a read-only ELF section whose name exceeds 64 bytes", () => {
const bytes = createRustImage({ format: "elf", omitSection: true });
// omitSection places the rustc section header at 384 and shstrtab at 320.
const nameOffset = bytes.readUInt32LE(384);
const tableOffset = Number(bytes.readBigUInt64LE(320 + 24));
const longName = Buffer.concat([Buffer.alloc(65, 0x61), Buffer.from([0])]);
longName.copy(bytes, tableOffset + nameOffset);
bytes.writeBigUInt64LE(BigInt(nameOffset + longName.length), 320 + 32);
const image = readRustBinaryImage(bytes);
expect(image.auditable_metadata).toBeNull();
expect(image.rustc_commit).toEqual({
evidence_kind: "inferred",
hashes: [{ hash: RUSTC_HASH, file_offset: 2048 }],
});
});
it("refuses read-only data with more distinct rustc paths than it retains", () => {
const bytes = createRustHashOverflowImage();
expect(() => readRustBinaryImage(bytes)).toThrow(
expect.objectContaining({
constraint: {
resource: "capacity",
reported_limits: { maximum_rustc_hashes: 64 },
},
}),
);
});
+263
View File
@@ -0,0 +1,263 @@
import { deflateSync } from "node:zlib";
/** zlib payload matching the embedded dependency JSON shape. */
export const rustDependencyPayload = (
document: unknown = {
packages: [
{ name: "itoa", version: "1.0.18", source: "crates.io" },
{
name: "sample",
version: "0.1.0",
source: "local",
dependencies: [0],
root: true,
},
],
format: 1,
},
): Buffer => deflateSync(Buffer.from(JSON.stringify(document)));
export const RUSTC_HASH = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const RUSTC_PATH = `/rustc/${RUSTC_HASH}/library/core`;
/** Synthetic ELF, PE, or thin Mach-O with an optional dependency section. */
export const createRustImage = (options: {
readonly format: "elf" | "pe" | "macho";
readonly payload?: Buffer;
readonly omitSection?: boolean;
readonly includeRustc?: boolean;
}): Buffer => {
const payload = options.payload ?? rustDependencyPayload();
const rustc = options.includeRustc === false ? null : Buffer.from(RUSTC_PATH);
const bytes = Buffer.alloc(4096);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const little = (offset: number, value: number, width: 16 | 32 | 64) => {
if (width === 16) view.setUint16(offset, value, true);
else if (width === 32) view.setUint32(offset, value, true);
else view.setBigUint64(offset, BigInt(value), true);
};
const image = {
bytes,
little,
payload,
omitSection: options.omitSection === true,
rustc,
};
if (options.format === "elf") writeElf(image);
else if (options.format === "pe") writePe(image);
else writeMacho(image);
return bytes;
};
interface RustImageWrite {
readonly bytes: Buffer;
readonly little: (offset: number, value: number, width: 16 | 32 | 64) => void;
readonly payload: Buffer;
readonly omitSection: boolean;
readonly rustc: Buffer | null;
}
const writeElf = ({
bytes,
little,
payload,
omitSection,
rustc,
}: RustImageWrite): void => {
bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1]);
little(16, 2, 16);
little(18, 62, 16);
little(20, 1, 32);
little(32, 128, 64);
little(40, 256, 64);
little(52, 64, 16);
little(54, 56, 16);
little(56, 1, 16);
little(58, 64, 16);
const names = omitSection
? Buffer.from("\0.shstrtab\0.rodata\0")
: Buffer.from("\0.shstrtab\0.dep-v0\0.rodata\0");
little(60, rustc === null && omitSection ? 0 : omitSection ? 3 : 4, 16);
little(62, rustc === null && omitSection ? 0 : 1, 16);
little(128, 1, 32);
little(132, 6, 32);
little(144, 0x400000, 64);
little(160, bytes.length, 64);
little(168, bytes.length, 64);
if (rustc === null && omitSection) return;
names.copy(bytes, 768);
const shstr = 320;
little(shstr, 1, 32);
little(shstr + 4, 3, 32);
little(shstr + 24, 768, 64);
little(shstr + 32, names.length, 64);
let next = 384;
if (!omitSection) {
little(next, 11, 32);
little(next + 4, 1, 32);
little(next + 24, 1024, 64);
little(next + 32, payload.length, 64);
payload.copy(bytes, 1024);
next += 64;
}
if (rustc !== null) {
const name = omitSection ? 11 : 19;
little(next, name, 32);
little(next + 4, 1, 32);
little(next + 8, 2, 64);
little(next + 16, 0x400000 + 2048, 64);
little(next + 24, 2048, 64);
little(next + 32, rustc.length, 64);
rustc.copy(bytes, 2048);
}
};
const writePe = ({
bytes,
little,
payload,
omitSection,
rustc,
}: RustImageWrite): void => {
bytes.write("MZ", 0, "ascii");
little(60, 128, 32);
bytes.write("PE\0\0", 128, "ascii");
little(132, 0x8664, 16);
const count = Number(!omitSection) + Number(rustc !== null);
little(134, count, 16);
little(148, 112, 16);
little(152, 0x20b, 16);
little(176, 0x140000000, 64);
const writeSection = (section: {
readonly entry: number;
readonly name: string;
readonly offset: number;
readonly body: Buffer;
readonly address: number;
}) => {
bytes.write(section.name, section.entry, "ascii");
little(section.entry + 8, section.body.length, 32);
little(section.entry + 12, section.address, 32);
little(section.entry + 16, section.body.length, 32);
little(section.entry + 20, section.offset, 32);
little(section.entry + 36, 0x40000040, 32);
section.body.copy(bytes, section.offset);
};
let entry = 264;
if (!omitSection) {
writeSection({
entry,
name: ".dep-v0",
offset: 1024,
body: payload,
address: 0x1000,
});
entry += 40;
}
if (rustc !== null)
writeSection({
entry,
name: ".rdata",
offset: 2048,
body: rustc,
address: 0x2000,
});
};
const writeMacho = ({
bytes,
little,
payload,
omitSection,
rustc,
}: RustImageWrite): void => {
const commands = Number(rustc !== null) + Number(!omitSection);
little(0, 0xfeedfacf, 32);
little(4, 0x0100000c, 32);
little(12, 2, 32);
little(16, commands, 32);
little(20, commands * 152, 32);
let command = 32;
if (rustc !== null) {
writeMachoSegment({
bytes,
little,
command,
segment: "__TEXT",
section: "__cstring",
body: rustc,
fileOffset: 2048,
protection: 5,
flags: 2,
});
command += 152;
}
if (!omitSection)
writeMachoSegment({
bytes,
little,
command,
segment: "__DATA",
section: ".dep-v0",
body: payload,
fileOffset: 1024,
protection: 3,
flags: 0,
});
};
const writeMachoSegment = ({
bytes,
little,
command,
segment,
section,
body,
fileOffset,
protection,
flags,
}: {
readonly bytes: Buffer;
readonly little: RustImageWrite["little"];
readonly command: number;
readonly segment: string;
readonly section: string;
readonly body: Buffer;
readonly fileOffset: number;
readonly protection: number;
readonly flags: number;
}): void => {
little(command, 0x19, 32);
little(command + 4, 152, 32);
bytes.write(segment, command + 8, "ascii");
little(command + 24, 0x100000000, 64);
little(command + 32, 0x2000, 64);
little(command + 40, fileOffset, 64);
little(command + 48, body.length, 64);
little(command + 56, protection, 32);
little(command + 60, protection, 32);
little(command + 64, 1, 32);
const header = command + 72;
bytes.write(section, header, "ascii");
bytes.write(segment, header + 16, "ascii");
little(header + 32, 0x100000000, 64);
little(header + 40, body.length, 64);
little(header + 48, fileOffset, 32);
little(header + 64, flags, 32);
body.copy(bytes, fileOffset);
};
/** Read-only ELF data exceeding the distinct rustc-hash retention capacity. */
export const createRustHashOverflowImage = (): Buffer => {
const bytes = createRustImage({ format: "elf", omitSection: true });
// Without .dep-v0 the read-only section header is the second one, at 384.
// Section names end before byte 800, so the hash block starts there.
bytes.writeBigUInt64LE(800n, 384 + 24);
bytes.writeBigUInt64LE(3296n, 384 + 32);
bytes.fill(0, 800);
for (let index = 0; index < 65; index += 1) {
const hash = index.toString(16).padStart(40, "0");
bytes.write(`/rustc/${hash}/`, 800 + index * 48, "latin1");
}
return bytes;
};
@@ -41,6 +41,9 @@ it
}
// A rejection must come from the fixture we are about to launch. An
// existing Xvfb would otherwise mask a broken executable-identity check.
// The copied launcher has a unique file identity and has not run yet.
// The synthetic proc root isolates the positive identity check from
// unrelated restricted host processes while retaining display-name checks.
await assertCleanLinuxHopperRuntime(
alternateMode ? [launcher] : [],
procRoot,