feat(ghidra): add private headless provider session

This commit is contained in:
N0zoM1z0
2026-07-16 01:27:54 +09:00
committed by N0zoM1z0
parent ed17e76473
commit f0e625d7ee
234 changed files with 8968 additions and 513 deletions
+30
View File
@@ -53,6 +53,36 @@ describe("CdpBrowserProvider", () => {
expect(JSON.stringify(result.value)).not.toContain("page-secret");
});
it("sanitizes URL-shaped transitional target titles", async () => {
const browser = await startFakeCdpBrowser({
urlShapedAllowedTitle: true,
});
browsers.push(browser);
const provider = new CdpBrowserProvider();
const input = {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
approved: true as const,
target_id: "allowed-page",
};
const listed = await provider.listTargets(
listBrowserTargetsInputSchema.parse(input),
);
if (!listed.ok) throw listed.error;
expect(listed.value.targets.items[0]?.title).toBe(
`${browser.allowedOrigin}/app?startup=%5BREDACTED%5D`,
);
const inspected = await provider.inspectPage(
inspectWebPageInputSchema.parse({ ...input, observation_ms: 0 }),
);
if (!inspected.ok) throw inspected.error;
expect(inspected.value.target.title).toBe(
`${browser.allowedOrigin}/app?startup=%5BREDACTED%5D`,
);
expect(JSON.stringify({ listed, inspected })).not.toContain("title-secret");
});
it("uses page-scoped discovery sockets as direct target transports", async () => {
const browser = await startFakeCdpBrowser({
pageScopedVersionWebSocket: true,
+19
View File
@@ -51,6 +51,25 @@ describe("runtime configuration", () => {
expect(parseConfig({ REA_ANALYSIS_PROVIDER: invalid }).ok).toBe(false);
});
it("parses absolute BYO Ghidra and optional Java paths", () => {
expect(
parseConfig({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
}),
).toMatchObject({
ok: true,
value: {
ghidraInstallDir: "/opt/ghidra_12.1.2_PUBLIC",
ghidraJavaHome: "/usr/lib/jvm/jdk-21",
},
});
expect(parseConfig({ GHIDRA_INSTALL_DIR: "relative/ghidra" }).ok).toBe(
false,
);
expect(parseConfig({ JAVA_HOME: "relative/jdk" }).ok).toBe(false);
});
it("builds a separate Electron endpoint and file-root ceiling", () => {
const result = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
+1 -1
View File
@@ -54,7 +54,7 @@ describe("direct analysis snapshot permissions", () => {
details: {
selection_reason: "unknown_provider",
requested_provider_id: "request-provider",
candidate_ids: ["hopper"],
candidate_ids: ["ghidra", "hopper"],
},
});
});
+20
View File
@@ -43,6 +43,26 @@ describe("analysis error projection", () => {
);
});
it("projects bounded provider diagnostics without dropping local coordinates", () => {
const diagnostics = {
runtime_root: "/tmp/rea-ghidra-fixture",
profile_digest: "a".repeat(64),
exit_code: 1,
};
const error = new ProviderAdapterError("ghidra", "health", {
diagnostics,
});
expect(error.diagnostics).not.toBe(diagnostics);
expect(projectAnalysisError(error)).toMatchObject({
details: {
provider_id: "ghidra",
operation: "health",
diagnostics,
},
});
});
it("projects stable, safe Linux startup failure codes", () => {
const expected = [
[70, "private_display_unavailable"],
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env node
import { readFile, stat, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
const arguments_ = process.argv.slice(2);
const descriptorPath = arguments_.at(-1);
if (descriptorPath === undefined) process.exit(64);
const descriptor = JSON.parse(await readFile(descriptorPath, "utf8"));
const runtimeRoot = dirname(descriptorPath);
await writeFile(
join(runtimeRoot, "launch-capture.json"),
`${JSON.stringify({
arguments: arguments_,
environment: {
HOME: process.env.HOME,
TMPDIR: process.env.TMPDIR,
XDG_CACHE_HOME: process.env.XDG_CACHE_HOME,
XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
XDG_DATA_HOME: process.env.XDG_DATA_HOME,
GHIDRA_HEADLESS_MAXMEM: process.env.GHIDRA_HEADLESS_MAXMEM,
GHIDRA_HEADLESS_JAVA_OPTIONS: process.env.GHIDRA_HEADLESS_JAVA_OPTIONS,
GHIDRA_JAVA_OPTIONS: process.env.GHIDRA_JAVA_OPTIONS,
JAVA_TOOL_OPTIONS: process.env.JAVA_TOOL_OPTIONS,
JDK_JAVA_OPTIONS: process.env.JDK_JAVA_OPTIONS,
_JAVA_OPTIONS: process.env._JAVA_OPTIONS,
JAVA_HOME: process.env.JAVA_HOME,
PATH: process.env.PATH,
REA_PROCESS_RUN_ID: process.env.REA_PROCESS_RUN_ID,
},
descriptor_mode: (await stat(descriptorPath)).mode & 0o777,
descriptor_has_token: typeof descriptor.token === "string",
})}\n`,
{ mode: 0o600 },
);
setInterval(() => undefined, 1_000);
+5 -1
View File
@@ -62,6 +62,7 @@ interface FakeOptions {
readonly webMcpChildLeavesScope?: boolean;
readonly electronFileUrl?: string;
readonly duplicateElectronInventory?: boolean;
readonly urlShapedAllowedTitle?: boolean;
}
/** Start a real HTTP/WebSocket fake at the same seams as a user-owned browser. */
@@ -225,7 +226,10 @@ const targets = (
{
id: "allowed-page",
type: "page",
title: "Inspectable application",
title:
options.urlShapedAllowedTitle === true
? `http://127.0.0.1:${String(port)}/app?startup=title-secret#fragment`
: "Inspectable application",
url: `http://127.0.0.1:${String(port)}/app?token=page-secret#fragment`,
attached: false,
...(options.omitTargetWebSocket === true
+128
View File
@@ -0,0 +1,128 @@
import { rm } from "node:fs/promises";
import { createServer } from "node:net";
const [
socketPath,
token,
runId,
providerVersion,
profileDigest,
mode = "success",
] = process.argv.slice(2);
if (
socketPath === undefined ||
token === undefined ||
runId === undefined ||
providerVersion === undefined ||
profileDigest === undefined
) {
process.exit(64);
}
if (mode === "exit") process.exit(73);
if (mode === "silent") setInterval(() => undefined, 1_000);
else {
await rm(socketPath, { force: true });
const server = createServer((socket) => {
socket.setEncoding("utf8");
let buffer = "";
let pings = 0;
socket.on("data", (chunk) => {
buffer += chunk;
let newline = buffer.indexOf("\n");
while (newline >= 0) {
const line = buffer.slice(0, newline);
buffer = buffer.slice(newline + 1);
newline = buffer.indexOf("\n");
const request = JSON.parse(line);
if (request.token !== token) {
socket.end(
`${JSON.stringify({
id: request.id,
ok: false,
error: { code: "auth", message: "Authentication failed" },
})}\n`,
);
continue;
}
if (request.method === "ping") {
pings += 1;
if (mode === "malformed") {
socket.write("{invalid\n");
continue;
}
if (mode === "contradictory") {
socket.write(
`${JSON.stringify({
id: request.id,
ok: false,
result: { unexpected: true },
error: { code: "failure", message: "Failed" },
})}\n`,
);
continue;
}
if (mode === "oversized_whitespace") {
socket.write(`${" ".repeat(1024 * 1024 + 1)}\n`);
continue;
}
if (mode === "future_id") {
socket.write(
`${JSON.stringify({ id: request.id + 10, ok: true, result: null })}\n`,
);
continue;
}
if (mode === "hang_after_start" && pings > 1) continue;
const result = sessionInfo({
runId,
providerVersion:
mode === "wrong_identity" ? "0.0.0" : providerVersion,
profileDigest,
timedOut: mode === "analysis_timeout",
});
const response = `${JSON.stringify({ id: request.id, ok: true, result })}\n`;
if (mode === "fragmented") {
const split = Math.floor(response.length / 2);
socket.write(response.slice(0, split));
setTimeout(() => socket.write(response.slice(split)), 5);
} else socket.write(response);
continue;
}
if (request.method === "shutdown") {
socket.end(
`${JSON.stringify({
id: request.id,
ok: true,
result: { shutdown: true, project_ephemeral: true },
})}\n`,
);
server.close(() => process.exit(0));
}
}
});
});
server.listen(socketPath);
}
const sessionInfo = ({
runId: sessionRunId,
providerVersion: version,
profileDigest: digest,
timedOut,
}) => ({
name: "REA Ghidra bridge",
bridge_version: 1,
run_id: sessionRunId,
profile_digest: digest,
provider: { id: "ghidra", version },
read_only: true,
analysis_complete: !timedOut,
analysis_timed_out: timedOut,
capabilities: ["ping", "shutdown"],
target: {
name: "fixture",
language_id: "x86:LE:64:default",
compiler_spec_id: "gcc",
},
});
+243
View File
@@ -0,0 +1,243 @@
import { spawn, type ChildProcess } from "node:child_process";
import { getEventListeners } from "node:events";
import { access, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { ok } from "../src/domain/result.js";
import {
GhidraClient,
type GhidraDiagnostic,
} from "../src/ghidra/GhidraClient.js";
import type {
GhidraLaunchSession,
GhidraLauncher,
} from "../src/ghidra/GhidraLauncher.js";
const fixturePath = fileURLToPath(
new URL("./fixtures/fakeGhidra.mjs", import.meta.url),
);
const PROFILE_DIGEST = "a".repeat(64);
const PROVIDER_VERSION = "12.1.2";
type FixtureMode =
| "success"
| "fragmented"
| "wrong_identity"
| "malformed"
| "contradictory"
| "oversized_whitespace"
| "future_id"
| "analysis_timeout"
| "hang_after_start"
| "silent"
| "exit";
class FixtureLauncher implements GhidraLauncher {
readonly runtimeRoots: string[] = [];
readonly socketPaths: string[] = [];
readonly tokens: string[] = [];
readonly processes: ChildProcess[] = [];
constructor(readonly mode: FixtureMode = "success") {}
async launch(session: GhidraLaunchSession) {
this.runtimeRoots.push(session.runtimeRoot);
this.socketPaths.push(session.socketPath);
this.tokens.push(session.token);
const projectRoot = join(session.runtimeRoot, "project");
await mkdir(projectRoot, { recursive: true });
const process_ = spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
session.providerVersion,
session.profileDigest,
this.mode,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
this.processes.push(process_);
return ok({
process: process_,
ownsProcessLifetime: true,
projectRoot,
ghidraLogPath: join(session.runtimeRoot, "ghidra.log"),
scriptLogPath: join(session.runtimeRoot, "script.log"),
});
}
}
const clients: GhidraClient[] = [];
const clientFor = (
launcher: GhidraLauncher,
options: {
readonly startupTimeoutMs?: number;
readonly requestTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
} = {},
): GhidraClient => {
const client = new GhidraClient({
launcher,
targetPath: "/tmp/fixture",
providerVersion: PROVIDER_VERSION,
profileDigest: PROFILE_DIGEST,
startupTimeoutMs: options.startupTimeoutMs ?? 1_000,
requestTimeoutMs: options.requestTimeoutMs ?? 100,
...(options.onDiagnostic === undefined
? {}
: { onDiagnostic: options.onDiagnostic }),
});
clients.push(client);
return client;
};
afterEach(async () => {
await Promise.all(clients.splice(0).map((client) => client.close()));
});
describe("GhidraClient", () => {
it("completes an exact, fragmented post-analysis handshake", async () => {
const launcher = new FixtureLauncher("fragmented");
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({
ok: true,
value: {
provider: { id: "ghidra", version: PROVIDER_VERSION },
profile_digest: PROFILE_DIGEST,
read_only: true,
analysis_complete: true,
analysis_timed_out: false,
capabilities: ["ping", "shutdown"],
},
});
expect(Buffer.byteLength(launcher.socketPaths[0] ?? "")).toBeLessThan(108);
});
it.each([
["wrong_identity", "protocol"],
["malformed", "protocol"],
["contradictory", "protocol"],
["oversized_whitespace", "protocol"],
["future_id", "protocol"],
["analysis_timeout", "analysis_timeout"],
["exit", "process"],
] as const)("projects %s startup as %s", async (mode, expectedKind) => {
const client = clientFor(new FixtureLauncher(mode));
const result = await client.start();
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.kind).toBe(expectedKind);
});
it("applies one startup deadline and removes the private runtime", async () => {
const launcher = new FixtureLauncher("silent");
const client = clientFor(launcher, { startupTimeoutMs: 30 });
const result = await client.start();
expect(result).toMatchObject({
ok: false,
error: { kind: "timeout", timeoutMs: 30 },
});
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
expect(exited(launcher.processes[0])).toBe(true);
});
it("cancels startup promptly and leaves no project or process", async () => {
const launcher = new FixtureLauncher("silent");
const client = clientFor(launcher, { startupTimeoutMs: 10_000 });
const controller = new AbortController();
const pending = client.start(controller.signal);
setTimeout(() => controller.abort(), 10);
const result = await pending;
expect(result).toMatchObject({ ok: false, error: { kind: "cancelled" } });
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
expect(exited(launcher.processes[0])).toBe(true);
});
it("times out an established ping without corrupting shutdown", async () => {
const client = clientFor(new FixtureLauncher("hang_after_start"));
await expect(client.start()).resolves.toMatchObject({ ok: true });
await expect(client.ping({ timeoutMs: 5 })).resolves.toMatchObject({
ok: false,
error: { kind: "timeout", timeoutMs: 5 },
});
});
it("makes double close idempotent and detaches process listeners", async () => {
const launcher = new FixtureLauncher();
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({ ok: true });
await Promise.all([client.close(), client.close()]);
await client.close();
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
const process_ = launcher.processes[0];
expect(exited(process_)).toBe(true);
if (process_ === undefined)
throw new Error("Fixture process was not captured");
expect(getEventListeners(process_, "exit")).toHaveLength(0);
expect(getEventListeners(process_, "close")).toHaveLength(0);
expect(getEventListeners(process_, "error")).toHaveLength(0);
expect(process_.stdout).not.toBeNull();
if (process_.stdout !== null)
expect(getEventListeners(process_.stdout, "data")).toHaveLength(0);
});
it("retains actionable runtime coordinates after successful cleanup", async () => {
const launcher = new FixtureLauncher();
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({ ok: true });
await client.close();
expect(client.diagnostics()).toMatchObject({
runtime_root: launcher.runtimeRoots[0],
socket_path: launcher.socketPaths[0],
project_root: join(launcher.runtimeRoots[0] ?? "", "project"),
process_id: expect.any(Number),
});
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("retains actionable diagnostics without retaining its token", async () => {
const launcher = new FixtureLauncher("exit");
const events: GhidraDiagnostic[] = [];
const client = clientFor(launcher, {
onDiagnostic: (event) => events.push(event),
});
const result = await client.start();
expect(result.ok).toBe(false);
if (result.ok) return;
const encoded = JSON.stringify(result.error.diagnostics);
expect(encoded).toContain("/tmp/fixture");
expect(encoded).toContain(PROFILE_DIGEST);
expect(encoded).not.toContain(launcher.tokens[0] ?? "missing-token");
expect(events).toContainEqual(
expect.objectContaining({ type: "launcher-exit" }),
);
});
});
const exited = (process_: ChildProcess | undefined): boolean =>
process_ !== undefined &&
(process_.exitCode !== null || process_.signalCode !== null);
+152
View File
@@ -0,0 +1,152 @@
import { describe, expect, it } from "vitest";
import { runDoctor, type DoctorHost } from "../src/application/Doctor.js";
import {
inspectGhidraInstallation,
type GhidraInstallationHost,
type GhidraInstallationInspection,
} from "../src/ghidra/GhidraInstallation.js";
import { projectGhidraDoctorInspection } from "../src/ghidra/GhidraDoctor.js";
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
const installationHost = (
overrides: Partial<GhidraInstallationHost> = {},
): GhidraInstallationHost => ({
readText: () => "application.version=12.1.2\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
jdk: true,
}),
...overrides,
});
const inspection = (
options: {
readonly installDir?: string;
readonly architecture?: NodeJS.Architecture;
} = { installDir: INSTALL },
overrides: Partial<GhidraInstallationHost> = {},
): GhidraInstallationInspection =>
inspectGhidraInstallation(
{
platform: "linux",
architecture: options.architecture ?? "x64",
...(options.installDir === undefined
? {}
: { installDir: options.installDir }),
},
installationHost(overrides),
);
const doctorHost = (
ghidra: GhidraInstallationInspection,
hopperAvailable = false,
): DoctorHost => ({
platform: "linux",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
validTarget: () => Promise.resolve(true),
executable: (path) =>
Promise.resolve(hopperAvailable && path.includes("Hopper")),
supportedLinuxHopper: () => Promise.resolve(true),
linuxDemoRuntimeReady: () => Promise.resolve(true),
brewHopperPath: () => Promise.resolve(undefined),
manualHopperPaths: () => Promise.resolve([]),
providerInspections: () =>
Promise.resolve([projectGhidraDoctorInspection(ghidra)]),
});
describe("Ghidra doctor integration", () => {
it("accepts a valid BYO Ghidra engine when Hopper is absent", async () => {
const result = await runDoctor(undefined, doctorHost(inspection()));
expect(result.healthy).toBe(true);
expect(result.hopperPath).toBeUndefined();
expect(result.providerInspections?.[0]).toMatchObject({
id: "ghidra",
available: true,
providerVersion: "12.1.2",
registrationEnvironment: {
GHIDRA_INSTALL_DIR: INSTALL,
JAVA_HOME: "/usr/lib/jvm/jdk-21",
},
});
expect(
result.checks.find(({ name }) => name === "ghidra-java"),
).toMatchObject({
ok: true,
detail: expect.stringContaining("21.0.11"),
});
});
it.each([
[
"bad installation",
inspection({ installDir: INSTALL }, { readText: () => undefined }),
"ghidra-installation",
],
[
"wrong version",
inspection(
{ installDir: INSTALL },
{ readText: () => "application.version=11.4\n" },
),
"ghidra-version",
],
[
"missing analyzeHeadless",
inspection({ installDir: INSTALL }, { executable: () => false }),
"ghidra-headless",
],
[
"wrong Java",
inspection(
{ installDir: INSTALL },
{
probeJava: () => ({
version: "17.0.12",
major: 17,
home: "/usr/lib/jvm/jdk-17",
bits: 64,
jdk: true,
}),
},
),
"ghidra-java",
],
[
"unsupported architecture",
inspection({ installDir: INSTALL, architecture: "arm64" }),
"ghidra-architecture",
],
] as const)("distinguishes %s", async (_label, ghidra, checkName) => {
const result = await runDoctor(undefined, doctorHost(ghidra, true));
expect(result.healthy).toBe(false);
expect(result.checks.find(({ name }) => name === checkName)).toMatchObject({
ok: false,
remediation: expect.any(String),
});
});
it("treats unconfigured Ghidra as optional when Hopper is healthy", async () => {
const result = await runDoctor(undefined, doctorHost(inspection({}), true));
expect(result.healthy).toBe(true);
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
ok: false,
classification: "missing_analysis_engine",
});
});
});
+174
View File
@@ -0,0 +1,174 @@
import { describe, expect, it } from "vitest";
import {
ghidraJavaEnvironment,
inspectGhidraInstallation,
SUPPORTED_GHIDRA_JAVA_MAJOR,
SUPPORTED_GHIDRA_VERSION,
type GhidraInstallationHost,
type GhidraJavaObservation,
} from "../src/ghidra/GhidraInstallation.js";
const INSTALL = "/opt/ghidra";
const PROPERTIES = `${INSTALL}/Ghidra/application.properties`;
const HEADLESS = `${INSTALL}/support/analyzeHeadless`;
const JAVA: GhidraJavaObservation = {
version: "21.0.11",
major: SUPPORTED_GHIDRA_JAVA_MAJOR,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
jdk: true,
};
const host = (
overrides: Partial<GhidraInstallationHost> = {},
): GhidraInstallationHost => ({
readText: (path) =>
path === PROPERTIES
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
: undefined,
executable: (path) => path === HEADLESS,
probeJava: () => JAVA,
...overrides,
});
describe("Ghidra installation inspection", () => {
it("clears inherited JVM option injection before probing Java", () => {
expect(
ghidraJavaEnvironment("/opt/jdk-21", {
PATH: "/usr/bin",
_JAVA_OPTIONS: "-Xmx99G",
JAVA_TOOL_OPTIONS: "-javaagent:/tmp/agent.jar",
JDK_JAVA_OPTIONS: "-XX:MaxRAMPercentage=99",
GHIDRA_JAVA_OPTIONS: "-Duser.home=/tmp/unapproved",
}),
).toMatchObject({
PATH: "/opt/jdk-21/bin:/usr/bin",
JAVA_HOME: "/opt/jdk-21",
_JAVA_OPTIONS: "",
JAVA_TOOL_OPTIONS: "",
JDK_JAVA_OPTIONS: "",
GHIDRA_JAVA_OPTIONS: "",
});
});
it("accepts only the exact Linux x64 Ghidra and JDK commitment", () => {
expect(
inspectGhidraInstallation(
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
host(),
),
).toMatchObject({
available: true,
providerVersion: SUPPORTED_GHIDRA_VERSION,
analyzeHeadlessPath: HEADLESS,
javaVersion: "21.0.11",
rejectionCode: null,
});
});
it.each([
{
name: "missing configuration",
options: { platform: "linux" as const, architecture: "x64" as const },
override: {},
failed: "configuration",
code: "not_configured",
},
{
name: "unsupported platform",
options: {
installDir: INSTALL,
platform: "darwin" as const,
architecture: "x64" as const,
},
override: {},
failed: "platform",
code: "unsupported_host",
},
{
name: "unsupported architecture",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "arm64" as const,
},
override: {},
failed: "architecture",
code: "unsupported_host",
},
{
name: "bad installation root",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { readText: () => undefined },
failed: "installation",
code: "executable_missing",
},
{
name: "wrong Ghidra version",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { readText: () => "application.version=11.4\n" },
failed: "version",
code: "unsupported_version",
},
{
name: "missing analyzeHeadless",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { executable: () => false },
failed: "headless",
code: "executable_missing",
},
{
name: "missing Java",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { probeJava: () => undefined },
failed: "java",
code: "runtime_missing",
},
{
name: "wrong Java",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { probeJava: () => ({ ...JAVA, major: 17, version: "17" }) },
failed: "java",
code: "unsupported_version",
},
{
name: "JRE instead of JDK",
options: {
installDir: INSTALL,
platform: "linux" as const,
architecture: "x64" as const,
},
override: { probeJava: () => ({ ...JAVA, jdk: false }) },
failed: "java",
code: "unsupported_version",
},
])("distinguishes $name", ({ options, override, failed, code }) => {
const result = inspectGhidraInstallation(options, host(override));
expect(result.available).toBe(false);
expect(result.checks.find(({ ok }) => !ok)).toMatchObject({
name: failed,
code,
});
});
});
+133
View File
@@ -0,0 +1,133 @@
import { access, chmod, mkdtemp, readFile, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
ghidraHeadlessArguments,
GhidraHeadlessLauncher,
} from "../src/ghidra/GhidraLauncher.js";
const fixturePath = fileURLToPath(
new URL("./fixtures/captureGhidraLaunch.mjs", import.meta.url),
);
const roots: string[] = [];
beforeAll(() => chmod(fixturePath, 0o755));
afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(
roots.splice(0).map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("Ghidra headless launcher", () => {
it("builds a bounded read-only import in deterministic order", () => {
expect(
ghidraHeadlessArguments({
projectRoot: "/tmp/project",
targetPath: "/tmp/target",
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
descriptorPath: "/tmp/session.json",
ghidraLogPath: "/tmp/ghidra.log",
scriptLogPath: "/tmp/script.log",
}),
).toEqual([
"/tmp/project",
"rea-project",
"-import",
"/tmp/target",
"-readOnly",
"-deleteProject",
"-analysisTimeoutPerFile",
"300",
"-max-cpu",
"2",
"-log",
"/tmp/ghidra.log",
"-scriptlog",
"/tmp/script.log",
"-scriptPath",
"/package/bridge",
"-postScript",
"ReaGhidraBridge.java",
"/tmp/session.json",
]);
});
it("keeps authority in a private descriptor and isolates Ghidra state", async () => {
vi.stubEnv("GHIDRA_JAVA_OPTIONS", "-javaagent:/unapproved/agent.jar");
vi.stubEnv("JAVA_TOOL_OPTIONS", "-Duser.home=/unapproved/home");
vi.stubEnv("JDK_JAVA_OPTIONS", "-XX:MaxRAMPercentage=99");
vi.stubEnv("_JAVA_OPTIONS", "-Xmx99G");
const runtimeRoot = await mkdtemp(join(tmpdir(), "rea-launcher-test-"));
roots.push(runtimeRoot);
const token = "secret-token-that-must-not-leak";
const launcher = new GhidraHeadlessLauncher({
analyzeHeadlessPath: fixturePath,
javaHome: "/opt/jdk-21",
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
});
const launched = await launcher.launch({
runtimeRoot,
socketPath: join(runtimeRoot, "bridge.sock"),
token,
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
targetPath: "/tmp/fixture",
providerVersion: "12.1.2",
profileDigest: "a".repeat(64),
});
expect(launched.ok).toBe(true);
if (!launched.ok) return;
const capturePath = join(runtimeRoot, "launch-capture.json");
await waitFor(capturePath);
const capture = JSON.parse(await readFile(capturePath, "utf8"));
const encodedArguments = JSON.stringify(capture.arguments);
const encodedEnvironment = JSON.stringify(capture.environment);
expect(encodedArguments).not.toContain(token);
expect(encodedEnvironment).not.toContain(token);
expect(capture).toMatchObject({
descriptor_mode: 0o600,
descriptor_has_token: true,
environment: {
HOME: join(runtimeRoot, "home"),
TMPDIR: join(runtimeRoot, "tmp"),
XDG_CACHE_HOME: join(runtimeRoot, "cache"),
XDG_CONFIG_HOME: join(runtimeRoot, "config"),
XDG_DATA_HOME: join(runtimeRoot, "data"),
GHIDRA_HEADLESS_MAXMEM: "2G",
GHIDRA_JAVA_OPTIONS: "",
JAVA_TOOL_OPTIONS: "",
JDK_JAVA_OPTIONS: "",
_JAVA_OPTIONS: "",
JAVA_HOME: "/opt/jdk-21",
REA_PROCESS_RUN_ID: "d6fcbb66-e829-4ff6-a535-0035aec63139",
},
});
expect(capture.environment.PATH).toMatch(/^\/opt\/jdk-21\/bin:/u);
expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).toContain(
`-Duser.home=${join(runtimeRoot, "home")}`,
);
expect((await stat(join(runtimeRoot, "ownership.json"))).mode & 0o777).toBe(
0o600,
);
const cleaned = await launched.value.cleanup?.();
expect(cleaned).toMatchObject({ cleaned: true });
await expect(access(join(runtimeRoot, "project"))).resolves.toBeUndefined();
});
});
const waitFor = async (path: string): Promise<void> => {
for (let attempt = 0; attempt < 100; attempt += 1) {
try {
await access(path);
return;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
throw new Error(`Timed out waiting for ${path}`);
};
+149
View File
@@ -0,0 +1,149 @@
import { describe, expect, it, vi } from "vitest";
import { parseConfig } from "../src/config.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_TOOL_CONTRACTS,
GhidraProvider,
} from "../src/ghidra/GhidraProvider.js";
import type { GhidraInstallationHost } from "../src/ghidra/GhidraInstallation.js";
import { silentLogger } from "../src/logger.js";
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
const installationHost = (): GhidraInstallationHost => ({
readText: () => "application.version=12.1.2\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
jdk: true,
}),
});
const provider = (host = installationHost()): GhidraProvider => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
if (!config.ok) throw config.error;
return new GhidraProvider(config.value, silentLogger, host);
};
describe("Ghidra provider", () => {
it("discovers the exact installation once without launching Ghidra", () => {
const host = installationHost();
const probe = vi.spyOn(host, "probeJava");
const ghidra = provider(host);
expect(ghidra.identity()).toEqual(GHIDRA_PROVIDER_IDENTITY);
expect(ghidra.capabilities()).toBe(GHIDRA_PROVIDER_TOOL_CONTRACTS);
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toEqual([]);
expect(Object.isFrozen(ghidra.capabilities())).toBe(true);
expect(ghidra.inspectAvailability()).toMatchObject({
status: "available",
diagnostics: {
install_dir: INSTALL,
provider_version: "12.1.2",
java_version: "21.0.11",
},
});
expect(ghidra.inspectAvailability()).toMatchObject({ status: "available" });
expect(probe).toHaveBeenCalledOnce();
});
it("separates target kind, format, and concrete architecture", () => {
const ghidra = provider();
expect(
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
).toMatchObject({
status: "supported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
).toMatchObject({
status: "supported",
});
expect(
ghidra.inspectTargetSupport({
...executableTarget("elf", "x86_64"),
kind: "archive",
format: "asar",
}),
).toMatchObject({
status: "unsupported",
code: "target_kind_unsupported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("javascript", "x86_64")),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(ghidra.inspectTargetSupport(executableTarget("elf"))).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
});
});
it("commits exact provider, isolation, and resource semantics", async () => {
const ghidra = provider();
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
expect(resolved.ok).toBe(true);
if (!resolved.ok || resolved.value.profile === null) return;
expect(resolved.value.profile).toMatchObject({
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
provider_profile_schema_version: 1,
parameters: {
import_mode: "ephemeral-read-only",
analyzer_preset: "ghidra-default",
analysis_timeout_seconds: 300,
max_cpu: 2,
max_heap: "2G",
},
});
expect(resolved.value.compatibility).toEqual({
languageId: "auto",
compilerSpecId: "auto",
});
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.execute("list_procedures", {});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "ghidra",
},
});
});
it("returns cancellation before profile work", async () => {
const controller = new AbortController();
controller.abort();
await expect(
provider().resolveAnalysisProfile(executableTarget("elf", "x86_64"), {
signal: controller.signal,
}),
).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
});
});
});
const executableTarget = (
format: BinaryTarget["format"],
architecture?: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
...(architecture === undefined
? {}
: { architecture, availableArchitectures: [architecture] }),
});
+7 -1
View File
@@ -19,6 +19,7 @@ import {
HOPPER_PROVIDER_IDENTITY,
HOPPER_PROVIDER_TOOL_CONTRACTS,
} from "../src/hopper/HopperProvider.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../src/ghidra/GhidraProvider.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../src/native/NativeMacOSProvider.js";
import {
assertDocumentationFacts,
@@ -57,6 +58,7 @@ describe("canonical product catalog", () => {
expect(catalog.providers.map(({ id }) => id).sort()).toEqual(
[
HOPPER_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
CDP_BROWSER_PROVIDER_IDENTITY,
@@ -69,6 +71,10 @@ describe("canonical product catalog", () => {
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual(HOPPER_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
expect(
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual([]);
expect(
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
).toMatchObject({
@@ -92,7 +98,7 @@ describe("canonical product catalog", () => {
assertDocumentationFacts(root, catalog),
).resolves.toBeUndefined();
await expect(documentationFactIssues(root, catalog)).resolves.toEqual([]);
});
}, 15_000);
it("uses the same primary command names as the actual Incur router", () => {
const inventory = createCliInventory(createCli());
+16 -2
View File
@@ -6,12 +6,13 @@ import { describe, expect, it } from "vitest";
import { parseConfig } from "../src/config.js";
import { HopperProvider } from "../src/hopper/HopperProvider.js";
import { GhidraProvider } from "../src/ghidra/GhidraProvider.js";
import { silentLogger } from "../src/logger.js";
const sourceRoot = new URL("../src/", import.meta.url);
describe("provider-neutral architecture", () => {
it("keeps Hopper imports behind its adapter and composition root", async () => {
it("keeps deep-provider imports behind adapters and the composition root", async () => {
const forbiddenRoots = ["domain", "contracts", "server", "application"];
const inspected = await Promise.all(
forbiddenRoots.map(async (root) => {
@@ -23,7 +24,7 @@ describe("provider-neutral architecture", () => {
if (root === "application" && file.endsWith("/runtime.ts"))
return undefined;
const source = await readFile(file, "utf8");
return /from\s+["'][^"']*\/hopper\//u.test(source)
return /from\s+["'][^"']*\/(?:hopper|ghidra)\//u.test(source)
? relative(fileURLToPath(sourceRoot), file)
: undefined;
}),
@@ -36,6 +37,19 @@ describe("provider-neutral architecture", () => {
expect(violations).toEqual([]);
});
it("publishes no speculative Ghidra binary capabilities", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
if (!config.ok) return;
const provider = new GhidraProvider(config.value, silentLogger, {
readText: () => undefined,
executable: () => false,
probeJava: () => undefined,
});
expect(provider.capabilities()).toEqual([]);
expect(Object.isFrozen(provider.capabilities())).toBe(true);
});
it("publishes deterministic immutable Hopper capability descriptors", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
+18
View File
@@ -254,6 +254,24 @@ describe("provider process lifecycle primitives", () => {
}
});
it("allows interpreter launchers to rely on parent and run-token identity", async () => {
const spawned = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: [processFixturePath, "graceful"],
runId: "provider-process-interpreter-run",
expectedCommand: null,
});
try {
expect(spawned.ownership).toMatchObject({
expectedParentPid: process.pid,
runId: "provider-process-interpreter-run",
});
expect(spawned.ownership).not.toHaveProperty("expectedCommand");
} finally {
await stopProviderProcessFixture(spawned.process);
}
});
it("rejects deterministic spawn failures without producing a process", async () => {
await expect(
spawnOwnedProviderProcess({
+1 -1
View File
@@ -83,5 +83,5 @@ describe("production stdio runtime", () => {
await client.close();
await transport.close();
}
});
}, 15_000);
});
+77 -3
View File
@@ -7,6 +7,7 @@ import {
type SetupHost,
type SetupOptions,
type SetupHopperInstallResult,
type SetupProviderEnvironment,
} from "../src/application/Setup.js";
import type { DoctorCheck } from "../src/application/Doctor.js";
import type { LinuxDistribution } from "../src/application/LinuxHopper.js";
@@ -17,6 +18,8 @@ class FakeSetupHost implements SetupHost {
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
hopper: string | undefined;
ghidra: string | undefined;
javaHome: string | undefined;
hopperInstallSucceeds = true;
skill: "installed" | "unchanged" | "failed" = "installed";
clients: readonly SetupClient[] = [];
@@ -26,6 +29,7 @@ class FakeSetupHost implements SetupHost {
configurations = 0;
skillInstalls = 0;
checkedHopperPaths: Array<string | undefined> = [];
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
doctorHealthy: boolean | undefined;
linuxDemoRuntimeMissing = false;
unsupportedHopperVersion = false;
@@ -39,6 +43,14 @@ class FakeSetupHost implements SetupHost {
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
Promise.resolve({
...(this.hopper === undefined
? {}
: { HOPPER_LAUNCHER_PATH: this.hopper }),
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
});
installHopper = (
replaceExisting: boolean,
): Promise<SetupHopperInstallResult> => {
@@ -62,17 +74,19 @@ class FakeSetupHost implements SetupHost {
Promise.resolve(this.clients);
configureClient = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
): Promise<ClientConfigurationResult> => {
this.configurations += 1;
this.configuredProviderEnvironments.push(providerEnvironment);
return Promise.resolve(
this.clientResults.get(client.name) ?? { status: "configured" },
);
};
clientNeedsConfigure = (
client: SetupClient,
hopperPath: string | undefined,
providerEnvironment: SetupProviderEnvironment,
): Promise<boolean> => {
this.checkedHopperPaths.push(hopperPath);
this.checkedHopperPaths.push(providerEnvironment.HOPPER_LAUNCHER_PATH);
return Promise.resolve(
this.clientResults.get(client.name)?.status !== "unchanged",
);
@@ -237,6 +251,42 @@ describe("setup workflow", () => {
expect(host.hopperInstalls).toBe(0);
});
it("plans and propagates BYO Ghidra without installing software", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const plan = await runSetup(options(false), host);
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
"configure_client",
]);
expect(plan.plannedActions[0]?.detail).toContain(
"GHIDRA_INSTALL_DIR=/opt/ghidra_12.1.2_PUBLIC",
);
expect(plan.plannedActions[0]?.detail).toContain(
"JAVA_HOME=/usr/lib/jvm/jdk-21",
);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
const applied = await runSetup(options(true), host);
expect(applied.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
it("reinstalls existing Hopper when explicitly requested", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
@@ -428,7 +478,31 @@ describe("setup workflow", () => {
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toBe(
"REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
);
});
it("configures BYO Ghidra on Linux outside Hopper's installer matrix", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
});
+27
View File
@@ -146,6 +146,33 @@ describe("JSON client configuration transaction", () => {
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
});
it("adds exact BYO Ghidra and Java paths without installing dependencies", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-setup-"));
const configPath = join(directory, "mcp.json");
const client = { name: "cursor", configPath };
const environment = {
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
};
expect(await configureJsonClient(client, environment)).toMatchObject({
status: "configured",
});
expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
mcpServers: {
rea: {
env: {
GHIDRA_INSTALL_DIR: environment.GHIDRA_INSTALL_DIR,
JAVA_HOME: environment.JAVA_HOME,
},
},
},
});
expect(await configureJsonClient(client, environment)).toEqual({
status: "unchanged",
});
});
it("refuses malformed existing JSON without overwriting it", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-setup-"));
const configPath = join(directory, "mcp.json");
+12 -2
View File
@@ -77,7 +77,11 @@ describe("agent lifecycle", () => {
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
"/Hopper Path",
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
@@ -85,10 +89,16 @@ describe("agent lifecycle", () => {
expect(configured).toContain('model = "gpt-5"');
expect(configured).toContain("[mcp_servers.rea]");
expect(configured).toContain('command = "rea"');
expect(configured).toContain('GHIDRA_INSTALL_DIR = "/opt/ghidra"');
expect(configured).toContain('JAVA_HOME = "/opt/jdk-21"');
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
"/Hopper Path",
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });