Files
rea/src/hopper/HopperRegexSearch.test.ts
T
6822ebe1f3 feat(ida): support the official Hex-Rays IDA MCP headlessly (#4813)
* feat(ida): support the official Hex-Rays IDA MCP headlessly

Hex-Rays IDA MCP serves database reads only through execute_python, so
REA rejected it as an upstream. A `hexrays` headless stdio registration
now leases a private idalib worker through open_database, answers the
existing database-supervisor reads with a fixed, packaged, read-only
query module, and releases the lease with close_database, verified by
list_databases.

Observations record execute_python, the query and the module digest.
Tool errors are typed so a completed rejection is distinguished from an
unknown outcome; an unconfirmed release is retried and a late lease on
the private input is adopted.

Validated IDA source and bridge tests, static checks, docs, and npm run
verify:ida on Linux x64 against x86-64 and AArch64 ELF fixtures.

* feat(ida): name the Hex-Rays registration for its catalog

A registration without `protocol` that reaches the official Hex-Rays
server failed with only the missing database-supervisor tools. Startup
profile failures now report the advertised catalog, and when it is the
Hex-Rays one the message and recovery name the `hexrays` registration.

Refs #1416

* docs(ida): state Hex-Rays prerequisites and upstream session traces

Upstream needs IDA 9.4 or later with idalib, Python 3.11 or later, uv
and Git. The profile does not analyze databases open in the IDA GUI, and
the server keeps its own session traces outside REA's workspace.

Refs #1416

* fix(ida): skip inline data when scanning Hex-Rays calls

The call scan decoded every head that FuncItems yields. Inline data such
as a jump table can decode as a call and refer to a function or import,
which reported false callees and call-graph edges. Skip non-code heads
before decoding, as disassembly already does.

Refs #1416

* fix(ida): retain Hex-Rays health reads in evidence

The identity and readiness reads around each operation kept only their
parsed result, dropping the bridge digest and any engine output. Keep
them whole as health_observations beside the parsed metadata, in both
successful and partial-failure Evidence.

Refs #1416

* test(ida): list the Hex-Rays bridge in package fixtures

The packed-bridge verifier has required bridge/ida/hexrays_queries.py
since the Hex-Rays profile landed, but three package tests still built
their member lists without it. The verifier stopped at that file, so 21
cases failed or asserted on the wrong omission.

Refs #1416

* feat(ida): open existing IDA databases through the Hex-Rays profile

A headless open re-ran auto-analysis from the input binary, discarding
the names, types and comments of an existing database and taking far
longer on large targets. Target admission now identifies IDA databases
by their IDA1/IDA2 signature, and the hexrays profile opens a private
copy of one; Hopper and the other IDA profiles reject them.

The copy is required, not incidental: idalib repacks a database when
its last lease is released, even without a save. A database reports
the input it was created from, so the session is bound to the opened
copy's idb_path, and health now reports the input SHA-256 it records.

Validated with resolver, provider and session tests, check:fast,
docs:check and test:changed, plus a real Hex-Rays MCP run against a
1.4 GB SC2 .i64 whose original file was left byte-identical.

Refs #1416

* fix(ida): verify the private workspace of a database target by idb_path

* test(ida): fix Hex-Rays health stand-ins and Windows path and runtime teardown

* refactor(ida): resolve the registration once for target support

* docs(ida): record the real Hex-Rays run on an existing .i64

* docs(ida): make the Hex-Rays registration example install-neutral

* chore: keep merge-hook formatting outside the IDA change

* fix(ida): retain live Hex-Rays databases this server does not lease

A list_databases row with instance_id null is a live owner, not a stopped
database. Mapping it to the supervisor's released-worker shape made cleanup
delete files another client still held. Unleased rows stay active, so the
private path must leave inventory before the workspace is removed.

Accept idat inventory rows, hash the query bridge with sha256Hex, and
complete databaseEngine on Hopper fixtures added on main.

* fix(ida): report uncapped Hex-Rays call graphs

* docs(ida): link to the Hex-Rays bridge on GitHub

* fix(ida): verify Hex-Rays worker identity and cleanup

* feat(ida): support Hex-Rays idat headless workers

Refs #12921

* fix(ida): retain workspace after ambiguous Hex-Rays startup

* fix(ida): preserve typed Hex-Rays call edges and deadlines

* test(ida): verify Hex-Rays cleanup with a peer lease

* test(ci): use project deadlines for the Cutter verifier

* test(ida): keep verifier cleanup fixtures scoped to mocked modules

* fix(ida): retain the worker backend in partial evidence

---------

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-20 17:58:27 -05:00

395 lines
12 KiB
TypeScript

import { expect, it, vi } from "vitest";
import { HopperRegexSearch } from "./HopperRegexSearch.js";
import {
hopperReplySchemas,
parseHopperReply,
} from "./HopperReplyContracts.js";
import { err, ok } from "../domain/result.js";
import {
AnalysisCapabilityUnavailableError,
OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import {
HopperRemoteError,
HopperTimeoutError,
HopperProcessError,
} from "./HopperErrors.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { parseConfig } from "../config/parseConfig.js";
import { silentLogger } from "../logger.js";
import { HopperClient } from "./HopperClient.js";
import { HopperProvider } from "./HopperProvider.js";
import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js";
const regexMatch = vi.hoisted(() => ({
afterSettle: undefined as (() => void) | undefined,
}));
vi.mock("../process/RegexMatcher.js", async (importOriginal) => {
const actual =
await importOriginal<typeof import("../process/RegexMatcher.js")>();
return {
...actual,
matchRegexValues: async (
request: Parameters<typeof actual.matchRegexValues>[0],
) => {
const result = await actual.matchRegexValues(request);
regexMatch.afterSettle?.();
return result;
},
};
});
it.each(["search_strings", "search_procedures"] as const)(
"preserves selected source metadata through the provider's %s regex boundary",
async (operation) => {
const config = parseConfig({});
if (!config.ok) throw config.error;
const metadata =
operation === "search_strings"
? {
provider_value: "short display",
string: {
encoding: "utf-8",
encoding_status: "observed",
termination: "present_or_not_required",
byte_length: 7,
},
}
: {
procedure: { external: false, thunk: true, thunk_target: "0x2" },
};
const selected = {
address: "0x1",
value: "matched",
...metadata,
provider_metadata: { empty: "", absent: null, zero: 0, flag: false },
};
const source = [
{ address: "0x1", value: "different" },
selected,
{ ...selected, value: "matched alternative" },
];
const originalSource = structuredClone(source);
const callTool = vi
.spyOn(HopperClient.prototype, "callTool")
.mockResolvedValue(ok(source));
const provider = new HopperProvider(
config.value,
silentLogger,
{},
"linux",
);
const client = provider.createClient({
path: "/tmp/fixture.hop",
sha256: "a".repeat(64),
kind: "database",
format: "analysis-database",
databaseEngine: "hopper",
});
try {
const result = await client.execute(operation, {
pattern: "^matched$",
mode: "regex",
case_sensitive: true,
});
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result).toEqual([originalSource[1]]);
expect(callTool).toHaveBeenCalledOnce();
expect(callTool.mock.calls[0]?.[0]).toBe(
operation === "search_strings" ? "list_strings" : "list_procedures",
);
expect(source).toEqual(originalSource);
} finally {
await client.close();
callTool.mockRestore();
}
},
);
it.each(["search_strings", "search_procedures"] as const)(
"rejects malformed canonical metadata in the %s inventory",
async (operation) => {
// The client validates each reply against its method contract.
const search = new HopperRegexSearch({
callTool: async (method, _arguments, options) =>
parseHopperReply(
hopperReplySchemas,
method,
[
{
address: "0x1",
value: "matched",
...(operation === "search_strings"
? { string: { encoding: false } }
: { procedure: { external: "unknown" } }),
},
],
options?.operation ?? method,
),
});
try {
expect(
await search.execute(operation, {
pattern: "matched",
mode: "regex",
case_sensitive: true,
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError", operation },
});
} finally {
await search.close();
}
},
);
it.each(
(["search_strings", "search_procedures"] as const).flatMap((operation) =>
(["remote", "capability", "timeout", "process"] as const).map((family) => ({
operation,
family,
})),
),
)(
"attributes $family inventory failure to accepted $operation with live cleanup",
async ({ operation, family }) => {
const inventory =
operation === "search_strings" ? "list_strings" : "list_procedures";
const diagnostics = {
provider_request: { operation: inventory, request_id: 17 },
};
const context = {
diagnostics,
cleanup: {
reason: "controlled close refusal",
resources: ["exact-owner"],
},
capturedOutput: {
stdout: "retained stdout",
stderr: "retained stderr",
truncated: false,
},
};
const original = {
remote: () =>
new HopperRemoteError(-32000, "fixture inventory unavailable", {
...context,
operation: inventory,
requestId: 17,
diagnosticType: "bridge_exception",
}),
capability: () =>
new AnalysisCapabilityUnavailableError(
"hopper",
inventory,
"fixture API unavailable",
context,
),
timeout: () =>
new HopperTimeoutError(
42,
inventory,
17,
"busy",
"analysis",
undefined,
context,
),
process: () =>
new HopperProcessError(7, {
...context,
operation: inventory,
requestId: 17,
providerState: "exited",
stage: "analysis",
}),
}[family]();
const search = new HopperRegexSearch({
callTool: async (name) => {
expect(name).toBe(inventory);
return err(original);
},
});
try {
const result = await search.execute(operation, {
pattern: "fixture",
mode: "regex",
case_sensitive: false,
});
if (result.ok) throw new Error("Expected inventory failure");
expect(projectAnalysisError(result.error).details).toMatchObject({
operation,
});
expect(result.error._tag).toBe(original._tag);
if (original instanceof AnalysisCapabilityUnavailableError)
expect(result.error.diagnostics).toEqual(diagnostics);
else
expect(result.error.diagnostics).toMatchObject({
provider_request: { operation: inventory, request_id: 17 },
provider_diagnostics: diagnostics,
});
expect(result.error.capturedOutput).toEqual(context.capturedOutput);
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual(["exact-owner"]);
if (result.error instanceof HopperRemoteError)
expect(result.error).toMatchObject({
code: -32000,
safeMessage: "fixture inventory unavailable",
diagnosticType: "bridge_exception",
requestId: 17,
});
if (result.error instanceof HopperTimeoutError)
expect(result.error).toMatchObject({
timeoutMs: 42,
requestId: 17,
providerState: "busy",
stage: "analysis",
});
if (result.error instanceof HopperProcessError)
expect(result.error).toMatchObject({
exitCode: 7,
requestId: 17,
providerState: "exited",
stage: "analysis",
});
expect(original.operation).toBe(inventory);
releaseOwnedCleanup(original);
expect(result.error.cleanupIncomplete).toBe(false);
} finally {
await search.close();
}
},
);
it.each([false, true])(
"joins an active search on close and preserves earlier caller cancellation: %s",
async (callerFirst) => {
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const controller = new AbortController();
const search = new HopperRegexSearch({
callTool: async () => {
await gate;
return ok([]);
},
});
const pending = search.execute(
"search_strings",
{ pattern: "fixture", mode: "regex", case_sensitive: false },
{ signal: controller.signal },
);
if (callerFirst) controller.abort("caller stopped");
let finished = false;
const closing = search.close().then(() => {
finished = true;
});
await Promise.resolve();
expect(finished).toBe(false);
release();
expect(await pending).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
cause: callerFirst ? "caller stopped" : OwnerCancellation.ownerClosed,
},
});
await closing;
expect(finished).toBe(true);
},
);
it.each(
[null, "caller stopped", { requested: "stop" }].flatMap((reason) =>
(["inventory", "progress"] as const).map((stage) => ({ reason, stage })),
),
)(
"keeps the exact reason at $stage completion cancellation",
async ({ reason, stage }) => {
const controller = new AbortController();
const search = new HopperRegexSearch({
callTool: async () => {
if (stage === "inventory") controller.abort(reason);
return ok([]);
},
});
try {
expect(
await search.execute(
"search_strings",
{ pattern: "fixture", mode: "regex", case_sensitive: false },
{
signal: controller.signal,
progress: {
report: async () => {
if (stage === "progress") controller.abort(reason);
},
},
},
),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cause: reason },
});
} finally {
await search.close();
}
},
);
it("preserves an inventory failure when cancellation arrives after the physical outcome", async () => {
const controller = new AbortController();
const failure = new HopperRemoteError(-32000, "inventory failed", {
operation: "list_strings",
requestId: 17,
diagnosticType: "bridge_exception",
});
const search = new HopperRegexSearch({
callTool: async () => {
controller.abort("late cancellation");
return err(failure);
},
});
try {
const result = await search.execute(
"search_strings",
{ pattern: "fixture", mode: "regex", case_sensitive: false },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "HopperRemoteError",
operation: "search_strings",
cause: failure,
},
});
} finally {
await search.close();
}
});
it("returns cancellation when the caller aborts after the regex worker settles", async () => {
const controller = new AbortController();
const reason = { request: "stop search" };
regexMatch.afterSettle = () => controller.abort(reason);
const search = new HopperRegexSearch({
callTool: async () => ok([{ address: "0x1000", value: "fixture" }]),
});
try {
const result = await search.execute(
"search_strings",
{ pattern: "fixture", mode: "regex", case_sensitive: false },
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(reason);
} finally {
regexMatch.afterSettle = undefined;
await search.close();
}
});