fix: reconcile captured main and owned findings for PR #1603

This commit is contained in:
morluto
2026-10-13 23:02:19 +08:00
433 changed files with 23739 additions and 3277 deletions
+10 -6
View File
@@ -180,14 +180,17 @@ describe("trace-dylib-resolution CLI", () => {
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
await symlink(outside, join(app, "Contents/Linked"), "dir");
for (const [root, reason, message] of [
["../outside", "invalid_format", "Use a normalized path"],
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
[
"Contents/Linked/Tool",
"invalid_value",
"resolves outside the analyzed root",
// Windows link text is outside the POSIX dyld path representation.
process.platform === "win32"
? "is not a regular file in the analyzed root"
: "resolves outside the analyzed root",
],
] as const) {
await expectRootInputError(cli, { app, root, reason, message });
@@ -378,7 +381,8 @@ cliTest(
},
);
describe.skipIf(process.getuid?.() === 0)(
// This permission fixture requires POSIX mode bits and a non-root caller.
describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
@@ -510,6 +514,8 @@ cliTest(
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64e",
"--json",
],
environment: ENVIRONMENT,
@@ -518,9 +524,7 @@ cliTest(
const trace = dylibResolutionResultSchema.parse(
parseEvidence(result.json).normalized_result,
);
expect(
trace.roots.filter(({ architecture }) => architecture === "arm64e"),
).toHaveLength(2);
expect(trace.roots).toHaveLength(2);
const environments = trace.findings
.filter(({ kind }) => kind === "dyld-environment-present")
.map(({ explanation }) =>
@@ -23,7 +23,7 @@ const analyze = async (cli: TestCli, extra = "") => {
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: result } = z
.object({
normalized_result: javascriptApplicationAnalysisResultSchema,
@@ -122,6 +122,190 @@ cliTest(
},
);
cliTest(
"traces a nested contextBridge member through a unique IPC channel",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-bridge-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain, clipboard } = require("electron");
ipcMain.handle("nested:write", (event, value) => clipboard.writeText(value));`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const paths = graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.entry_kind === "bridge-member",
);
expect(
paths.some(
(observation) => observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
paths.some(
(observation) => observation.properties.step_kind === "terminal",
),
).toBe(true);
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"nested:write",
]);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.paths.some((path) => path.contains_inference)).toBe(true);
},
);
cliTest(
"preserves exact bridge member segments through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-bridge-segments-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
const write = () => ipcRenderer.send("write");
contextBridge.exposeInMainWorld("desktop", {
"nested.write": write,
nested: { write },
__proto__: { inherited: write },
["__proto__"]: { own: write },
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("write", (event) => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap((node) =>
node.observations.filter(
(observation) =>
observation.properties.entry_kind === "bridge-member" &&
observation.properties.step_kind === "exposure",
),
);
const bridge = application.graph.nodes
.filter((node) => node.kind === "context-bridge-api")
.flatMap((node) => node.observations)
.find((observation) => observation.properties.api_key === "desktop");
expect(bridge?.properties.members).not.toContain("__proto__.inherited");
expect(bridge?.properties.members).toContain("__proto__.own");
const paths = observations.map(
(observation) => observation.properties.entry_path,
);
expect(paths).toEqual(
expect.arrayContaining([
["desktop", "nested.write"],
["desktop", "nested", "write"],
["desktop", "__proto__", "own"],
]),
);
expect(paths).not.toContainEqual(["desktop", "__proto__", "inherited"]);
const handlerPaths = application.graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) => observation.properties.entry_kind === "ipc-handler",
);
expect(handlerPaths.length).toBeGreaterThan(0);
expect(
handlerPaths.every(
(observation) => !("entry_path" in observation.properties),
),
).toBe(true);
},
);
cliTest(
"retains a nested bridge path when its IPC handler has no external terminal",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-return-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.handle("nested:write", (event, value) => value);`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
expect(
graph.nodes.some((node) =>
node.observations.some(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.step_kind === "exposure",
),
),
).toBe(true);
expect(
graph.edges.some(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
),
).toBe(false);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.graph?.nodes.length).toBeGreaterThan(1);
},
);
for (const surface of ["CLI", "stdio MCP"] as const) {
cliTest(
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
@@ -225,3 +409,89 @@ cliTest(
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
},
);
cliTest(
"keeps shallow bridge members when a sibling exceeds the nesting limit",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-deep-bridge-");
let deepMember = '() => e.ipcRenderer.send("deep:run")';
for (let index = 0; index < 129; index += 1)
deepMember = `{ level${index}: ${deepMember} }`;
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
e.contextBridge.exposeInMainWorld("desktop", {
deep: ${deepMember},
shallow: () => e.ipcRenderer.send("shallow:run")
});`,
"main.js": `const e=require("electron");
e.ipcMain.on("shallow:run", event => event.sender.copy());
e.ipcMain.on("deep:run", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"shallow:run",
]);
expect(
graph.nodes
.flatMap((node) => node.observations)
.some(
(observation) =>
observation.properties.entry === "desktop.shallow" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
},
);
cliTest(
"preserves empty bridge member segments in nested paths",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-electron-empty-bridge-key-",
);
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("desktop", {
"": { nested: { call: () => ipcRenderer.send("empty:key") } }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("empty:key", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap(
(node) => node.observations,
);
expect(
observations.some(
(observation) =>
observation.properties.entry === "desktop..nested.call" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
application.graph.edges
.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
)
.map((edge) => edge.properties.channel),
).toEqual(["empty:key"]);
},
);
@@ -0,0 +1,77 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
import { startHttpComparisonBrowser } from "../../fixtures/httpComparisonBrowser.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("CLI compares incomplete HTTP responses without inventing changes", async () => {
const root = await createTestTempDirectory("rea-http-comparison-");
const response = {
requestId: "request-1",
status: 200,
mimeType: "application/json",
};
const fixture = await startHttpComparisonBrowser([response]);
try {
const inspect = async () =>
webPageInspectionSchema.parse(
parseEvidence(
await runCliJson([
"inspect-web-page",
fixture.browser.endpoint,
"allowed-page",
"--observation-ms",
"0",
"--json",
]),
).normalized_result,
);
const pending = await inspect();
fixture.setRequests([{ ...response, encodedDataLength: 100 }]);
const finished = await inspect();
fixture.setRequests([{ ...response, status: 500, encodedDataLength: 100 }]);
const changed = await inspect();
expect(pending.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: null },
]);
expect(finished.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: 100 },
]);
const paths = [pending, finished, changed].map((_, index) =>
join(root, `capture-${String(index)}.json`),
);
await Promise.all(
[pending, finished, changed].map((inspection, index) =>
writeFile(paths[index]!, JSON.stringify({ inspection })),
),
);
for (const [left, right, status, count] of [
[0, 1, "unknown", 0],
[1, 0, "unknown", 0],
[0, 2, "changed", 1],
] as const) {
const compared = await runCliJson([
"compare-web-captures",
paths[left]!,
paths[right]!,
"--json",
]);
expect(compared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
overall_status: status,
dimensions: {
network: { status, total_changes: count },
},
},
});
}
} finally {
await fixture.browser.close();
}
}, 60_000);
@@ -0,0 +1,93 @@
import { describe, expect } from "vitest";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
import { elf } from "../../../src/domain/binaryTarget.fixture.js";
/**
* A headless IDA supervisor that completes the MCP handshake and then leaves
* every tool call unanswered, as an `idb_open` still running auto-analysis
* would. It exits when REA closes its input.
*/
const UNRESPONSIVE_SUPERVISOR = `import { createInterface } from "node:readline";
const tools = ["idb_open", "idb_list", "idb_close", "server_health", "list_funcs",
"lookup_funcs", "find_regex", "decompile", "disasm", "callees", "xrefs_to"];
const send = (message) =>
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
for await (const line of createInterface({ input: process.stdin })) {
const request = JSON.parse(line);
if (request.method === "initialize")
send({ id: request.id, result: {
protocolVersion: request.params.protocolVersion,
capabilities: { tools: {} },
serverInfo: { name: "unresponsive-ida-fixture", version: "1" },
} });
else if (request.method === "tools/list")
send({ id: request.id, result: {
tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })),
} });
}
`;
describe("headless IDA timeout through the one-shot CLI", () => {
workspaceCliTest(
"exits after a retained-cleanup failure instead of waiting on the supervisor",
async ({ cli, workspace }) => {
const supervisor = await workspace.write(
"supervisor.mjs",
UNRESPONSIVE_SUPERVISOR,
);
const workspaceRoot = await workspace.mkdir("ida-workspaces");
const registration = await workspace.write(
"ida-mcp.json",
JSON.stringify({
command: process.execPath,
args: [supervisor],
mode: "headless",
timeoutMs: 500,
workspaceRoot,
}),
);
const target = await workspace.write("target.elf", elf(2, 1, 62));
const result = await cli.run({
arguments: ["decompile", target, "main", "--json"],
environment: {
...workspace.environment,
REA_ANALYSIS_PROVIDER: "ida",
REA_IDA_MCP_CONFIG: registration,
REA_LOG_LEVEL: "silent",
},
timeoutMs: 30_000,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "ida",
cleanup: "incomplete",
resources: [expect.stringContaining(workspaceRoot)],
cleanup_error: {
details: {
diagnostics: {
upstream_sessions: {
state: "unverified",
sessions: [
{
session_id: expect.stringMatching(/^rea-/),
backend: "worker",
owned: null,
input_path: null,
is_active: null,
},
],
},
},
},
},
},
});
},
);
});
+32
View File
@@ -561,3 +561,35 @@ describe("CLI result output surface", () => {
});
}, 60_000);
});
describe("streamed CLI filtered selections", () => {
it.each([
["raw_result", "json", "null\n"],
["raw_result", "jsonl", "null\n"],
["nested.value", "json", '{"nested":{"value":null}}\n'],
["missing", "json", "{}\n"],
["count", "json", "0\n"],
["enabled", "json", "false\n"],
] as const)(
"keeps the selected value of --filter-output %s in %s",
async (filter, format, expected) => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const output = createCliResultOutput(
["--format", format, "--filter-output", filter],
destination,
);
if (output === undefined) throw new Error("Missing JSON output surface");
await output.write(
{ raw_result: null, nested: { value: null }, count: 0, enabled: false },
{ command: "fixture", duration: "1ms", format },
);
expect(Buffer.concat(chunks).toString("utf8")).toBe(expected);
},
);
});
@@ -1,9 +1,13 @@
import { copyFile } from "node:fs/promises";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import {
inspectMachoSchema,
listArchitecturesSchema,
} from "../../../src/domain/native/nativeInspection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -34,27 +38,68 @@ const resultSchema = z.object({
describe.skipIf(process.platform !== "darwin")(
"native Mach-O CLI with echoed path text",
() => {
cliTest(
"does not read load commands or symbols from the file name",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-macho-echo-");
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile("/usr/bin/true", path);
const result = await cli.run({
arguments: ["inspect-macho", path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const forged = await inspect(FORGED_NAME);
expect(forged).toEqual(await inspect("tool"));
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
);
const lipoName = "tool\narchitecture forged\n offset 123\n size 32";
for (const [facts, command, filename] of [
["load commands or symbols", "inspect-macho", FORGED_NAME],
["FAT architecture records", "inspect-macho", lipoName],
["FAT architecture inventory", "list-architectures", lipoName],
["thin-file framing", "inspect-macho", "tool\nNon-fat file: forged"],
] as const) {
cliTest(
`does not read ${facts} from the file name`,
async ({ cli, processes }) => {
const directory = await createTestTempDirectory(
"rea-native-cli-echo-",
);
const fixture = join(directory, "fat-fixture");
const compiled = await processes.run(
"/usr/bin/xcrun",
[
"clang",
"-arch",
"arm64",
"-arch",
"x86_64",
resolve("tests/conformance/c/fixture.c"),
"-o",
fixture,
],
{ timeoutMs: 30_000 },
);
expect(compiled.exitCode, compiled.stderr).toBe(0);
const inspect = async (name: string) => {
const path = join(directory, name);
await copyFile(fixture, path);
const result = await cli.run({
arguments: [command, path, "--json"],
environment,
});
expect(result.exitCode).toBe(0);
const { provenance: _provenance, ...facts } = resultSchema.parse(
result.json,
).normalized_result;
return facts;
};
const ordinary = await inspect("tool");
// Prove this comparison exercised FAT framing, independent of host binaries.
const architectures =
listArchitecturesSchema.shape.architectures.parse(
ordinary.architectures,
);
expect(architectures.total).toBeGreaterThan(1);
if (command === "inspect-macho") {
const selected =
inspectMachoSchema.shape.selected_architecture.parse(
ordinary.selected_architecture,
);
expect(selected.container_file_offset).toBeGreaterThan(0);
}
const forged = await inspect(filename);
expect(forged).toEqual(ordinary);
expect(JSON.stringify(forged)).not.toMatch(/forged|4242/u);
},
60_000,
);
}
},
);
@@ -71,4 +71,27 @@ describe("native UI scenario CLI input", () => {
});
},
);
cliTest(
"refuses scenario steps on passive observation instead of dropping them",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"observe-native-ui",
"/provider-must-not-be-invoked",
"--pid",
"1",
"--window-id",
"1",
"--steps",
'[{"kind":"wait","milliseconds":0}]',
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.stdout).toContain("Unknown flag: --steps");
},
);
});
+30
View File
@@ -38,6 +38,36 @@ cliTest(
},
);
cliTest(
"rejects a 6502 image crossing the 16-bit boundary before provider startup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-6502-cli-overflow-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"6502",
"--entry-point",
"0xffff",
"--provider",
"ghidra",
"--json",
],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { reason: expect.stringContaining("6502 address width") },
});
},
);
cliTest(
"rejects an unaligned AArch64 entry before provider startup",
async ({ cli }) => {
@@ -1,3 +1,5 @@
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { describe, expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -62,3 +64,42 @@ describe("scenario CLI schema diagnostics", () => {
});
});
});
for (const field of [
"executable_path",
"application_path",
"application_root",
] as const) {
cliTest(`names the unresolved Electron ${field}`, async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-path-");
const missing = join(root, "missing");
const result = await cli.run({
arguments: [
"capture-electron-scenario",
JSON.stringify({
executable_path: process.execPath,
application_path: root,
application_root: root,
actions: [],
[field]: missing,
}),
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
},
],
},
});
expect(JSON.stringify(result.json)).toContain(missing);
});
}