fix(ghidra): preserve request and shutdown failure diagnostics (#647)

This commit is contained in:
N0zoM1z0
2026-10-06 12:13:52 +08:00
committed by GitHub
parent 9f42495d11
commit 19f8cddfd6
10 changed files with 567 additions and 13 deletions
+8
View File
@@ -281,6 +281,14 @@ is no fixed per-operation or response-size ceiling. Unresolved computed calls
remain unknown, reference-kind provenance is preserved, and provider-specific
pseudocode is never treated as original source or Hopper-equivalent text.
Unexpected request failures retain their original internal cause. CLI and MCP
errors expose Error names, messages, and available codes under
`details.diagnostics.failure_cause`; other rejection values retain their
primitive value or an explicit type. Shutdown warnings include the failure
kind, message, and diagnostics, while process and temporary-project cleanup
continues. These messages redact known bridge authentication tokens and
preserve local paths and other analysis context.
Run `GHIDRA_INSTALL_DIR=... npm run verify:ghidra` from a source checkout to
compile and analyze debug and stripped host-native fixtures (ELF on Linux x64
or Mach-O on macOS), plus a native DWARF 4 type-layout object. This lane needs a
+27 -4
View File
@@ -76,6 +76,8 @@ export class GhidraClient {
#runtimeRoot: PrivateRuntimeRoot | undefined;
#snapshotPath: string | undefined;
#token: string | undefined;
// Retain authentication identities for diagnostics from late request settlement.
readonly #authenticationTokens = new Set<string>();
#runId: string | undefined;
readonly #lineage = new ProviderRunLineage();
#nextId = 1;
@@ -85,7 +87,10 @@ export class GhidraClient {
#startupController: AbortController | undefined;
#startPromise: Promise<GhidraStartResult> | undefined;
#closePromise: Promise<void> | undefined;
readonly #failure = bindGhidraSessionFailure(() => this.#diagnostics());
readonly #failure = bindGhidraSessionFailure(
() => this.#diagnostics(),
(value) => this.#redactAuthentication(value),
);
readonly #wire: GhidraWire;
readonly #requestQueue: GhidraRequestQueue;
readonly #responseRouter = new GhidraResponseRouter({
@@ -287,6 +292,7 @@ export class GhidraClient {
}
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
this.#token = randomBytes(32).toString("hex");
this.#authenticationTokens.add(this.#token);
this.#lineage.reset();
this.#runId = this.#options.runId ?? randomUUID();
const launched = await this.#options.launcher
@@ -419,12 +425,23 @@ export class GhidraClient {
if (!forceStop && socket !== undefined && !socket.destroyed) {
const shutdown = await this.#wire
.request("shutdown", {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS })
.catch(() =>
err(this.#failure("process", "Ghidra shutdown request failed")),
.catch((cause: unknown) =>
err(
this.#failure("process", "Ghidra shutdown request failed", cause),
),
);
if (!shutdown.ok || !isGhidraShutdownAcknowledgement(shutdown.value))
this.#logger.warn(
{ status: shutdown.ok ? "invalid-acknowledgement" : "failed" },
{
status: shutdown.ok ? "invalid-acknowledgement" : "failed",
...(shutdown.ok
? {}
: {
kind: shutdown.error.kind,
message: shutdown.error.message,
diagnostics: shutdown.error.diagnostics,
}),
},
"Ghidra bridge shutdown was not confirmed",
);
}
@@ -480,6 +497,12 @@ export class GhidraClient {
}
}
#redactAuthentication(value: string): string {
for (const token of this.#authenticationTokens)
value = value.replaceAll(token, "[REDACTED]");
return value;
}
#onProcessDiagnostic(event: ProviderProcessDiagnostic): void {
if (event.type === "output") {
this.#options.onDiagnostic?.({
+92
View File
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { err, ok } from "../domain/result.js";
import { GhidraRequestQueue } from "./GhidraRequestQueue.js";
import { bindGhidraSessionFailure } from "./GhidraSessionError.js";
const failure = bindGhidraSessionFailure(() => ({
target_path: "/tmp/queue-fixture",
}));
describe("Ghidra request queue failure settlement", () => {
it.each([new TypeError("Decoder rejected"), "decoder rejected", null])(
"preserves a rejected executor cause (%j) and drains the next request",
async (cause) => {
const executed: string[] = [];
const queue = new GhidraRequestQueue(
async (method) => {
executed.push(method);
if (method === "first") throw cause;
return ok({ method });
},
failure,
() => Promise.resolve(),
);
const first = queue.run("first", {}, {});
const second = queue.run("second", {}, {});
const result = await first;
expect(result).toMatchObject({
ok: false,
error: {
kind: "protocol",
message: "Ghidra serial request execution rejected unexpectedly",
diagnostics: { target_path: "/tmp/queue-fixture" },
},
});
if (result.ok) throw new Error("Expected queue failure");
expect(result.error.cause).toBe(cause);
expect(result.error.diagnostics).toHaveProperty("failure_cause");
await expect(second).resolves.toEqual(ok({ method: "second" }));
expect(executed).toEqual(["first", "second"]);
},
);
it("does not replace an executor's typed failure", async () => {
const original = failure("timeout", "Request deadline elapsed");
const queue = new GhidraRequestQueue(
() => Promise.resolve(err(original)),
failure,
() => Promise.resolve(),
);
const result = await queue.run("first", {}, {});
expect(result).toEqual(err(original));
if (!result.ok) expect(result.error).toBe(original);
});
it("preserves cancellation cleanup failures and rejects queued work", async () => {
const controller = new AbortController();
const cause = new Error("Runtime removal failed");
let release: (() => void) | undefined;
const completed = new Promise<void>((resolve) => {
release = resolve;
});
const queue = new GhidraRequestQueue(
async () => {
await completed;
return err(failure("cancelled", "Request cancelled"));
},
failure,
async () => {
throw cause;
},
);
const active = queue.run("active", {}, { signal: controller.signal });
const queued = queue.run("queued", {}, {});
controller.abort();
release?.();
const result = await active;
expect(result).toMatchObject({
ok: false,
error: {
kind: "process",
diagnostics: { failure_cause: { message: cause.message } },
},
});
if (result.ok) throw new Error("Expected cleanup failure");
expect(result.error.cause).toBe(cause);
await expect(queued).resolves.toMatchObject({
ok: false,
error: { kind: "process" },
});
});
});
+2 -1
View File
@@ -148,13 +148,14 @@ export class GhidraRequestQueue {
executionSettled = true;
entry.resolve(result);
})
.catch(() => {
.catch((cause: unknown) => {
executionSettled = true;
entry.resolve(
err(
this.failure(
"protocol",
"Ghidra serial request execution rejected unexpectedly",
cause,
),
),
);
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { bindGhidraSessionFailure } from "./GhidraSessionError.js";
const diagnostics = {
target_path: "/tmp/public-fixture",
target_sha256: "a".repeat(64),
};
describe("Ghidra session failure diagnostics", () => {
it("retains the original Error while projecting its name, message and code", () => {
const cause = Object.assign(
new TypeError("Cannot decode /tmp/public-fixture at offset 17"),
{ code: "EDECODE" },
);
const failure = bindGhidraSessionFailure(() => diagnostics)(
"protocol",
"Request rejected",
cause,
);
expect(failure.cause).toBe(cause);
expect(failure.kind).toBe("protocol");
expect(failure.diagnostics).toEqual({
...diagnostics,
failure_cause: {
name: "TypeError",
message: cause.message,
code: "EDECODE",
},
});
expect(failure.diagnostics).not.toHaveProperty("stack");
});
it.each([
["decoder rejected", { type: "string", message: "decoder rejected" }],
[null, { type: "null", value: null }],
[false, { type: "boolean", value: false }],
[42, { type: "number", value: 42 }],
[{ opaque: true }, { type: "object" }],
])("handles a non-Error rejection (%j)", (cause, expected) => {
const failure = bindGhidraSessionFailure(() => diagnostics)(
"process",
"Shutdown rejected",
cause,
);
expect(failure.cause).toBe(cause);
expect(failure.diagnostics.failure_cause).toEqual(expected);
});
it("redacts only known authentication material in projected failure fields", () => {
const token = "actual-bridge-authentication";
const message = `Failure ${token}: http://localhost/secret?token=public-value /tmp/password-fixture`;
const cause = Object.assign(new Error(message), { code: `code-${token}` });
const failure = bindGhidraSessionFailure(
() => diagnostics,
(value) => value.replaceAll(token, "[REDACTED]"),
)("remote", message, cause, { remoteCode: `code-${token}` });
expect(failure.cause).toBe(cause);
expect(failure.message).toBe(message.replaceAll(token, "[REDACTED]"));
expect(failure.diagnostics).toMatchObject({
remote_code: "code-[REDACTED]",
remote_message: failure.message,
failure_cause: { message: failure.message, code: "code-[REDACTED]" },
});
expect(JSON.stringify(failure.diagnostics)).not.toContain(token);
expect(JSON.stringify(failure.diagnostics)).toContain(
"token=public-value /tmp/password-fixture",
);
});
it("leaves absent causes and existing timeout metadata unchanged", () => {
const failure = bindGhidraSessionFailure(() => diagnostics)(
"timeout",
"Deadline elapsed",
undefined,
{ timeoutMs: 5 },
);
expect(failure.timeoutMs).toBe(5);
expect(failure.diagnostics).toEqual(diagnostics);
});
});
+39 -4
View File
@@ -44,6 +44,7 @@ const createGhidraSessionError = (failure: {
readonly cause?: unknown;
readonly timeoutMs?: number;
readonly remoteCode?: string;
readonly redact: (value: string) => string;
}): GhidraSessionError =>
new GhidraSessionError(
failure.kind,
@@ -52,7 +53,7 @@ const createGhidraSessionError = (failure: {
? failure.diagnostics
: {
...failure.diagnostics,
remote_code: failure.remoteCode,
remote_code: failure.redact(failure.remoteCode),
remote_message: failure.message,
},
{
@@ -68,7 +69,10 @@ const createGhidraSessionError = (failure: {
/** Bind session-failure construction to a live, token-redacted diagnostic view. */
export const bindGhidraSessionFailure =
(diagnostics: () => Readonly<Record<string, JsonValue>>) =>
(
diagnostics: () => Readonly<Record<string, JsonValue>>,
redact: (value: string) => string = (value) => value,
) =>
(
kind: GhidraSessionFailureKind,
message: string,
@@ -77,8 +81,39 @@ export const bindGhidraSessionFailure =
): GhidraSessionError =>
createGhidraSessionError({
kind,
message,
diagnostics: diagnostics(),
message: redact(message),
diagnostics: {
...diagnostics(),
...(cause === undefined
? {}
: { failure_cause: describeCause(cause, redact) }),
},
redact,
...(cause === undefined ? {} : { cause }),
...options,
});
const describeCause = (
cause: unknown,
redact: (value: string) => string,
): JsonValue => {
if (cause instanceof Error) {
const code = "code" in cause ? cause.code : undefined;
return {
name: redact(cause.name),
message: redact(cause.message),
...(typeof code === "string"
? { code: redact(code) }
: typeof code === "number" && Number.isFinite(code)
? { code }
: {}),
};
}
if (typeof cause === "string")
return { type: "string", message: redact(cause) };
if (cause === null || typeof cause === "boolean")
return { type: cause === null ? "null" : "boolean", value: cause };
if (typeof cause === "number" && Number.isFinite(cause))
return { type: "number", value: cause };
return { type: typeof cause };
};
@@ -0,0 +1,79 @@
import { expect, it } from "vitest";
import { logCliCommand } from "../../../src/cliLogging.js";
import { analysisErrorProjectionSchema } from "../../../src/contracts/errorSchemas.js";
import { GhidraRequestQueue } from "../../../src/ghidra/GhidraRequestQueue.js";
import { bindGhidraSessionFailure } from "../../../src/ghidra/GhidraSessionError.js";
import { silentLogger } from "../../../src/logger.js";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
it("preserves queue failure diagnostics through the provider, CLI adapter and SDK MCP transport", async () => {
const token = "fixture-authentication-token";
const cause = Object.assign(
new TypeError(
`Decode failed ${token}: /tmp/password-fixture http://localhost/secret?token=public-value`,
),
{ code: "EDECODE" },
);
const failure = bindGhidraSessionFailure(
() => ({
target_path: "/tmp/public-fixture",
target_sha256: "a".repeat(64),
}),
(value) => value.replaceAll(token, "[REDACTED]"),
);
const queue = new GhidraRequestQueue(
async () => {
throw cause;
},
failure,
() => Promise.resolve(),
);
const harness = await connectGhidraMcp(
"ghidra-failure-diagnostics",
(operation, input, options) => queue.run(operation, input, options ?? {}),
);
const previousExitCode = process.exitCode;
try {
const cli = await logCliCommand(silentLogger, "inspect", async () => {
const result = await harness.session.execute("list_procedures", {
document: null,
});
if (!result.ok) throw result.error;
return result.value.result;
});
expect(process.exitCode).toBe(1);
const parsed = analysisErrorProjectionSchema.parse(cli);
expect(parsed).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
target_path: "/tmp/public-fixture",
failure_cause: {
name: "TypeError",
code: "EDECODE",
message:
"Decode failed [REDACTED]: /tmp/password-fixture http://localhost/secret?token=public-value",
},
},
},
});
const mcp = await harness.mcp.callTool({
name: "list_procedures",
arguments: {},
});
expect(mcp.isError).toBe(true);
expect(mcp.structuredContent).toMatchObject({ error: parsed });
expect(mcp.content).toContainEqual(
expect.objectContaining({
type: "text",
text: expect.stringContaining("EDECODE"),
}),
);
expect(JSON.stringify(mcp)).not.toContain(token);
expect(JSON.stringify(mcp)).not.toContain(cause.stack);
} finally {
process.exitCode = previousExitCode;
await harness.close();
}
}, 30_000);
+6 -2
View File
@@ -24,15 +24,19 @@ import {
const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
export const connectGhidraMcp = async (name: string) => {
export const connectGhidraMcp = async (
name: string,
execute?: ReturnType<GhidraProviderClientFactory>["callTool"],
) => {
const calls: GhidraOperation[] = [];
const factory: GhidraProviderClientFactory = (options) => ({
start: () =>
Promise.resolve(
ok(sessionInfo(options.profileDigest, options.targetSha256)),
),
callTool: (operation, input) => {
callTool: (operation, input, options) => {
calls.push(operation);
if (execute !== undefined) return execute(operation, input, options);
return Promise.resolve(ok(resultFor(operation, input)));
},
close: () => Promise.resolve(),
@@ -6,6 +6,8 @@ import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import pino from "pino";
import type { Logger } from "../../../../src/logger.js";
import { ok } from "../../../../src/domain/result.js";
import {
@@ -39,6 +41,8 @@ type FixtureMode =
| "future_id"
| "analysis_timeout"
| "remote_error"
| "shutdown_error"
| "invalid_shutdown_ack"
| "hang_after_start"
| "hang_tools"
| "exit_tools"
@@ -94,6 +98,7 @@ const clientFor = (
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly transport?: GhidraTransportKind;
readonly runId?: string;
readonly logger?: Logger;
} = {},
): GhidraClient => {
const client = new GhidraClient({
@@ -105,6 +110,7 @@ const clientFor = (
profileDigest: PROFILE_DIGEST,
startupTimeoutMs: options.startupTimeoutMs ?? 1_000,
...(options.runId === undefined ? {} : { runId: options.runId }),
...(options.logger === undefined ? {} : { logger: options.logger }),
...(options.onDiagnostic === undefined
? {}
: { onDiagnostic: options.onDiagnostic }),
@@ -385,3 +391,215 @@ const waitForExit = async (
const wait = (milliseconds: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, milliseconds));
describe("GhidraClient rejected requests", () => {
it("redacts authentication after failed startup cleanup and retry", async () => {
const fixture = new FixtureLauncher();
const tokens: string[] = [];
const launcher: GhidraLauncher = {
launch: async (session) => {
tokens.push(session.token);
if (tokens.length === 1)
throw new Error("Launch rejected before process creation");
return fixture.launch(session);
},
};
let rejectCompletion = false;
const logger = pino(
{
level: "debug",
hooks: {
logMethod(args, method) {
const fields = args[0];
if (
rejectCompletion &&
typeof fields === "object" &&
fields !== null &&
"method" in fields &&
fields.method === "list_procedures"
)
throw new Error(
`Late failure ${tokens.join(" ")} /tmp/public-fixture`,
);
method.apply(this, args);
},
},
},
{ write: () => undefined },
);
const client = clientFor(launcher, { logger });
await expect(client.start()).resolves.toMatchObject({
ok: false,
error: { kind: "start" },
});
await expect(client.start()).resolves.toMatchObject({ ok: true });
expect(tokens).toHaveLength(2);
rejectCompletion = true;
const result = await client.callTool("list_procedures", { document: null });
expect(result).toMatchObject({
ok: false,
error: {
diagnostics: {
failure_cause: {
message: "Late failure [REDACTED] [REDACTED] /tmp/public-fixture",
},
},
},
});
if (result.ok) throw new Error("Expected late failure");
for (const token of tokens)
expect(JSON.stringify(result.error.diagnostics)).not.toContain(token);
});
it("retains an unexpected wire rejection and continues serial requests", async () => {
const launcher = new FixtureLauncher();
const cause = Object.assign(new TypeError("Request completion rejected"), {
code: "ECOMPLETION",
});
let rejectCompletion = true;
const logger = pino(
{
level: "debug",
hooks: {
logMethod(args, method) {
const fields = args[0];
if (
rejectCompletion &&
typeof fields === "object" &&
fields !== null &&
"method" in fields &&
fields.method === "list_procedures"
) {
rejectCompletion = false;
throw cause;
}
method.apply(this, args);
},
},
},
{ write: () => undefined },
);
const client = clientFor(launcher, { logger });
const first = client.callTool("list_procedures", { document: null });
const second = client.callTool("list_procedures", { document: null });
const result = await first;
expect(result).toMatchObject({
ok: false,
error: {
kind: "protocol",
diagnostics: {
failure_cause: {
name: "TypeError",
message: cause.message,
code: "ECOMPLETION",
},
},
},
});
if (result.ok) throw new Error("Expected rejected request");
expect(result.error.cause).toBe(cause);
await expect(second).resolves.toMatchObject({ ok: true });
});
});
describe("GhidraClient shutdown diagnostics", () => {
it("logs an unexpected shutdown rejection and still removes its process and runtime", async () => {
const launcher = new FixtureLauncher();
const logs: string[] = [];
const logger = pino(
{
level: "debug",
hooks: {
logMethod(args, method) {
const fields = args[0];
if (
typeof fields === "object" &&
fields !== null &&
"method" in fields &&
fields.method === "shutdown"
)
throw Object.assign(
new Error(
`Shutdown rejected ${launcher.tokens[0]} /tmp/password-fixture`,
),
{ code: "ESHUTDOWN" },
);
method.apply(this, args);
},
},
},
{
write: (line) => {
logs.push(line);
},
},
);
const client = clientFor(launcher, { logger });
await expect(client.start()).resolves.toMatchObject({ ok: true });
await expect(client.close()).resolves.toBeUndefined();
const warning: unknown[] = logs.map((line) => JSON.parse(line));
expect(warning).toContainEqual(
expect.objectContaining({
status: "failed",
kind: "process",
message: "Ghidra shutdown request failed",
diagnostics: expect.objectContaining({
failure_cause: {
name: "Error",
message: "Shutdown rejected [REDACTED] /tmp/password-fixture",
code: "ESHUTDOWN",
},
}),
}),
);
expect(logs.join("")).not.toContain(launcher.tokens[0]);
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
await expect(waitForExit(launcher.processes[0])).resolves.toBe(true);
});
it.each(["shutdown_error", "invalid_shutdown_ack"] as const)(
"keeps cleanup best effort for %s",
async (mode) => {
const launcher = new FixtureLauncher(mode);
const logs: string[] = [];
const logger = pino(
{ level: "warn" },
{
write: (line) => {
logs.push(line);
},
},
);
const client = clientFor(launcher, { logger });
await expect(client.start()).resolves.toMatchObject({ ok: true });
await expect(client.close()).resolves.toBeUndefined();
const warning: unknown[] = logs.map((line) => JSON.parse(line));
expect(warning).toContainEqual(
expect.objectContaining({
msg: "Ghidra bridge shutdown was not confirmed",
status:
mode === "shutdown_error" ? "failed" : "invalid-acknowledgement",
}),
);
if (mode === "shutdown_error") {
expect(warning).toContainEqual(
expect.objectContaining({
kind: "remote",
diagnostics: expect.objectContaining({
remote_code: "shutdown_fixture_failure",
remote_message:
"Shutdown denied for [REDACTED]: /tmp/password-fixture http://localhost/secret?token=public-value",
}),
}),
);
}
expect(logs.join("")).not.toContain(launcher.tokens[0]);
await expect(
access(launcher.runtimeRoots[0] ?? ""),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(waitForExit(launcher.processes[0])).resolves.toBe(true);
},
);
});
+15 -2
View File
@@ -118,8 +118,21 @@ const handleRequest = (socket, server, request, state) => {
socket.end(
`${JSON.stringify({
id: request.id,
ok: true,
result: { shutdown: true, project_ephemeral: true },
...(state.mode === "shutdown_error"
? {
ok: false,
error: {
code: "shutdown_fixture_failure",
message: `Shutdown denied for ${state.token}: /tmp/password-fixture http://localhost/secret?token=public-value`,
},
}
: {
ok: true,
result: {
shutdown: state.mode !== "invalid_shutdown_ack",
project_ephemeral: true,
},
}),
})}\n`,
);
server.close(() => process.exit(0));