chore: reconcile iNES inventory with current main

This commit is contained in:
64579525
2026-10-13 09:36:35 +08:00
646 changed files with 49020 additions and 6280 deletions
@@ -0,0 +1,266 @@
import { createHash } from "node:crypto";
import {
copyFile,
mkdtemp,
readFile,
readdir,
rm,
writeFile,
} from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import { AdbProvider } from "../../../../src/adb/AdbProvider.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import {
execFileBytes,
execFileOutput,
} from "../../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
// Exercise real filesystem publication; the Android process reply is simulated.
vi.mock(
"../../../../src/process/ExecFileOutput.js",
async (importOriginal) => ({
...(await importOriginal<
typeof import("../../../../src/process/ExecFileOutput.js")
>()),
execFileBytes: vi.fn(),
execFileOutput: vi.fn(),
}),
);
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return {
...actual,
copyFile: vi.fn(actual.copyFile),
mkdtemp: vi.fn(actual.mkdtemp),
rm: vi.fn(actual.rm),
};
});
afterEach(() => vi.restoreAllMocks());
const fixture = async (duringCollection?: (root: string) => Promise<void>) => {
const root = await createTestTempDirectory("rea-adb-bugreport-");
const binary = join(root, "adb");
let reportedPath = "";
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
expect(args).toEqual(["version"]);
return {
stdout: `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`,
stderr: "",
};
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
expect(args.slice(0, 3)).toEqual(["-s", "device", "bugreport"]);
const staging = args[3]!;
reportedPath = join(staging, "bugreport test.zip");
await writeFile(reportedPath, "bugreport-bytes");
await duringCollection?.(root);
return {
stdout: Buffer.from(`Bug report copied to ${reportedPath}\n`),
stderr: Buffer.alloc(0),
};
});
const provider = new AdbProvider({ environment: { REA_ADB_PATH: binary } });
return {
root,
provider,
reportedPath: () => reportedPath,
request: {
operation: "collect_adb_bugreport" as const,
input: { serial: "device", output_directory: root },
},
};
};
test.each(["before", "during"] as const)(
"preserves a same-name caller archive created %s collection",
async (when) => {
const existing = async (root: string) => {
await writeFile(join(root, "bugreport test.zip"), "existing evidence");
await writeFile(join(root, "bugreport test (1).zip"), "other evidence");
};
const f = await fixture(when === "during" ? existing : undefined);
if (when === "before") await existing(f.root);
const result = await f.provider.execute(f.request);
if (!result.ok) throw result.error;
const localPath = join(f.root, "bugreport test (2).zip");
expect(result.value.result).toMatchObject({
local_path: localPath,
adb_reported_path: f.reportedPath(),
bytes: 15,
sha256: createHash("sha256").update("bugreport-bytes").digest("hex"),
});
expect(await readFile(join(f.root, "bugreport test.zip"), "utf8")).toBe(
"existing evidence",
);
expect(await readFile(join(f.root, "bugreport test (1).zip"), "utf8")).toBe(
"other evidence",
);
expect(await readFile(localPath, "utf8")).toBe("bugreport-bytes");
expect((await readdir(f.root)).sort()).toEqual([
"bugreport test (1).zip",
"bugreport test (2).zip",
"bugreport test.zip",
]);
await f.provider.close();
},
);
test("retains a completed archive after failed publication and later provider work", async () => {
const f = await fixture();
const existing = join(f.root, "bugreport test.zip");
await writeFile(existing, "existing evidence");
const publicationFailure = Object.assign(new Error("no space left"), {
code: "ENOSPC",
});
vi.mocked(copyFile).mockRejectedValueOnce(publicationFailure);
const failed = await f.provider.execute(f.request);
if (failed.ok) throw new Error("expected publication failure");
const retainedPath = f.reportedPath();
expect(failed.error._tag).toBe("AnalysisOutputError");
expect(failed.error.cause).toBe(publicationFailure);
expect(
projectAnalysisError(failed.error).details?.partial_observation,
).toMatchObject({
provider_id: "adb",
operation: f.request.operation,
result: {
serial: "device",
local_path: retainedPath,
adb_reported_path: retainedPath,
digest_status: "unknown",
},
});
expect(await readFile(retainedPath, "utf8")).toBe("bugreport-bytes");
expect(await readFile(existing, "utf8")).toBe("existing evidence");
// New work and terminal cleanup must not reclaim the retained acquisition.
const next = await f.provider.execute(f.request);
if (!next.ok) throw next.error;
expect(next.value.result).toMatchObject({
local_path: join(f.root, "bugreport test (1).zip"),
bytes: 15,
sha256: createHash("sha256").update("bugreport-bytes").digest("hex"),
});
await f.provider.close();
expect(await readFile(retainedPath, "utf8")).toBe("bugreport-bytes");
expect(await readFile(existing, "utf8")).toBe("existing evidence");
expect(await readFile(join(f.root, "bugreport test (1).zip"), "utf8")).toBe(
"bugreport-bytes",
);
expect((await readdir(f.root)).sort()).toEqual(
[
basename(dirname(retainedPath)),
"bugreport test.zip",
"bugreport test (1).zip",
].sort(),
);
});
test("retains final and producer paths when digest verification is cancelled", async () => {
const f = await fixture();
const controller = new AbortController();
const actualCopy =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
vi.mocked(copyFile).mockImplementationOnce(async (...args) => {
await actualCopy.copyFile(...args);
controller.abort();
});
const result = await f.provider.execute(f.request, {
signal: controller.signal,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
operation: f.request.operation,
result: {
local_path: join(f.root, "bugreport test.zip"),
adb_reported_path: f.reportedPath(),
digest_status: "unknown",
},
});
expect(await readFile(join(f.root, "bugreport test.zip"), "utf8")).toBe(
"bugreport-bytes",
);
expect(await readdir(f.root)).toEqual(["bugreport test.zip"]);
await f.provider.close();
});
test("returns staging allocation failures without invoking device collection", async () => {
const f = await fixture();
vi.mocked(mkdtemp).mockRejectedValueOnce(new Error("staging denied"));
const result = await f.provider.execute(f.request);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected output failure");
expect(result.error._tag).toBe("AnalysisOutputError");
expect(execFileBytes).not.toHaveBeenCalled();
await f.provider.close();
});
test("retains published evidence and retries failed staging cleanup", async () => {
const f = await fixture();
vi.mocked(rm).mockRejectedValueOnce(new Error("cleanup denied"));
const result = await f.provider.execute(f.request);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected cleanup failure");
expect(result.error.cleanupResources).toContain(dirname(f.reportedPath()));
expect(result.error.partialObservation).toMatchObject({
operation: f.request.operation,
result: {
local_path: join(f.root, "bugreport test.zip"),
adb_reported_path: f.reportedPath(),
bytes: 15,
sha256: createHash("sha256").update("bugreport-bytes").digest("hex"),
},
});
await f.provider.close();
expect(await readdir(f.root)).toEqual(["bugreport test.zip"]);
});
test("refuses an archive reported outside the owned staging directory", async () => {
const f = await fixture();
const existing = join(f.root, "bugreport test.zip");
await writeFile(existing, "existing evidence");
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.from(`Bug report copied to ${existing}\n`),
stderr: Buffer.alloc(0),
});
const result = await f.provider.execute(f.request);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected protocol refusal");
expect(result.error._tag).toBe("AnalysisProtocolError");
expect(await readFile(existing, "utf8")).toBe("existing evidence");
expect(await readdir(f.root)).toEqual(["bugreport test.zip"]);
await f.provider.close();
});
test("preserves the primary protocol failure when staging cleanup also fails", async () => {
const f = await fixture();
vi.mocked(execFileBytes).mockResolvedValueOnce({
stdout: Buffer.from("unsupported completion format\n"),
stderr: Buffer.alloc(0),
});
vi.mocked(rm).mockRejectedValueOnce(new Error("cleanup denied"));
const result = await f.provider.execute(f.request);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected protocol and cleanup failure");
expect(result.error.cause).toMatchObject({
errors: [
{
_tag: "AnalysisProtocolError",
message: expect.stringContaining("did not report an archive path"),
},
expect.any(Error),
],
});
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toHaveLength(1);
await f.provider.close();
expect(await readdir(f.root)).toEqual([]);
});
@@ -0,0 +1,345 @@
import { mkdir, writeFile } from "node:fs/promises";
import { createHash, randomUUID } from "node:crypto";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { createGhidraDiagnostics } from "../../../../src/ghidra/GhidraDiagnostics.js";
import {
GhidraHeadlessLauncher,
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
type GhidraLaunchSession,
} from "../../../../src/ghidra/GhidraLauncher.js";
import { bindGhidraSessionFailure } from "../../../../src/ghidra/GhidraSessionError.js";
import { spawnOwnedProviderProcess } from "../../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../../src/process/ProcessOwnership.js";
import { waitForAbortableDelay } from "../../../../src/process/ProviderDeadline.js";
import { GhidraProvider } from "../../../../src/ghidra/GhidraProvider.js";
import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
import { parseConfig } from "../../../../src/config/parseConfig.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../../../../src/contracts/errorSchemas.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
import { elf } from "../../../../src/domain/binaryTarget.fixture.js";
import { silentLogger } from "../../../../src/logger.js";
const warning =
"[0.004s][warning][os,container] Cgroup limits may be inaccurate: /tmp/password-fixture?token=public-value";
const fixture = async (
mode: string,
javaVmName: string | null = "OpenJDK 64-Bit Server VM",
) => {
const root = await createTestTempDirectory("rea-ghidra-java-launch-");
const javaHome = join(root, "jdk");
await mkdir(join(javaHome, "bin"), { recursive: true });
await writeFile(
join(javaHome, "bin", "java"),
`#!/usr/bin/env node
const args = process.argv.slice(2);
const probe = args.at(-1);
if (probe !== "-envvars" && probe !== "-vmargs") process.exit(64);
const mode = ${JSON.stringify(mode)};
if (mode === "non-hotspot" && args.some(arg => arg.startsWith("-Xlog:"))) process.exit(65);
const warning = ${JSON.stringify(warning)};
const stream = args.includes("-Xlog:disable") && args.includes("-Xlog:all=warning:stderr") ? process.stderr : process.stdout;
if (mode !== "quiet" && mode !== "non-hotspot") stream.write(probe + ": " + warning + "\\n");
if (mode === "credential") stream.write("explicit credential: private-transport-token\\n");
if (mode === "large") stream.write("é".repeat(${GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES}) + "UNRETAINED-TAIL\\n");
if (mode === "env-failure" || (probe === "-vmargs" && mode === "vm-failure")) {
process.stderr.write("failed " + probe + "\\n");
process.exitCode = 3;
} else if (probe === "-envvars") {
process.stdout.write(mode === "env-malformed" ? "invalid environment\\n" : "GHIDRA_MAXMEM=1G\\n");
} else {
process.stdout.write(mode === "vm-malformed" ? "invalid JVM argument\\n" : "-Dfile.encoding=UTF8\\n");
}
`,
{ mode: 0o755 },
);
const session: GhidraLaunchSession = {
runtimeRoot: join(root, "runtime"),
transport: "unix-socket",
endpointPath: join(root, "endpoint.sock"),
token: "private-transport-token",
runId: randomUUID(),
targetPath: join(root, "target.bin"),
targetSha256: "0".repeat(64),
providerVersion: "test",
profileDigest: "test",
};
const analysisArguments: (readonly string[])[] = [];
const controller = new AbortController();
const launcher = new GhidraHeadlessLauncher({
environment: { PATH: process.env.PATH ?? "" },
platform: process.platform,
javaHome,
...(javaVmName === null ? {} : { javaVmName }),
analyzeHeadlessPath: join(root, "ghidra", "support", "analyzeHeadless"),
bridgeScriptPath: join(root, "ReaGhidraBridge.java"),
spawnProcess: async (options) => {
analysisArguments.push(options.arguments);
const spawned = await spawnOwnedProviderProcess({
...options,
command: process.execPath,
arguments: ["-e", "setInterval(() => {}, 1000)"],
expectedCommand: process.execPath,
});
onTestFinished(async () => {
const cleanup =
spawned.cleanup === undefined
? await cleanupOwnedProcessGroup(spawned.ownership)
: await spawned.cleanup();
expect(cleanup.cleaned).toBe(true);
});
if (mode === "cancel-after-spawn") controller.abort();
if (mode === "timeout-after-spawn")
await waitForAbortableDelay(10_000, options.signal);
return spawned;
},
});
return { session, launcher, analysisArguments, controller };
};
describe.skipIf(process.platform === "win32")(
"Ghidra LaunchSupport JVM compatibility",
() => {
it.each(["Eclipse OpenJ9 VM", "unrecognized VM", ""])(
"keeps HotSpot-only flags off a VM identified as %s",
async (javaVmName) => {
const { session, launcher, analysisArguments } = await fixture(
"non-hotspot",
javaVmName === "" ? null : javaVmName,
);
const launched = await launcher.launch(session);
if (!launched.ok) throw launched.error;
expect(analysisArguments).toHaveLength(1);
expect(launched.value.launchSupport).toBeUndefined();
},
);
it.each([
"OpenJDK 64-Bit Server VM",
"Java HotSpot(TM) 64-Bit Server VM",
"OpenJDK 64-Bit Zero VM",
])(
"preserves redirected warnings for %s while keeping the analysis JVM arguments clean",
async (javaVmName) => {
const { session, launcher, analysisArguments } = await fixture(
"success",
javaVmName,
);
const launched = await launcher.launch(session);
if (!launched.ok) throw launched.error;
expect(analysisArguments[0]).toContain("-Dfile.encoding=UTF8");
expect(analysisArguments[0]).toContain("-Xmx1G");
expect(
analysisArguments[0]?.some(
(argument) =>
argument.startsWith("-Xlog:") || argument.includes("[warning]"),
),
).toBe(false);
const diagnostics = createGhidraDiagnostics({
targetPath: session.targetPath,
targetSha256: session.targetSha256,
transport: session.transport,
providerVersion: session.providerVersion,
profileDigest: session.profileDigest,
launch: launched.value,
token: session.token,
previous: {},
});
expect(diagnostics.launch_support).toEqual(
["-envvars", "-vmargs"].map((mode) => ({
mode,
stderr: `${mode}: ${warning}\n`,
stderr_bytes: Buffer.byteLength(`${mode}: ${warning}\n`),
stderr_truncated: false,
})),
);
},
);
},
);
describe.skipIf(process.platform === "win32")(
"Ghidra LaunchSupport diagnostics",
() => {
it.each(["env-failure", "vm-failure", "env-malformed", "vm-malformed"])(
"retains helper warnings through session failure diagnostics after %s",
async (mode) => {
const { session, launcher, analysisArguments } = await fixture(mode);
const launched = await launcher.launch(session);
expect(launched.ok).toBe(false);
if (launched.ok) throw new Error("Expected a helper failure");
expect(analysisArguments).toEqual([]);
const failure = bindGhidraSessionFailure(() => ({}))(
"start",
launched.error.message,
launched.error,
);
const cause = failure.diagnostics.failure_cause;
if (mode === "env-failure") {
expect(cause).toMatchObject({
launch_outcome: {
exit_code: 3,
stderr: expect.stringContaining(`-envvars: ${warning}`),
},
});
} else {
expect(cause).toMatchObject({
launch_support: expect.arrayContaining([
expect.objectContaining({
mode: "-envvars",
stderr: `-envvars: ${warning}\n`,
}),
]),
});
}
if (mode === "vm-failure")
expect(cause).toMatchObject({
launch_outcome: {
exit_code: 3,
stderr: expect.stringContaining(`-vmargs: ${warning}`),
},
});
if (mode === "vm-malformed")
expect(cause).toMatchObject({
launch_support: expect.arrayContaining([
expect.objectContaining({
mode: "-vmargs",
stderr: `-vmargs: ${warning}\n`,
}),
]),
});
},
);
it("bounds retained UTF-8 warnings and reports original byte counts", async () => {
const { session, launcher } = await fixture("large");
const launched = await launcher.launch(session);
if (!launched.ok) throw launched.error;
for (const output of launched.value.launchSupport ?? []) {
expect(output.stderr_truncated).toBe(true);
expect(output.stderr_bytes).toBeGreaterThan(
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
);
expect(Buffer.byteLength(output.stderr)).toBeLessThanOrEqual(
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
);
expect(output.stderr).not.toContain("UNRETAINED-TAIL");
expect(output.stderr).not.toContain("�");
}
expect(launched.value.launchSupport).toHaveLength(2);
});
it("omits helper diagnostics when both stderr streams are empty", async () => {
const { session, launcher } = await fixture("quiet");
const launched = await launcher.launch(session);
if (!launched.ok) throw launched.error;
expect(launched.value.launchSupport).toBeUndefined();
});
it("redacts the explicit transport credential and preserves caller-selected paths and URL values", async () => {
const { session, launcher } = await fixture("credential");
const launched = await launcher.launch(session);
if (!launched.ok) throw launched.error;
expect(launched.value.launchSupport).toHaveLength(2);
for (const output of launched.value.launchSupport ?? []) {
expect(output.stderr).toContain(warning);
expect(output.stderr).toContain("explicit credential: [REDACTED]");
expect(output.stderr).not.toContain(session.token);
expect(output.stderr_truncated).toBe(false);
}
});
},
);
describe.skipIf(process.platform === "win32")(
"Ghidra startup interruption diagnostics",
() => {
it.each(["cancelled", "timeout"] as const)(
"preserves helper warnings through the provider-neutral %s projection",
async (kind) => {
const { session, launcher, controller } = await fixture(
kind === "cancelled" ? "cancel-after-spawn" : "timeout-after-spawn",
);
const bytes = elf(2, 1, 62);
await writeFile(session.targetPath, bytes);
const target: BinaryTarget = {
path: session.targetPath,
sha256: createHash("sha256").update(bytes).digest("hex"),
kind: "executable",
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
};
const config = parseConfig({
GHIDRA_INSTALL_DIR: "/fixture/ghidra",
REA_GHIDRA_STARTUP_TIMEOUT_MS: "3000",
});
if (!config.ok) throw config.error;
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
{
platform: process.platform,
architecture: process.arch,
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.12",
major: 21,
home: "/fixture/jdk",
bits: 64,
runtime: "jdk",
}),
},
(options) => new GhidraClient({ ...options, launcher }),
);
const profile = await provider.resolveAnalysisProfile(target);
if (!profile.ok) throw profile.error;
if (profile.value.profile === null)
throw new Error("Expected Ghidra profile");
const client = provider.createClient(target, profile.value.profile);
onTestFinished(async () => {
expect((await client.close()).ok).toBe(true);
});
const result = await client.execute(
"health",
{},
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected interrupted startup");
const projected = analysisErrorProjectionSchema.parse(
JSON.parse(JSON.stringify(projectAnalysisError(result.error))),
);
expect(projected.code).toBe(
kind === "cancelled" ? "cancelled" : "provider_timeout",
);
expect(projected).toMatchObject({
details: {
diagnostics: {
failure_cause: {
cause: {
launch_support: expect.arrayContaining([
expect.objectContaining({
mode: "-envvars",
stderr: `-envvars: ${warning}\n`,
}),
expect.objectContaining({
mode: "-vmargs",
stderr: `-vmargs: ${warning}\n`,
}),
]),
},
},
},
},
});
},
);
},
);
@@ -28,6 +28,30 @@ const armSession = () =>
leafRoots: ["0x2000", "0x3000"],
});
it("keeps unknown caller coverage and callee diagnostics in an ARM64 dossier", async () => {
const { client } = await armSession();
try {
const result = await client.execute("analyze_function", {
procedure: "main",
});
if (!result.ok) throw result.error;
expect(result.value.relationshipCoverage).toMatchObject({
status: "unknown",
reason:
"Callers: Upstream xrefs do not establish direct caller relationships.",
diagnostics: expect.arrayContaining([
expect.stringContaining("targets IDA does not recognize as functions"),
]),
});
expect(result.value.result).toMatchObject({
callers: [],
callees: [{ address: "0x2000" }, { address: "0x3000" }],
});
} finally {
await client.close();
}
});
it("shows the callee edges of an ARM64 procedure in the call graph", async () => {
const { client, producer } = await armSession();
try {
@@ -0,0 +1,271 @@
import { randomUUID } from "node:crypto";
import { readFile, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { join } from "node:path";
import { expect, it } from "vitest";
import { z } from "zod";
import {
jsonValueSchema,
type JsonValue,
} from "../../../../src/domain/jsonValue.js";
import { nativeTools } from "../../../../src/ida/IdaNativeProtocol.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../../../../src/process/OwnedCommand.js";
import { createIdaTarget } from "../../../fixtures/idaMcp.js";
const requestSchema = z.object({
id: z.union([z.string(), z.number()]).optional(),
method: z.string(),
params: z
.object({
protocolVersion: z.string().optional(),
name: z.string().optional(),
arguments: z.record(z.string(), jsonValueSchema).optional(),
})
.passthrough()
.optional(),
});
const fn = (address: string) => ({
addr: address,
name: address === "0x1000" ? "main" : "helper",
size: "0x20",
});
const observation = (
name: string,
args: Readonly<Record<string, JsonValue>>,
scenario: { readonly empty: readonly string[]; readonly omitMore: boolean },
): JsonValue => {
switch (name) {
case "lookup_funcs":
return z
.array(z.string())
.parse(args.queries)
.map((query) => ({
query,
fn: fn(
query === "helper" || query === "0x2000" ? "0x2000" : "0x1000",
),
error: null,
}));
case "list_funcs":
return [
{
data: scenario.empty.includes(name) ? [] : [fn("0x1000")],
next_offset: null,
},
];
case "find_regex":
return {
matches: scenario.empty.includes(name)
? []
: [{ addr: "0x3000", string: "a.b" }],
cursor: { done: true },
};
case "decompile": {
const addr = z.string().parse(args.addr);
return {
addr,
ok: true,
pseudocode:
addr === "0x1000"
? "int main(void) { return 42; }"
: "int helper(void) { return 55; }",
lines: 1,
};
}
case "disasm":
return {
asm: {
name: "main",
start_ea: "0x1000",
lines: "main (.text @ 0x1000):\n1000 ret",
},
cursor: { done: true },
};
case "callees":
return [
{
callees: [],
error: null,
...(scenario.omitMore ? {} : { more: false }),
},
];
case "xrefs_to":
return [
{
xrefs: scenario.empty.includes(name)
? []
: [{ addr: "0x1004", type: "code", fn: null }],
more: false,
error: null,
},
];
default:
throw new Error(`Unexpected fixture operation ${name}`);
}
};
const fixture = async (empty: readonly string[], omitMore: boolean) => {
const { root, target } = await createIdaTarget();
const server = createServer(async (request, response) => {
try {
let body = "";
for await (const chunk of request) body += String(chunk);
const input = requestSchema.parse(JSON.parse(body));
if (input.id === undefined) {
response.writeHead(202).end();
return;
}
const result =
input.method === "initialize"
? {
protocolVersion: input.params?.protocolVersion,
capabilities: { tools: {}, resources: {} },
serverInfo: { name: "native-verifier-fixture", version: "1" },
}
: input.method === "tools/list"
? {
tools: nativeTools.map((name) => ({
name,
inputSchema: { type: "object" },
})),
}
: input.method === "resources/read"
? {
contents: [
{
uri: "ida://idb/metadata",
mimeType: "application/json",
text: JSON.stringify({
path: `${target.path}.i64`,
sha256: target.sha256,
base: "0x1000",
module: "target.elf",
}),
},
],
}
: {
content: [
{
type: "text",
text: JSON.stringify(
observation(
z.string().parse(input.params?.name),
input.params?.arguments ?? {},
{ empty, omitMore },
),
),
},
],
};
response
.writeHead(200, { "Content-Type": "application/json" })
.end(JSON.stringify({ jsonrpc: "2.0", id: input.id, result }));
} catch {
response.writeHead(500).end();
}
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("No fixture address");
const config = join(root, "native.json");
await writeFile(
config,
JSON.stringify({
url: `http://127.0.0.1:${address.port}/mcp`,
protocol: "native",
timeoutMs: 30000,
}),
);
return {
root,
target,
config,
close: async (removeWorkspace: boolean) => {
server.closeAllConnections();
await new Promise<void>((resolve, reject) =>
server.close((error) =>
error === undefined ? resolve() : reject(error),
),
);
if (removeWorkspace) await rm(root, { recursive: true, force: true });
},
};
};
it.each([
{ empty: [], omitMore: false, oracles: true, passed: true },
{ empty: ["list_funcs"], omitMore: false, oracles: true, passed: false },
{ empty: ["find_regex"], omitMore: false, oracles: true, passed: false },
{ empty: ["xrefs_to"], omitMore: false, oracles: true, passed: false },
{ empty: [], omitMore: true, oracles: true, passed: false },
{
empty: ["find_regex", "xrefs_to"],
omitMore: false,
oracles: false,
passed: true,
},
])(
"checks real-verifier values for $empty / omitted more=$omitMore / oracles=$oracles",
async ({ empty, omitMore, oracles, passed }) => {
const upstream = await fixture(empty, omitMore);
let cleanupConfirmed = false;
try {
const reportPath = join(upstream.root, "report.json");
const result = await runOwnedCommand(
{
command: process.execPath,
arguments: [
"scripts/verify-real-ida.mjs",
"--target",
upstream.target.path,
"--procedure",
"main",
"--second-procedure",
"helper",
"--second-marker",
"55",
"--report",
reportPath,
...(oracles
? ["--expected-string", "a.b", "--expected-xref", "0x1004"]
: []),
],
runId: `rea-ida-verifier-${randomUUID()}`,
cwd: process.cwd(),
env: {
REA_IDA_MCP_CONFIG: upstream.config,
NODE_OPTIONS: "--max-old-space-size=1024",
},
},
{ timeoutMs: 90000, diagnosticBytes: 16384, acceptNonZeroExit: true },
);
cleanupConfirmed = true;
const report = z
.object({ passed: z.boolean(), unverified: z.array(z.string()) })
.parse(JSON.parse(await readFile(reportPath, "utf8")));
expect(report.passed, result.stdout.text + result.stderr.text).toBe(
passed,
);
expect(result.exitCode).toBe(passed ? 0 : 1);
if (!oracles)
expect(report.unverified).toEqual([
"String inventory/search correctness: no independent expected literal supplied.",
"Xref correctness: no independent expected source address supplied.",
]);
else expect(report.unverified).toEqual([]);
} catch (cause) {
if (cause instanceof OwnedCommandFailure && cause.cleanupFailure === null)
cleanupConfirmed = true;
throw cause;
} finally {
await upstream.close(cleanupConfirmed);
}
},
120000,
);
@@ -0,0 +1,68 @@
import { execFile } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
const execute = promisify(execFile);
it.each([
{ protocol: "native", flags: [], required: true },
{
protocol: "native",
flags: ["--second-procedure", "other", "--second-marker", "unique"],
required: false,
},
{ protocol: "legacy", flags: [], required: false },
{ protocol: "modern", flags: [], required: false },
])(
"enforces native switching requirements for $protocol with $flags",
async ({ protocol, flags, required }) => {
const root = await mkdtemp(join(tmpdir(), "rea-ida-verifier-options-"));
try {
const config = join(root, "ida.json");
await writeFile(
config,
JSON.stringify({
url: "http://127.0.0.1:13337/mcp",
mode: protocol === "modern" ? "headless" : "attached",
...(protocol === "native" ? { protocol } : {}),
}),
);
// The absent target stops accepted option sets at admission, before any provider call.
await expect(
execute(
process.execPath,
[
"scripts/verify-real-ida.mjs",
"--target",
join(root, "absent"),
...flags,
],
{
cwd: process.cwd(),
env: { ...process.env, REA_IDA_MCP_CONFIG: config },
timeout: 10_000,
},
),
).rejects.toMatchObject(
required
? {
stdout: "",
stderr: expect.stringContaining(
"Native IDA verification requires --second-procedure and --second-marker",
),
}
: {
stderr: "",
stdout: expect.stringContaining(
'"failed_phase": "target admission"',
),
},
);
} finally {
await rm(root, { recursive: true, force: true });
}
},
);
@@ -619,23 +619,31 @@ describe("native DMG artifact reader", () => {
expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]);
});
it("rejects non-zero verification results", async () => {
await expect(
createAttachedReader("/tmp/image.dmg", process.env, undefined, {
run: () =>
Promise.resolve({
stdout: "verify output",
stderr: "hdiutil: verify failed - image not recognized",
exitCode: 1,
}),
}),
).rejects.toMatchObject({
reason: "format",
message: expect.stringMatching(
/"arguments":\["verify","\/tmp\/image\.dmg"\].*"exitCode":1.*"stderr":"hdiutil: verify failed - image not recognized"/u,
),
});
});
// hdiutil localizes its diagnostics; en-GB and other English locales spell
// the refusal "recognised".
it.each(["recognized", "recognised"])(
"rejects non-zero verification results (image not %s)",
async (spelling) => {
await expect(
createAttachedReader("/tmp/image.dmg", process.env, undefined, {
run: () =>
Promise.resolve({
stdout: "verify output",
stderr: `hdiutil: verify failed - image not ${spelling}`,
exitCode: 1,
}),
}),
).rejects.toMatchObject({
reason: "format",
message: expect.stringMatching(
new RegExp(
`"arguments":\\["verify","/tmp/image\\.dmg"\\].*"exitCode":1.*"stderr":"hdiutil: verify failed - image not ${spelling}"`,
"u",
),
),
});
},
);
it("retains the root and reports unknown ownership when recovery discovery fails", async () => {
const mount = createMountFixture();
@@ -15,6 +15,7 @@ import {
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
import {
withSignatureTarget,
verifySignatureTarget,
@@ -277,6 +278,7 @@ it("returns typed cancellation at binding entry and final verification", async (
await expect(
withSignatureTarget(
target,
new ArtifactResourceScope(),
async () => {
throw new Error("Cancelled acquisition must not invoke inspection");
},
@@ -286,14 +288,18 @@ it("returns typed cancellation at binding entry and final verification", async (
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
await withSignatureTarget(target, async (binding) => {
const result = await verifySignatureTarget(target, binding, signal);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
return result;
});
await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
const result = await verifySignatureTarget(target, binding, signal);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
return result;
},
);
});
it("preserves cancellation after a capture instead of classifying it as invalid output", async () => {
@@ -348,21 +354,31 @@ it("copies and hashes the same bytes across multiple snapshot chunks", async ()
const bytes = Buffer.alloc(128 * 1024 + 13, 42);
await writeFile(path, bytes);
const target = await nativeMachoTargetForFile(path);
await withSignatureTarget(target, async (binding) => {
expect(await readFile(binding.snapshotPath)).toEqual(bytes);
return verifySignatureTarget(target, binding);
});
await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
expect(await readFile(binding.snapshotPath)).toEqual(bytes);
return verifySignatureTarget(target, binding);
},
);
});
it("cleans the private snapshot when inspection throws", async () => {
const { target } = await fixture();
let snapshotPath: string | undefined;
await expect(
withSignatureTarget(target, async (binding) => {
const result = await withSignatureTarget(
target,
new ArtifactResourceScope(),
async (binding) => {
snapshotPath = binding.snapshotPath;
throw new Error("Invalid parsed output");
}),
).rejects.toThrow("Invalid parsed output");
},
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
if (snapshotPath === undefined) throw new Error("Expected snapshot");
await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({
code: "ENOENT",