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,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 },
},
}),
);
});