fix(ghidra): harden location resolution and provider lifecycle

Preserve boundary diagnostics, resolve procedure names before bare hex addresses, and launch the inspected JVM directly on macOS for verifiable startup cancellation. Keep private socket paths within host limits and retain ownership when cleanup is incomplete.

Exercise the fixes through real CLI/MCP Ghidra workflows and provider-boundary integration tests, replacing redundant unit coverage.
This commit is contained in:
morluto
2026-10-09 02:38:07 +08:00
parent e2fc2493b6
commit 1f5be750bc
24 changed files with 962 additions and 297 deletions
+5
View File
@@ -42,6 +42,11 @@ export const resolveGhidraAnalysisProfile = (
annotation_policy: "atomic-function-entry-metadata-v1",
load_image_observations: "source-mappings-entry-context-v2",
function_body_evidence: "complete-inclusive-ranges-v1",
location_resolution: "explicit-address-exact-name-first-v2",
process_launch:
installation.platform === "darwin"
? "inspected-jvm-launch-support-v1"
: "official-headless-script-v1",
...(dos
? {
load_image_evidence: dosCom
-110
View File
@@ -1,110 +0,0 @@
import { functionDossierSchema } from "../domain/hopperValues.js";
import { describe, expect, it } from "vitest";
import { nativeFunctionAnnotationsInputSchema } from "../domain/native/nativeFunctionAnnotations.js";
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
import {
parseGhidraFunctionInput,
parseGhidraFunctionResult,
} from "./GhidraFunctionValues.js";
import {
CAPABILITIES,
windowsP0Capabilities,
} from "./GhidraProviderCapabilities.js";
import { HOPPER_OPERATIONS } from "../hopper/HopperProvider.js";
const result = () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
return {
annotations: {
address: dossier.procedure.address,
name: dossier.procedure.name,
comment: null,
inline_comment: "Finding",
},
dossier,
effects: {
scope: "session-analysis-database",
source_bytes_modified: false,
persists_after_close: false,
},
};
};
describe("Ghidra function annotations", () => {
it("requires an explicit function and at least one change without approval flags", () => {
for (const input of [
{},
{ procedure: "main" },
{ procedure: "", name: "entry" },
{ procedure: "main", name: "" },
{ procedure: "main", comment: null },
{ procedure: "main", name: "entry", approve: true },
])
expect(
nativeFunctionAnnotationsInputSchema.safeParse(input).success,
).toBe(false);
expect(
parseGhidraFunctionInput("annotate_native_function", {
procedure: "0x10100",
comment: "",
}),
).toEqual({ ok: true, value: { procedure: "0x10100", comment: "" } });
});
it("preserves multiline Unicode text and omitted fields", () => {
const input = { procedure: "entry", inline_comment: "Line one\n註記" };
expect(parseGhidraFunctionInput("annotate_native_function", input)).toEqual(
{ ok: true, value: input },
);
});
it("validates readback identity, exact effects and the complete Ghidra dossier", () => {
const value = result();
expect(
parseGhidraFunctionResult("annotate_native_function", value).ok,
).toBe(true);
for (const malformed of [
{ ...value, annotations: { ...value.annotations, name: "different" } },
{ ...value, annotations: { ...value.annotations, address: "0x9999" } },
{ ...value, effects: { ...value.effects, source_bytes_modified: true } },
{ ...value, effects: { ...value.effects, persists_after_close: true } },
{ ...value, dossier: { ...value.dossier, native_value_flow: null } },
])
expect(
parseGhidraFunctionResult("annotate_native_function", malformed).ok,
).toBe(false);
});
it("preserves qualified names in readback and the refreshed dossier", () => {
const value = result();
const name = "namespace::recovered_routine";
expect(
parseGhidraFunctionResult("annotate_native_function", {
...value,
annotations: { ...value.annotations, name },
dossier: {
...value.dossier,
procedure: { ...value.dossier.procedure, name },
},
}).ok,
).toBe(true);
});
it("declares mutation only for the admitted operation and keeps Windows and Hopper unavailable", () => {
expect(
CAPABILITIES.find((c) => c.operation === "annotate_native_function"),
).toMatchObject({
available: true,
effects: { mutatesArtifact: true, mayShowUi: false },
});
expect(
CAPABILITIES.find((c) => c.operation === "analyze_function"),
).toMatchObject({ effects: { mutatesArtifact: false } });
expect(
windowsP0Capabilities().find(
(c) => c.operation === "annotate_native_function",
),
).toMatchObject({ available: false });
expect(HOPPER_OPERATIONS).not.toContain("annotate_native_function");
});
});
+57 -18
View File
@@ -1,7 +1,6 @@
import { randomBytes, randomUUID } from "node:crypto";
import type { Socket } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -40,7 +39,10 @@ import {
import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js";
import { readFile } from "node:fs/promises";
import { connectGhidraSocket } from "./GhidraSocketConnection.js";
import type { GhidraEndpoint } from "./GhidraTransport.js";
import {
createGhidraEndpoint,
type GhidraEndpoint,
} from "./GhidraTransport.js";
import { GhidraWire } from "./GhidraClientWire.js";
import { completeGhidraStartupHandshake } from "./GhidraClientStartup.js";
@@ -75,6 +77,8 @@ export class GhidraClient {
#launch: GhidraLaunch | undefined;
#process: ProviderProcessSupervisor | undefined;
#runtimeRoot: PrivateRuntimeRoot | undefined;
#socketRoot: PrivateRuntimeRoot | undefined;
#endpointPath: string | undefined;
#snapshotPath: string | undefined;
#targetAdmission: JsonValue | undefined;
#token: string | undefined;
@@ -145,7 +149,13 @@ export class GhidraClient {
start(signal?: AbortSignal): Promise<GhidraStartResult> {
if (this.#closePromise !== undefined)
return this.#closePromise.then(() => this.start(signal));
if (this.#startPromise !== undefined) return this.#startPromise;
if (this.#startPromise !== undefined) {
if (this.#startupController?.signal.aborted && !signal?.aborted)
return this.#startPromise.then((result) =>
result.ok ? result : this.start(signal),
);
return this.#startPromise;
}
const controller = new AbortController();
const onAbort = (): void => controller.abort(signal?.reason);
if (signal?.aborted === true) onAbort();
@@ -265,12 +275,16 @@ export class GhidraClient {
return err(this.#failure("cancelled", "Ghidra startup was cancelled"));
if (this.#socket !== undefined || this.#runtimeRoot !== undefined)
return err(this.#failure("protocol", "Ghidra client is already started"));
this.#processSnapshot = undefined;
const deadline = new ProviderStartupDeadline(
this.#options.startupTimeoutMs,
signal,
);
try {
return await this.#startWithin(deadline);
} catch (cause: unknown) {
if (cause instanceof GhidraSessionError) return err(cause);
throw cause;
} finally {
deadline.dispose();
}
@@ -291,15 +305,25 @@ export class GhidraClient {
);
}
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
const endpoint: GhidraEndpoint = {
transport: this.#options.transport,
path: join(
let endpoint: GhidraEndpoint;
try {
const allocated = await createGhidraEndpoint(
this.#runtimeRoot.path,
this.#options.transport === "unix-socket"
? "bridge.sock"
: "bridge-endpoint.json",
),
};
this.#options.transport,
this.#options.platform,
);
endpoint = allocated.endpoint;
this.#socketRoot = allocated.socketRoot;
this.#endpointPath = endpoint.path;
} catch (cause: unknown) {
const failure = this.#failure(
"start",
"Ghidra private endpoint allocation failed",
cause,
);
await this.#cleanup();
return err(failure);
}
try {
const snapshot = await createGhidraTargetSnapshot(
this.#options.targetPath,
@@ -386,7 +410,7 @@ export class GhidraClient {
deadline,
failure: this.#failure,
isClosed: () => this.#closing,
processExited: () => this.#processSnapshot?.exitCode !== undefined,
processExited: () => this.#process?.snapshot().exitCode !== undefined,
startupTimeoutMs: this.#options.startupTimeoutMs,
handlers: {
data: this.#onSocketData,
@@ -498,20 +522,28 @@ export class GhidraClient {
{ reason: stopped.reason },
"Ghidra process cleanup failed closed",
);
if (forceStop)
forcedStopFailure = this.#failure(
"process",
`Ghidra process cleanup after cancellation was incomplete: ${stopped.reason}`,
);
// Keep the supervisor and private files available for a later close.
// A still-live JVM can recreate files if its runtime is removed here.
throw this.#failure(
"process",
`Ghidra process cleanup was incomplete: ${stopped.reason}`,
);
}
}
this.#lastDiagnostics = this.#diagnostics();
this.#process = undefined;
this.#launch = undefined;
const runtimeRoot = this.#runtimeRoot;
const socketRoot = this.#socketRoot;
this.#runtimeRoot = undefined;
this.#socketRoot = undefined;
try {
await runtimeRoot?.close();
const removed = await Promise.allSettled([
runtimeRoot?.close(),
socketRoot?.close(),
]);
const failed = removed.find((result) => result.status === "rejected");
if (failed?.status === "rejected") throw failed.reason;
} catch (cause: unknown) {
if (forceStop)
forcedStopFailure ??= this.#failure(
@@ -522,6 +554,7 @@ export class GhidraClient {
else throw cause;
}
this.#snapshotPath = undefined;
this.#endpointPath = undefined;
this.#token = undefined;
this.#runId = undefined;
this.#responseBuffer.reset();
@@ -604,6 +637,12 @@ export class GhidraClient {
...(this.#runtimeRoot === undefined
? {}
: { runtimeRoot: this.#runtimeRoot.path }),
...(this.#socketRoot === undefined
? {}
: { socketRoot: this.#socketRoot.path }),
...(this.#endpointPath === undefined
? {}
: { endpointPath: this.#endpointPath }),
...(this.#launch === undefined ? {} : { launch: this.#launch }),
...(snapshot === undefined ? {} : { snapshot }),
...(this.#token === undefined ? {} : { token: this.#token }),
+9 -11
View File
@@ -1,5 +1,3 @@
import { join } from "node:path";
import type { JsonValue } from "../domain/jsonValue.js";
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
@@ -15,6 +13,8 @@ export interface GhidraDiagnosticsOptions {
readonly profileDigest: string;
readonly runId?: string;
readonly runtimeRoot?: string;
readonly socketRoot?: string;
readonly endpointPath?: string;
readonly launch?: GhidraLaunch;
readonly snapshot?: ProviderProcessSnapshot;
readonly token?: string;
@@ -47,15 +47,13 @@ export const createGhidraDiagnostics = (
...(options.runId === undefined ? {} : { run_id: options.runId }),
...(options.runtimeRoot === undefined
? {}
: {
runtime_root: options.runtimeRoot,
endpoint_path: join(
options.runtimeRoot,
options.transport === "unix-socket"
? "bridge.sock"
: "bridge-endpoint.json",
),
}),
: { runtime_root: options.runtimeRoot }),
...(options.socketRoot === undefined
? {}
: { socket_root: options.socketRoot }),
...(options.endpointPath === undefined
? {}
: { endpoint_path: options.endpointPath }),
...(options.launch === undefined
? {}
: {
+12 -6
View File
@@ -10,7 +10,7 @@ import {
} from "../domain/native/nativeInstruction.js";
import {
AnalysisInputError,
type AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import {
@@ -27,8 +27,10 @@ import {
import { nativeApiBoundarySchema } from "../domain/native/nativeApiBoundary.js";
import { nativeValueFlowSchema } from "../domain/native/nativeValueFlow.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import {
ghidraIdentifierSchema,
ghidraInputAddressSchema,
ghidraCanonicalAddressSchema,
ghidraFunctionClassificationSchema as classification,
ghidraFunctionBodySchema as ghidraFunctionBody,
@@ -73,7 +75,7 @@ const inputSchemas = {
.object({
document,
type: z.string().min(1).nullable().default(null),
address: ghidraCanonicalAddressSchema.nullable().default(null),
address: ghidraInputAddressSchema.nullable().default(null),
})
.strict()
.refine(
@@ -81,10 +83,10 @@ const inputSchemas = {
"Supply exactly one of type or address",
),
inspect_native_instruction: z
.object({ document, address: ghidraCanonicalAddressSchema })
.object({ document, address: ghidraInputAddressSchema })
.strict(),
resolve_native_call_targets: z
.object({ document, address: ghidraCanonicalAddressSchema })
.object({ document, address: ghidraInputAddressSchema })
.strict(),
analyze_function: z.object({ procedure }).strict(),
procedure_assembly: z.object(directProcedure).strict(),
@@ -99,7 +101,7 @@ const inputSchemas = {
direction: z.enum(["incoming", "outgoing"]).default("outgoing"),
})
.strict(),
xrefs: z.object({ document, address: ghidraCanonicalAddressSchema }).strict(),
xrefs: z.object({ document, address: ghidraInputAddressSchema }).strict(),
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
/** Validate and default one function request before it crosses the socket. */
@@ -118,7 +120,11 @@ export const parseGhidraFunctionInput = (
),
),
)
: err(new AnalysisInputError(operation, { cause: parsed.error }));
: err(
analysisInputErrorFromIssues(operation, parsed.error.issues, value, {
cause: parsed.error,
}),
);
};
const localVariable = z
+15 -3
View File
@@ -2,7 +2,7 @@ import { z } from "zod";
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
import {
AnalysisInputError,
type AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import {
@@ -11,6 +11,7 @@ import {
} from "../domain/hopperValues.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
/** Read-only direct inventory operations admitted by the Ghidra adapter. */
export const GHIDRA_INVENTORY_OPERATIONS = [
@@ -43,7 +44,14 @@ export const isGhidraInventoryOperation = (
export const ghidraIdentifierSchema = z.string().min(1);
const identifier = ghidraIdentifierSchema;
const document = identifier.nullable().default(null);
const explicitAddress = identifier;
/** Caller address spelling; the bridge resolves its space and emits canonical output. */
export const ghidraInputAddressSchema = z
.string()
.regex(
/^(?:(?:0[xX])?[0-9a-fA-F]+|(?:[A-Za-z0-9._~-]|%[0-9a-fA-F]{2})+:0[xX][0-9a-fA-F]+)$/u,
"Use hexadecimal digits, optionally prefixed with 0x, or an encoded address-space name followed by :0x and hexadecimal digits",
);
const explicitAddress = ghidraInputAddressSchema;
const filteredAddress = explicitAddress.nullable().default(null);
const searchInput = {
pattern: z.string().min(1),
@@ -84,7 +92,11 @@ export const parseGhidraInventoryInput = (
): Result<Readonly<Record<string, JsonValue>>, AnalysisInputError> => {
const parsed = inputSchemas[operation].safeParse(value);
if (!parsed.success)
return err(new AnalysisInputError(operation, { cause: parsed.error }));
return err(
analysisInputErrorFromIssues(operation, parsed.error.issues, value, {
cause: parsed.error,
}),
);
return ok(parsed.data);
};
+88
View File
@@ -0,0 +1,88 @@
import { dirname, join } from "node:path";
import { execFileOutput } from "../process/ExecFileOutput.js";
/** Launch coordinates obtained from Ghidra's own release configuration helper. */
export const ghidraJavaLaunch = async (options: {
readonly analyzeHeadlessPath: string;
readonly javaHome: string;
readonly homeRoot: string;
readonly tempRoot: string;
readonly arguments: readonly string[];
readonly environment: NodeJS.ProcessEnv;
readonly signal?: AbortSignal;
}): Promise<{
readonly command: string;
readonly arguments: readonly string[];
readonly environment: NodeJS.ProcessEnv;
}> => {
const supportRoot = dirname(options.analyzeHeadlessPath);
const installRoot = dirname(supportRoot);
const command = join(options.javaHome, "bin", "java");
const isolatedProperties = [
`-Duser.home=${options.homeRoot}`,
`-Djava.io.tmpdir=${options.tempRoot}`,
];
const supportArguments = [
...isolatedProperties,
"-cp",
join(supportRoot, "LaunchSupport.jar"),
"LaunchSupport",
installRoot,
];
const environment = { ...options.environment };
const configuredEnvironment = await execFileOutput(
command,
[...supportArguments, "-envvars"],
{
env: environment,
...(options.signal === undefined ? {} : { signal: options.signal }),
},
);
for (const line of configuredEnvironment.stdout.split(/\r?\n/u)) {
if (line === "") continue;
const separator = line.indexOf("=");
const key = line.slice(0, separator);
if (separator < 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key))
throw new Error(
`Invalid Ghidra LaunchSupport environment entry: ${line}`,
);
if ((environment[key] ?? "") === "")
environment[key] = line.slice(separator + 1);
}
const configuredArguments = await execFileOutput(
command,
[...supportArguments, "-vmargs"],
{
env: environment,
...(options.signal === undefined ? {} : { signal: options.signal }),
},
);
const vmArguments = configuredArguments.stdout
.split(/\r?\n/u)
.filter((line) => line !== "");
if (
vmArguments.some(
(argument) => !argument.startsWith("-") || argument.includes("\0"),
)
)
throw new Error("Invalid Ghidra LaunchSupport JVM argument");
return {
command,
environment,
arguments: [
...vmArguments,
"-Xdock:name=Ghidra-Headless",
`-Xmx${environment.GHIDRA_HEADLESS_MAXMEM || environment.GHIDRA_MAXMEM || "2G"}`,
"-XX:ParallelGCThreads=2",
"-XX:CICompilerCount=2",
"-Djava.awt.headless=true",
...isolatedProperties,
"-showversion",
"-cp",
join(installRoot, "Ghidra", "Framework", "Utility", "lib", "Utility.jar"),
"ghidra.Ghidra",
"ghidra.app.util.headless.AnalyzeHeadless",
...options.arguments,
],
};
};
+34 -11
View File
@@ -18,6 +18,7 @@ import {
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { ghidraJavaEnvironment } from "./GhidraInstallation.js";
import { ghidraJavaLaunch } from "./GhidraJavaLaunch.js";
import type { GhidraTransportKind } from "./GhidraTransport.js";
import {
snapshotGhidraExtensions,
@@ -124,7 +125,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
? {}
: { dosMz: this.options.dosMz }),
});
const command = ghidraHeadlessCommand({
const scriptCommand = ghidraHeadlessCommand({
platform,
analyzeHeadlessPath: this.options.analyzeHeadlessPath,
arguments: headlessArguments,
@@ -132,33 +133,55 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
? {}
: { comSpec: this.options.comSpec }),
});
const environment = ghidraLaunchEnvironment(
paths,
this.options.javaHome,
platform,
scriptCommand.command,
);
if (platform === "darwin" && this.options.javaHome === undefined)
throw new GhidraLaunchError(
"macOS Ghidra requires its inspected JDK home",
);
const command =
platform === "darwin" && this.options.javaHome !== undefined
? await ghidraJavaLaunch({
analyzeHeadlessPath: this.options.analyzeHeadlessPath,
javaHome: this.options.javaHome,
homeRoot: paths.homeRoot,
tempRoot: paths.tempRoot,
arguments: headlessArguments,
environment,
...(options.signal === undefined
? {}
: { signal: options.signal }),
})
: { ...scriptCommand, environment };
started = await spawnOwnedProviderProcess({
command: command.command,
arguments: command.arguments,
runId: session.runId,
// analyzeHeadless is an interpreter-driven script. Parent identity and
// the per-process run token remain the cleanup authority.
expectedCommand: null,
// macOS launches the inspected JVM directly: platform shell wrappers
// with withheld environments cannot establish run-token ownership.
expectedCommand: platform === "darwin" ? command.command : null,
windowsVerbatimArguments: platform === "win32",
platform,
env: ghidraLaunchEnvironment(
paths,
this.options.javaHome,
platform,
command.command,
),
env: command.environment,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
await writeGhidraRuntimeFile(
paths.ownershipPath,
`${JSON.stringify({
run_id: session.runId,
transport: session.transport,
endpoint_path: session.endpointPath,
pid: started.ownership.leaderPid,
process_group_id: started.ownership.processGroupId,
parent_pid: process.pid,
ownership_kind:
platform === "win32" ? "windows-job-object" : "posix-process-group",
launcher: this.options.analyzeHeadlessPath,
launcher: command.command,
headless_script: this.options.analyzeHeadlessPath,
created_at: new Date().toISOString(),
})}\n`,
platform,
+6 -4
View File
@@ -132,9 +132,7 @@ export const createGhidraProviderClient = (input: {
platform: installation.platform,
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
...(config.ghidraJavaHome === undefined
? {}
: { javaHome: config.ghidraJavaHome }),
javaHome: prerequisites.value.javaHome,
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
),
@@ -266,6 +264,7 @@ export const createGhidraProviderClient = (input: {
interface GhidraClientCoordinates {
readonly analyzeHeadlessPath: string;
readonly javaHome: string;
readonly providerVersion: string;
readonly profile: AnalysisProfileCommitment;
}
@@ -304,6 +303,7 @@ const ghidraClientPrerequisites = (
return err(new ProviderAdapterError("ghidra", "health"));
return ok({
analyzeHeadlessPath: installation.analyzeHeadlessPath,
javaHome: installation.javaHome,
providerVersion: installation.providerVersion,
profile,
});
@@ -341,7 +341,9 @@ const projectSessionError = (
failure.remoteCode ?? "",
)
)
return new AnalysisInputError(operation, { cause: failure });
return new AnalysisInputError(operation, { cause: failure }, [
{ path: [], reason: "invalid_value", message: failure.message },
]);
if (failure.kind === "remote" && failure.remoteCode === "method_unavailable")
return new AnalysisCapabilityUnavailableError(
"ghidra",
-81
View File
@@ -1,81 +0,0 @@
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);
});
});
+11 -7
View File
@@ -49,13 +49,17 @@ const createGhidraSessionError = (failure: {
new GhidraSessionError(
failure.kind,
failure.message,
failure.remoteCode === undefined
? failure.diagnostics
: {
...failure.diagnostics,
remote_code: failure.redact(failure.remoteCode),
remote_message: failure.message,
},
{
...failure.diagnostics,
failure_kind: failure.kind,
failure_message: failure.message,
...(failure.remoteCode === undefined
? {}
: {
remote_code: failure.redact(failure.remoteCode),
remote_message: failure.message,
}),
},
{
...(failure.cause === undefined ? {} : { cause: failure.cause }),
...(failure.timeoutMs === undefined
+33
View File
@@ -1,4 +1,6 @@
import { access, open } from "node:fs/promises";
import { join } from "node:path";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { readWindowsPrivateRuntimeFile } from "../windows/WindowsPrivateRuntime.js";
@@ -14,6 +16,37 @@ export interface GhidraEndpoint {
readonly path: string;
}
/** Allocate an endpoint that fits the host's Unix sockaddr without moving the project. */
export const createGhidraEndpoint = async (
runtimeRoot: string,
transport: GhidraTransportKind,
platform: NodeJS.Platform,
): Promise<{
readonly endpoint: GhidraEndpoint;
readonly socketRoot?: PrivateRuntimeRoot;
}> => {
const path = join(
runtimeRoot,
transport === "unix-socket" ? "bridge.sock" : "bridge-endpoint.json",
);
// sockaddr_un includes a terminating NUL: macOS has 104 bytes, Linux 108.
const maximumPathBytes = platform === "darwin" ? 103 : 107;
if (
transport !== "unix-socket" ||
Buffer.byteLength(path, "utf8") <= maximumPathBytes
)
return { endpoint: { transport, path } };
const socketRoot = await PrivateRuntimeRoot.create({
parent: "/tmp",
prefix: "rea-ghidra-socket-",
platform,
});
return {
endpoint: { transport, path: join(socketRoot.path, "s") },
socketRoot,
};
};
/** Exact Node connection target after endpoint discovery. */
export type GhidraConnectTarget =
| { readonly path: string }