refactor(test): keep coverage at behavioral boundaries (#474)

* refactor(test): keep coverage at behavioral boundaries

* fix(ci): restore package workflow temp-root classification
This commit is contained in:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
+183
View File
@@ -0,0 +1,183 @@
import { describe, expect, it } from "vitest";
import { runDoctor, type DoctorHost } from "../application/Doctor.js";
import { createDoctorHostFixture } from "../application/Doctor.fixture.js";
import {
inspectGhidraInstallation,
type GhidraInstallationHost,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import { projectGhidraDoctorInspection } from "./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,
runtime: "jdk",
}),
...overrides,
});
const inspection = (
options: {
readonly installDir?: string;
readonly architecture?: NodeJS.Architecture;
readonly platform?: NodeJS.Platform;
} = { installDir: INSTALL },
overrides: Partial<GhidraInstallationHost> = {},
): GhidraInstallationInspection =>
inspectGhidraInstallation(
{
platform: options.platform ?? "linux",
architecture: options.architecture ?? "x64",
...(options.installDir === undefined
? {}
: { installDir: options.installDir }),
},
installationHost(overrides),
);
const doctorHost = (
ghidra: GhidraInstallationInspection,
hopperAvailable = false,
): DoctorHost =>
createDoctorHostFixture({
platform: "linux",
architecture: "x64",
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),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: true,
classification: "healthy",
}),
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("accepts the experimental Windows x64 Ghidra provider boundary", async () => {
const ghidra = inspection({
installDir: "C:\\tools\\ghidra_12.1.2_PUBLIC",
platform: "win32",
});
const result = await runDoctor(undefined, {
...doctorHost(ghidra),
platform: "win32",
architecture: "x64",
linuxDistribution: () => Promise.resolve(undefined),
});
expect(result.healthy).toBe(true);
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
ok: true,
detail: "win32 x64",
});
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
ok: true,
});
});
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,
runtime: "jdk",
}),
},
),
"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",
});
});
});
+302
View File
@@ -0,0 +1,302 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../domain/jsonValue.js";
import {
GHIDRA_FUNCTION_OPERATIONS,
isGhidraFunctionOperation,
parseGhidraFunctionInput,
parseGhidraFunctionResult,
type GhidraFunctionOperation,
} from "./GhidraFunctionValues.js";
import {
ghidraBounded,
ghidraFunctionClassification,
ghidraFunctionDossier,
ghidraFunctionIdentity,
ghidraNativeApiBoundary,
ghidraReferenceEdge,
} from "../domain/hopperValues.fixture.js";
describe("Ghidra function-analysis boundary values", () => {
it("defaults bounded inputs and rejects undeclared or implicit addresses", () => {
expect(
parseGhidraFunctionInput("procedure_info", { procedure: "main" }),
).toEqual({
ok: true,
value: { document: null, procedure: "main" },
});
expect(
parseGhidraFunctionInput("procedure_references", { procedure: "main" }),
).toEqual({
ok: true,
value: {
document: null,
procedure: "main",
direction: "outgoing",
offset: 0,
limit: 100,
max_instructions: 500,
},
});
expect(
parseGhidraFunctionInput("analyze_function", { procedure: "main" }),
).toMatchObject({
ok: true,
value: {
procedure: "main",
include_assembly: false,
limit: 100,
max_pseudocode_chars: 20_000,
max_instructions: 500,
pseudocode_offset: 0,
assembly_offset: 0,
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
},
});
expect(
parseGhidraFunctionInput("read_function_instructions", {
procedure: "main",
}),
).toEqual({
ok: true,
value: {
document: null,
procedure: "main",
offset: 0,
limit: 64,
},
});
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(
parseGhidraFunctionInput("procedure_info", {
procedure: "main",
extra: true,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("keeps the admitted operation set closed", () => {
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(9);
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
expect(isGhidraFunctionOperation("read_function_instructions")).toBe(true);
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
});
});
describe("Ghidra function-analysis result values", () => {
it("parses provider-classified function facts and reference kinds", () => {
expect(
parseGhidraFunctionResult("read_function_instructions", {
procedure: ghidraFunctionIdentity(),
instructions: ghidraBounded(["0x401000: push rbp"]),
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
).toMatchObject({ ok: true });
expect(
parseGhidraFunctionResult("read_function_instructions", {
procedure: {
...ghidraFunctionIdentity(),
address: "0X401000",
},
instructions: ghidraBounded(["0x401000: push rbp"]),
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
expect(
parseGhidraFunctionResult("procedure_info", {
name: "fixture_main",
entrypoint: "0x401000",
basicblock_count: 1,
length: 6,
signature: "int fixture_main(void)",
locals: [
{
description: "int local @ Stack[-0x4]:4",
provenance: "ghidra-function-database",
},
],
classification: ghidraFunctionClassification(),
}),
).toMatchObject({ ok: true });
expect(
parseGhidraFunctionResult("procedure_references", {
procedure: ghidraFunctionIdentity(),
direction: "outgoing",
references: ghidraBounded([ghidraReferenceEdge()]),
instructions_scanned: 2,
instruction_scan_truncated: false,
}),
).toMatchObject({
ok: true,
value: {
references: {
items: [
{
kind: {
available: true,
provenance: "ghidra-reference-manager",
data: true,
},
},
],
},
},
});
expect(
parseGhidraFunctionResult("analyze_function", ghidraFunctionDossier()),
).toMatchObject({
ok: true,
value: {
native_api: {
available: true,
provenance: "ghidra-high-function",
return_type: {
data_type: "int",
confidence: "medium",
},
jump_tables: [
{
dispatch_address: "0x401010",
data_sources: [{ address: "0x403000" }],
mappings: [
{
target_address: "0x401020",
data_addresses: ["0x403000"],
},
],
},
],
pseudocode: {
classification: "decompiler-generated-non-source",
compilable: false,
},
},
},
});
});
it.each(malformedOutputs())(
"rejects malformed %s output",
(_name, operation, value) => {
expect(parseGhidraFunctionResult(operation, value)).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
},
);
});
const malformedOutputs = (): Array<
[string, GhidraFunctionOperation, JsonValue]
> => {
const dossier = ghidraFunctionDossier();
if (typeof dossier !== "object" || dossier === null || Array.isArray(dossier))
throw new TypeError("Ghidra dossier fixture is invalid");
const edge = ghidraReferenceEdge();
const nativeApi = ghidraNativeApiBoundary();
const jumpTable = nativeApi.jump_tables[0];
const mapping = jumpTable?.mappings[0];
if (jumpTable === undefined || mapping === undefined)
throw new TypeError("Ghidra native API fixture is invalid");
return [
["non-canonical address", "procedure_callers", ["401000"]],
[
"missing classification",
"procedure_info",
{
name: "main",
entrypoint: "0x401000",
basicblock_count: 1,
length: 1,
signature: null,
locals: [],
},
],
[
"unavailable Ghidra reference kind",
"procedure_references",
{
procedure: ghidraFunctionIdentity(),
direction: "outgoing",
references: ghidraBounded([
{ ...edge, kind: { available: false, reason: "unknown" } },
]),
instructions_scanned: 1,
instruction_scan_truncated: false,
},
],
[
"missing native API boundary",
"analyze_function",
Object.fromEntries(
Object.entries(dossier).filter(([key]) => key !== "native_api"),
),
],
[
"non-canonical native API target",
"analyze_function",
{
...dossier,
native_api: {
...nativeApi,
jump_tables: [
{
...jumpTable,
mappings: [
{
...mapping,
target_address: "401020",
},
],
},
],
},
},
],
[
"Hopper local provenance",
"analyze_function",
{
...dossier,
procedure: {
...ghidraFunctionIdentity(),
signature: null,
locals: [
{
description: "opaque",
provenance: "hopper-public-python-api",
},
],
},
},
],
[
"inconsistent dossier bound",
"analyze_function",
{
...dossier,
instruction_scan: { scanned: -1, truncated: false },
},
],
[
"missing uncertainty limitations",
"analyze_function",
{
...dossier,
limitations: [],
},
],
];
};
+223
View File
@@ -0,0 +1,223 @@
import { describe, expect, it } from "vitest";
import {
ghidraJavaEnvironment,
inspectGhidraInstallation,
SUPPORTED_GHIDRA_JAVA_MAJOR,
SUPPORTED_GHIDRA_VERSION,
type GhidraInstallationHost,
type GhidraJavaObservation,
} from "./GhidraInstallation.js";
const INSTALL = "/opt/ghidra";
const PROPERTIES = `${INSTALL}/Ghidra/application.properties`;
const HEADLESS = `${INSTALL}/support/analyzeHeadless`;
const WINDOWS_INSTALL = "C:\\tools\\ghidra_12.1.2_PUBLIC";
const WINDOWS_PROPERTIES = `${WINDOWS_INSTALL}\\Ghidra\\application.properties`;
const WINDOWS_HEADLESS = `${WINDOWS_INSTALL}\\support\\analyzeHeadless.bat`;
const JAVA: GhidraJavaObservation = {
version: "21.0.11",
major: SUPPORTED_GHIDRA_JAVA_MAJOR,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
runtime: "jdk",
};
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",
},
"linux",
),
).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({
status: "available",
providerVersion: SUPPORTED_GHIDRA_VERSION,
analyzeHeadlessPath: HEADLESS,
javaVersion: "21.0.11",
});
});
it("accepts the exact Windows x64 batch launcher and JDK commitment", () => {
const windowsHost: GhidraInstallationHost = {
platform: "win32",
architecture: "x64",
readText: (path) =>
path === WINDOWS_PROPERTIES
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
: undefined,
executable: (path) => path === WINDOWS_HEADLESS,
probeJava: (command, environment) => {
expect(command).toBe("C:\\Java\\jdk-21\\bin\\java.exe");
expect(environment.PATH).toMatch(/^C:\\Java\\jdk-21\\bin;/u);
return {
...JAVA,
home: "C:\\Java\\jdk-21",
};
},
};
expect(
inspectGhidraInstallation(
{
installDir: WINDOWS_INSTALL,
javaHome: "C:\\Java\\jdk-21",
platform: "win32",
architecture: "x64",
},
windowsHost,
),
).toMatchObject({
status: "available",
platform: "win32",
architecture: "x64",
analyzeHeadlessPath: WINDOWS_HEADLESS,
javaCommand: "C:\\Java\\jdk-21\\bin\\java.exe",
providerVersion: SUPPORTED_GHIDRA_VERSION,
});
});
});
describe("Ghidra installation rejection diagnostics", () => {
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, runtime: "jre" as const }) },
failed: "java",
code: "unsupported_version",
},
])("distinguishes $name", ({ options, override, failed, code }) => {
const result = inspectGhidraInstallation(options, host(override));
expect(result.status).toBe("unavailable");
expect(
result.checks.find(({ status }) => status === "failed"),
).toMatchObject({
name: failed,
code,
});
});
});
+232
View File
@@ -0,0 +1,232 @@
import { describe, expect, it } from "vitest";
import {
GHIDRA_INVENTORY_OPERATIONS,
isGhidraInventoryOperation,
parseGhidraInventoryInput,
parseGhidraInventoryResult,
type GhidraInventoryOperation,
} from "./GhidraInventoryValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
describe("Ghidra inventory boundary values", () => {
it("defaults bounded provider inputs without accepting undeclared fields", () => {
expect(parseGhidraInventoryInput("list_procedures", {})).toEqual({
ok: true,
value: { document: null, offset: 0, limit: 100 },
});
expect(
parseGhidraInventoryInput("search_strings", { pattern: "needle" }),
).toEqual({
ok: true,
value: {
pattern: "needle",
mode: "literal",
case_sensitive: false,
offset: 0,
limit: 100,
document: null,
},
});
expect(
parseGhidraInventoryInput("list_documents", { extra: true }),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(parseGhidraInventoryInput("address_name", {})).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(
parseGhidraInventoryInput("procedure_address", {
procedure: "x".repeat(4097),
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it("keeps the admitted operation set closed", () => {
expect(GHIDRA_INVENTORY_OPERATIONS).toHaveLength(10);
expect(isGhidraInventoryOperation("list_names")).toBe(true);
expect(isGhidraInventoryOperation("goto_address")).toBe(false);
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
});
it("parses primary, dynamic, and external symbol facts", () => {
const items = [
{
address: "EXTERNAL:0x1",
value: "libc::puts",
value_truncated: false,
symbol: {
primary: true,
dynamic: false,
external: true,
type: "function",
source: "imported",
},
},
{
address: "0x401000",
value: "LAB_00401000",
value_truncated: false,
symbol: {
primary: true,
dynamic: true,
external: false,
type: "label",
source: "default",
},
},
] satisfies readonly JsonValue[];
expect(parseGhidraInventoryResult("list_names", page(items))).toEqual({
ok: true,
value: page(items),
});
});
it("parses thunk, string-layout, and memory-permission observations", () => {
expect(
parseGhidraInventoryResult(
"list_procedures",
page([
{
address: "0x401020",
value: "puts",
value_truncated: false,
procedure: {
external: false,
thunk: true,
thunk_target: "EXTERNAL:0x1",
},
},
]),
),
).toMatchObject({ ok: true });
expect(
parseGhidraInventoryResult(
"list_strings",
page([
{
address: "0x402000",
value: "fixture",
value_truncated: false,
string: {
encoding: "UTF-8",
termination: "missing",
byte_length: 7,
},
},
]),
),
).toMatchObject({ ok: true });
expect(
parseGhidraInventoryResult("list_segments", [
{
name: ".text",
start: "0x401000",
end: "0x402000",
readable: true,
writable: false,
executable: true,
permissions: { available: true, source: "ghidra-memory-block" },
provenance: "ghidra-memory-block",
address_space: "ram",
image_base: "0x400000",
initialized: true,
overlay: false,
sections: [],
},
]),
).toMatchObject({ ok: true });
});
it.each(malformedOutputs())(
"rejects malformed %s output",
(_name, operation, value) => {
expect(parseGhidraInventoryResult(operation, value)).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
},
);
});
function malformedOutputs(): Array<
[string, GhidraInventoryOperation, JsonValue]
> {
return [
[
"non-canonical address",
"list_procedures",
page([
{
address: "00401000",
value: "main",
value_truncated: false,
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
]),
],
[
"missing external metadata",
"list_names",
page([{ address: "0x401000", value: "main", value_truncated: false }]),
],
[
"contradictory continuation",
"search_strings",
{
...page([]),
total: 1,
has_more: false,
next_offset: null,
},
],
[
"non-advancing continuation",
"list_procedures",
{
...page([]),
total: 1,
has_more: true,
next_offset: 0,
},
],
[
"items beyond exact total",
"list_procedures",
{ ...page([procedureItem()]), total: 0 },
],
["provider limit", "search_procedures", { ...page([]), limit: 101 }],
["multiple programs", "list_documents", ["first", "second"]],
];
}
function procedureItem(): JsonValue {
return {
address: "0x401000",
value: "main",
value_truncated: false,
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
};
}
function page(items: readonly JsonValue[]) {
return {
items: [...items],
offset: 0,
limit: 500,
total: items.length,
next_offset: null,
has_more: false,
};
}
+492
View File
@@ -0,0 +1,492 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../config.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_TOOL_CONTRACTS,
GhidraProvider,
type GhidraProviderClientFactory,
} from "./GhidraProvider.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
import { err, ok } from "../domain/result.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import { silentLogger } from "../logger.js";
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.2\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
runtime: "jdk",
}),
});
const provider = (
host = installationHost(),
clientFactory?: GhidraProviderClientFactory,
): GhidraProvider => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
if (!config.ok) throw config.error;
return new GhidraProvider(config.value, silentLogger, host, clientFactory);
};
describe("Ghidra provider", () => {
it("discovers the exact installation once without launching Ghidra", () => {
let probeCount = 0;
const host: GhidraInstallationHost = {
...installationHost(),
probeJava: () => {
probeCount += 1;
return {
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
runtime: "jdk",
};
},
};
const ghidra = provider(host);
expect(ghidra.identity()).toEqual(GHIDRA_PROVIDER_IDENTITY);
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(19);
expect(ghidra.capabilities()).toEqual(
expect.arrayContaining([
expect.objectContaining({
operation: "list_procedures",
pagination: "offset",
effects: expect.objectContaining({
mutatesArtifact: false,
mayShowUi: false,
mayWriteFilesystem: true,
}),
limits: {
maxResults: 500,
maxPayloadBytes: 1024 * 1024,
timeoutMs: 10_000,
},
}),
expect.objectContaining({
operation: "analyze_function",
pagination: "offset",
limits: {
maxResults: 500,
maxPayloadBytes: 1024 * 1024,
timeoutMs: 35_000,
},
limitations: expect.arrayContaining([
expect.stringContaining(
"unresolved targetless flows remain unknown",
),
]),
}),
]),
);
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(probeCount).toBe(1);
});
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({
path: "/tmp/fixture.asar",
sha256: "a".repeat(64),
kind: "archive",
format: "asar",
}),
).toMatchObject({
status: "unsupported",
code: "target_kind_unsupported",
});
expect(
ghidra.inspectTargetSupport({
path: "/tmp/fixture.js",
sha256: "a".repeat(64),
kind: "artifact",
format: "javascript",
}),
).toMatchObject({
status: "unsupported",
code: "target_kind_unsupported",
});
});
});
describe("Ghidra platform support", () => {
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
const ghidra = provider({ ...installationHost(), platform: "win32" });
const nativeApplication = peTarget("x86_64");
expect(ghidra.inspectTargetSupport(nativeApplication)).toMatchObject({
status: "supported",
diagnostics: {
host_platform: "win32",
executable_role: "application",
managed: false,
},
});
expect(ghidra.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "unsupported_host",
reason: expect.stringContaining("native authority is unavailable"),
diagnostics: {
windows_security: {
job_object_process_ownership: expect.objectContaining({
available: false,
proof: "not-proven",
}),
private_runtime_dacl: expect.objectContaining({
available: false,
proof: "not-proven",
}),
reparse_safe_path_admission: expect.objectContaining({
available: false,
proof: "not-proven",
}),
},
},
});
expect(ghidra.capabilities()).toEqual(
expect.arrayContaining([
expect.objectContaining({
operation: "list_procedures",
available: false,
availabilityCode: "unsupported_host",
limitations: expect.arrayContaining([
expect.stringContaining("bounded taskkill cleanup"),
expect.stringContaining("private DACL enforcement"),
]),
}),
]),
);
expect(
ghidra.inspectTargetSupport({
...nativeApplication,
executableRole: "shared-library",
}),
).toMatchObject({
status: "unsupported",
code: "target_role_unsupported",
});
expect(
ghidra.inspectTargetSupport({ ...nativeApplication, managed: true }),
).toMatchObject({
status: "unsupported",
code: "managed_target_unsupported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
).toMatchObject({
status: "unsupported",
code: "target_format_unsupported",
});
expect(
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
).toMatchObject({
status: "unsupported",
code: "architecture_unsupported",
});
});
});
describe("Ghidra client projection", () => {
it("commits exact provider, isolation, and resource semantics", async () => {
const toolCalls: Array<{
readonly operation: string;
readonly input: unknown;
readonly options: unknown;
}> = [];
let startCount = 0;
const factoryOptions: unknown[] = [];
const callTool: ReturnType<GhidraProviderClientFactory>["callTool"] = (
operation,
input,
options,
) => {
toolCalls.push({ operation, input, options });
return Promise.resolve(
ok({
items: [
{
address: "0x1000",
value: "fixture_main",
value_truncated: false,
procedure: {
external: false,
thunk: false,
thunk_target: null,
},
},
],
offset: 0,
limit: 100,
total: 1,
next_offset: null,
has_more: false,
}),
);
};
const clientFactory: GhidraProviderClientFactory = (options) => {
factoryOptions.push(options);
return {
start: () => {
startCount += 1;
return Promise.resolve(ok(sessionInfo()));
},
callTool,
close: () => Promise.resolve(),
};
};
const ghidra = provider(installationHost(), clientFactory);
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, {
runId: "11111111-1111-4111-8111-111111111111",
})
.execute("list_procedures", {});
expect(factoryOptions).toEqual([
expect.objectContaining({
runId: "11111111-1111-4111-8111-111111111111",
}),
]);
expect(toolCalls).toEqual([
{
operation: "list_procedures",
input: { document: null, offset: 0, limit: 100 },
options: {},
},
]);
expect(result).toMatchObject({
ok: true,
value: {
provider: {
id: "ghidra",
name: "Ghidra",
version: "12.1.2",
},
analysisProfile: resolved.value.profile,
result: {
items: [{ address: "0x1000", value: "fixture_main" }],
total: 1,
},
rawResult: {
items: [{ procedure: { external: false, thunk: false } }],
},
},
});
expect(startCount).toBe(0);
});
});
describe("Ghidra result projection", () => {
it("rejects malformed inventory output before Evidence creation", async () => {
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () => Promise.resolve(ok({ items: "not-a-page" })),
close: () => Promise.resolve(),
}));
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
await expect(
ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.execute("list_procedures", {}),
).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
});
it.each([
["invalid_request", "AnalysisInputError"],
["not_found", "AnalysisInputError"],
["ambiguous", "AnalysisInputError"],
["method_unavailable", "AnalysisCapabilityUnavailableError"],
] as const)(
"projects remote %s without losing its typed meaning",
async (code, tag) => {
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () =>
Promise.resolve(
err(
new GhidraSessionError(
"remote",
"Fixture remote failure",
{ remote_code: code },
{ remoteCode: code },
),
),
),
close: () => Promise.resolve(),
}));
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
await expect(
ghidra
.createClient(
executableTarget("elf", "x86_64"),
resolved.value.profile,
)
.execute("list_procedures", {}),
).resolves.toMatchObject({ ok: false, error: { _tag: tag } });
},
);
it.each([
["decompile_timeout", "AnalysisTimeoutError", 30_000],
["decompile_cancelled", "AnalysisCancelledError", undefined],
] as const)(
"projects remote %s as a provider-neutral interruption",
async (code, tag, timeoutMs) => {
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () =>
Promise.resolve(
err(
new GhidraSessionError(
"remote",
"Fixture decompiler interruption",
{ remote_code: code },
{ remoteCode: code },
),
),
),
close: () => Promise.resolve(),
}));
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.execute("procedure_pseudo_code", { procedure: "main" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: tag,
...(timeoutMs === undefined ? {} : { timeoutMs }),
},
});
},
);
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 sessionInfo = () => ({
name: "REA Ghidra bridge" as const,
bridge_version: 6 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: "a".repeat(64),
provider: { id: "ghidra" as const, version: "12.1.2" },
read_only: true as const,
analysis_complete: true,
analysis_timed_out: false,
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
target: {
name: "fixture",
language_id: "x86:LE:64:default",
compiler_spec_id: "gcc",
image_base: "0x1000",
default_address_space: "ram",
sha256: "a".repeat(64),
},
});
const executableTarget = (
format: "mach-o" | "elf" | "pe",
architecture: NonNullable<BinaryTarget["architecture"]>,
): BinaryTarget =>
format === "pe"
? peTarget(architecture)
: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format,
architecture,
availableArchitectures: [architecture],
};
const peTarget = (
architecture: NonNullable<BinaryTarget["architecture"]>,
): Extract<BinaryTarget, { format: "pe" }> => ({
path: "/tmp/fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "pe",
architecture,
availableArchitectures: [architecture],
executableRole: "application",
managed: false,
});