fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)

* feat(process): add owned debugger shutdown lifecycle

* feat(reverse): add local inspection commands

* feat(gdb): add persistent debugger integration

* feat(cutter): add Cutter bridge integration

* test(reverse): enforce complete integration coverage

* fix(process): preserve debugger shutdown ownership

* fix(reverse): retain evidence across interrupted commands

* fix(gdb): honor captured provider environment

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* test(process): cover debugger shutdown retries

* fix(reverse): retain evidence for interrupted providers

* fix(server): snapshot provider environment at creation

* fix(reverse): close review gaps with complete coverage

* fix(reverse): address inspection review findings

* fix(gdb): bound sessions and retain cleanup ownership

* fix(ci): require reverse-tools quality lane

* fix(process): unref inherited debugger output pipes

* fix(reverse): address remaining PR 1960 findings

* fix(gdb): address remaining PR 1961 findings

* fix(reverse): account for unrestricted provider execution

* fix(process): retain debugger ownership until safe shutdown

* fix(process): preserve replacement debugger sessions

* fix(reverse): preserve admission and output provenance

* fix(process): retain exited debugger until output settles

* fix(mcp): bound provider admission and debugger cleanup

* fix(reverse): preserve failure provenance and classify E2BIG

* fix(gdb): preserve startup cleanup and detach safety

* fix(process): retain debugger ownership after detach failure

* fix(reverse): preserve mutation and failure provenance

* fix(gdb): address debugger review findings

* fix(reverse): rebind sessions after external mutation

* fix(process): cap debugger output after exit

* fix(gdb): protect one-shot detach verification

* feat(debugger): add reverse tool coverage gate

* test(debugger): cover integrated failure paths

* fix(gdb): bound and preserve session observations

* fix(gdb): address review regressions

* style: format merged integration files

* fix(reverse): preserve session and output evidence

* refactor(gdb): share repeated test and partial result setup

* fix(gdb): invalidate TTY proof for Python aliases

* fix(reverse): retain failure output byte counts

* test(process): synchronize late debugger output

* fix(gdb): invalidate TTY proof for wrapped commands

* fix(gdb): recognize wit command abbreviation

* test(reverse): wait for cancelled descendant readiness

* test(reverse): bound descendant cancellation cleanup

* style(reverse): format integration tests and adapters

* style: format reverse engineering integration files

* test(reverse): remove duplicate environment harness

* test(gdb): share session startup assertions

* fix(gdb): invalidate output proof for command abbreviations

* test(reverse): share composition edge case scenarios

* fix(ci): recognize verification and mutation tool entries

* test(rizin): cover successful fake inferior detach

* test(cli): align full output failure envelope

* test(cli): isolate reverse command lifecycle service

* test(process): share debugger output fixture setup

* fix(binary): preserve high-bit Windows signature bytes

* style(binary): format Windows signature parser

* test(mcp): preserve call coverage in unchanged comparison

* fix(ci): include reverse tools Vitest configs in lint cache

* fix(mcp): preserve target content on delivery errors

* ci: align duplication ceiling with expanded suite

* test(reverse): allow signal admission mutants

* fix(reverse): bound retained cleanup failures to process owners

* fix(test): replace drifting mutation ranges with owned selectors

* fix(reverse): admit persistent commands and retain cleanup ownership

* fix(cutter): recover timed-out commands from exact receipts

* fix(cutter): reject unsupported bridge request kinds

* fix(ci): repair client format and shared verification fixtures

* fix(native): preserve debugger cleanup ownership and bridge authentication

* test(native): retain diagnostics without perfect coverage requirements

* chore(licenses): refresh locked dependency inventory and notices

* fix(test): exclude transient command locks from mutation sandboxes

* fix(gdb): admit only platforms with safe detach verification

* fix(cutter): retain bounded completion receipts until acknowledgement

* fix(cutter): acknowledge commands rejected before UI dispatch

* test(reverse): fail cancellation checks before fixture teardown

* test(gdb): clean up the retained broken-stdin fixture owner

* docs(test): clarify focused provider verification scope

* fix(rizin): retain close cleanup failures

* fix(gdb): wait for inferior stop and bound MI buffering

* fix(cutter): retain failed receipt acknowledgements

* fix(rizin): return retained session identity on rebind failure

* fix(gdb): preserve startup cancellation and lossy status

* fix(rizin): retain launch provenance and assemble frames once

* fix(cutter): recover receipts across callers and bound discovery

* docs: describe debugger evidence and bridge recovery

* fix(process): keep cleanup incomplete while writers remain

Stopping a debugger no longer reports success when inherited output
streams stay open, so BinarySession cannot reopen a binary a child is
still changing. Concurrent Cutter cleanup retries share one receipt
acknowledgement instead of treating a consumed receipt as failure.

* fix(debuggers): recover cleanup with captured process identities

* fix(analysis): retire sessions after unrestricted commands

* fix(cli): preserve completed evidence after cleanup recovery

* fix(cutter): bound frame collection and coalesce cleanup

* fix(windows): resolve selected provider paths absolutely

* fix(gdb): report decoding loss in failed startup evidence

* fix(rizin): scope decoding loss to collected command frames

* test(mcp): cover snapshot retirement in reverse tools CI

---------

Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com>
Co-authored-by: REA Maintainers <noreply@github.com>
Co-authored-by: OpenAI Codex <codex@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
morluto
2026-10-14 04:47:34 +08:00
committed by GitHub
co-authored by Daniel Gonçalves Araujo REA Maintainers OpenAI Codex Cursor Agent
parent 2ad2a044d4
commit 4aa51bfe19
168 changed files with 32703 additions and 238 deletions
+183
View File
@@ -0,0 +1,183 @@
import { createServer } from "node:net";
import { createHmac } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Cli } from "incur";
import { afterEach, describe, expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
import { serveCli } from "./cliServeHarness.js";
const SESSION_ID = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const registeredCommands = Cli.toCommands as WeakMap<
object,
Map<string, unknown>
>;
const cutterCommand = async (
environment: Record<string, string | undefined>,
args: {
readonly sessionId: string;
readonly expectedGeneration: number;
readonly command: string;
},
): Promise<unknown> => {
const cli = createCli(environment);
const entry = registeredCommands.get(cli)?.get("cutter-command") ?? {};
const run = Reflect.get(entry, "run") as (...args: unknown[]) => unknown;
return Reflect.apply(run, undefined, [{ args, options: { json: false } }]);
};
const listen = async (
server: ReturnType<typeof createServer>,
): Promise<number> => {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral TCP listener");
return address.port;
};
describe("Cutter CLI commands", () => {
let directory: string | undefined;
let server: ReturnType<typeof createServer> | undefined;
afterEach(async () => {
if (server !== undefined)
await new Promise<void>((resolve) => server?.close(() => resolve()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
server = undefined;
});
it("lists sessions from the selected bridge directory", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const result = await serveCli(["list-cutter-sessions", "--json"], {
REA_CUTTER_BRIDGE_DIR: directory,
});
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
sessions: [],
discovery_status: "no_live_bridge_found",
bridge_directory: directory,
});
});
it("reports an unavailable selected session for a command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const result = await serveCli(
["cutter-command", SESSION_ID, "0", "pdi", "--json"],
{ REA_CUTTER_BRIDGE_DIR: directory },
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("invalid_request");
});
it("returns Evidence when the selected Cutter session completes a command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const token = "synthetic-cutter-cli-token-for-test";
let nextConnectionOrdinal = 0;
server = createServer((connection) => {
const ordinal = ++nextConnectionOrdinal;
connection.setEncoding("utf8");
let input = "";
let clientNonce = "";
let serverNonce = "";
connection.on("data", (chunk: string) => {
input += chunk;
const newline = input.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(input.slice(0, newline)) as Record<
string,
unknown
>;
input = input.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce = `${ordinal.toString(16).padStart(16, "0")}${"b".repeat(48)}`;
connection.write(
`${JSON.stringify({ session_id: SESSION_ID, nonce: serverNonce, proof: createHmac("sha256", token).update(`rea-cutter-server-v2:${SESSION_ID}:${clientNonce}:${serverNonce}`).digest("hex") })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
if (
frame.proof !==
createHmac("sha256", token)
.update(
`rea-cutter-client-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex")
) {
connection.destroy();
return;
}
const status = request.kind === "status";
const response = JSON.stringify({
ok: true,
session_id: request.session_id,
...(status
? {
current_file: null,
document_generation: 0,
cutter_version: "Cutter fixture",
identity_status: "partial",
completed_connection: (ordinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: request.kind === "ack"
? { acknowledged: false }
: {
output: { answer: 42 },
current_file: null,
document_generation: 0,
cutter_version: "Cutter fixture",
identity_status: "partial",
execution_state: "complete",
output_truncated: false,
}),
});
const proof = createHmac("sha256", token)
.update(
`rea-cutter-response-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof })}\n`);
});
});
const port = await listen(server);
await writeFile(
join(directory, `cutter-${process.pid}-${SESSION_ID}.json`),
JSON.stringify({
session_id: SESSION_ID,
pid: process.pid,
host: "127.0.0.1",
port,
token,
document_generation: 0,
current_file: null,
cutter_version: "Cutter fixture",
identity_status: "partial",
}),
{ mode: 0o600 },
);
const result = await cutterCommand(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ sessionId: SESSION_ID, expectedGeneration: 0, command: "pdi" },
);
expect(JSON.stringify(result)).toContain("rea.cutter.command-observation");
expect(JSON.stringify(result)).toContain('"answer":42');
});
});
@@ -0,0 +1,132 @@
import pino from "pino";
import { expect, it, vi } from "vitest";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err } from "../../../src/domain/result.js";
import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js";
import { CLI_COMMANDS } from "../../../src/cliCommandNames.js";
import type { CliInstance } from "../../../src/cli/types.js";
import type { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
const registerGdbCommand = (
createManager: () => GdbSessionManager,
): {
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
} => {
const commands = new Map<
string,
{
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(cli, pino({ enabled: false }), {}, () =>
createManager(),
);
const command = commands.get(CLI_COMMANDS.debugWithGdb);
if (command === undefined)
throw new Error("GDB CLI command was not registered");
return command;
};
it.each([
"source /tmp/gdbinit",
"python print('x')",
"def custom-command",
"run > /tmp/out",
"set inferior-t /dev/null",
"with inferior-t /dev/null -- run",
])("rejects one-shot command %s before starting GDB", async (inputCommand) => {
const manager = {
start: vi.fn(),
closeAll: vi.fn(),
} as unknown as GdbSessionManager;
const command = registerGdbCommand(() => manager);
const result = await command.run({
args: { command: inputCommand },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
message: expect.stringContaining("persistent GDB session workflow"),
}),
],
},
});
expect(manager.start).not.toHaveBeenCalled();
expect(manager.closeAll).not.toHaveBeenCalled();
});
it("retries retained GDB cleanup when CLI session startup fails", async () => {
const closeAll = vi.fn(async () => undefined);
const manager = {
start: vi.fn(async () =>
err(new AnalysisOutputError("start_gdb_session", "startup failed")),
),
closeAll,
} as unknown as GdbSessionManager;
const originalExitCode = process.exitCode;
const command = registerGdbCommand(() => manager);
try {
const result = await command.run({
args: { command: "info files" },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({ code: "unreadable_output" });
expect(manager.start).toHaveBeenCalledOnce();
expect(manager.start).toHaveBeenCalledWith(expect.anything(), {
inferiorTty: "/dev/pts/42",
});
expect(closeAll).toHaveBeenCalledOnce();
} finally {
process.exitCode = originalExitCode;
}
});
it("marks the CLI failed when retained GDB cleanup remains incomplete", async () => {
const manager = {
start: vi.fn(async () =>
err(new AnalysisOutputError("start_gdb_session", "startup failed")),
),
closeAll: vi.fn(async () => {
throw new Error("process still owned");
}),
} as unknown as GdbSessionManager;
const originalExitCode = process.exitCode;
const command = registerGdbCommand(() => manager);
try {
const result = await command.run({
args: { command: "info files" },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({ code: "unreadable_output" });
expect(manager.closeAll).toHaveBeenCalledOnce();
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = originalExitCode;
}
});
@@ -0,0 +1,429 @@
import pino from "pino";
import { Cli, z } from "incur";
import { afterEach, expect, it, vi } from "vitest";
import { rm } from "node:fs/promises";
import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js";
import { CLI_COMMANDS } from "../../../src/cliCommandNames.js";
import {
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
createEvidence,
evidenceSchema,
} from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import { ReverseEngineeringService as CoreReverseEngineeringService } from "../../../src/application/reverse/ReverseEngineeringService.js";
import { createReverseEngineeringCommandPort } from "../../../src/composition/reverseEngineering.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../../src/process/ProviderProcess.js";
import {
createArtifact,
providerSnapshot,
} from "../../support/reverseEngineeringCompositionFixtures.js";
import type { CliInstance } from "../../../src/cli/types.js";
import type { ReverseEngineeringService } from "../../../src/application/reverse/ReverseEngineeringService.js";
const originalExitCode = process.exitCode;
afterEach(() => {
process.exitCode = originalExitCode;
});
const observation = (completionStatus: "complete" | "unknown") =>
createEvidence(
undefined,
{ id: "gnu.objdump", name: "GNU objdump", version: null },
{
predicateType: "rea.reverse-engineering.command-observation",
operation: "inspect_with_objdump",
parameters: { operation: "file_headers" },
result: { completion_status: completionStatus },
rawResult: { completion_status: completionStatus },
},
);
const runObjdump = async (
service: Partial<ReverseEngineeringService>,
path = "/tmp/sample",
) => {
const commands = new Map<
string,
{
run(input: {
args: { path: string; operation: string };
options: { followDebugLinks: boolean };
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: { path: string; operation: string };
options: { followDebugLinks: boolean };
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(
cli,
pino({ enabled: false }),
{},
undefined,
() => service as ReverseEngineeringService,
);
const command = commands.get(CLI_COMMANDS.inspectWithObjdump);
if (command === undefined)
throw new Error("objdump CLI command was not registered");
return command.run({
args: { path, operation: "file_headers" },
options: { followDebugLinks: false },
});
};
it("lists objdump architectures without inventing an artifact path", async () => {
const evidence = observation("complete");
const inspectWithObjdump = vi.fn(async (_input: unknown) => ok(evidence));
const commands = new Map<
string,
{
readonly args?: { safeParse(input: unknown): { success: boolean } };
run(input: { args?: unknown; options?: unknown }): Promise<unknown>;
}
>();
const cli = {
command: (_name: string, definition: unknown) => {
commands.set(
_name,
definition as {
readonly args?: {
safeParse(input: unknown): { success: boolean };
};
run(input: { args?: unknown; options?: unknown }): Promise<unknown>;
},
);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(
cli,
pino({ enabled: false }),
{},
undefined,
() =>
({
inspectWithObjdump,
close: vi.fn(async () => undefined),
}) as unknown as ReverseEngineeringService,
);
const command = commands.get(CLI_COMMANDS.listObjdumpArchitectures);
if (command === undefined)
throw new Error("architecture command was not registered");
const result = await command.run({});
expect(result).toEqual(evidence);
expect(inspectWithObjdump).toHaveBeenCalledWith(
{ operation: "architectures" },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
const artifactCommand = commands.get(CLI_COMMANDS.inspectWithObjdump);
expect(
artifactCommand?.args?.safeParse({
path: "/tmp/sample",
operation: "dwarf",
}).success,
).toBe(true);
expect(
artifactCommand?.args?.safeParse({
path: "/tmp/sample",
operation: "architectures",
}).success,
).toBe(false);
});
it("promotes only complete production cleanup-only Evidence after CLI cleanup retry", async () => {
const { directory, path } = await createArtifact();
const owner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort({}),
runOwned: vi.fn(async () => {
throw new OwnedCommandFailure(
"process",
"Cleanup after process completion was incomplete.",
providerSnapshot(),
"provider process still running",
undefined,
["owned-run"],
owner,
);
}),
});
const inspect = service.inspectWithObjdump.bind(service);
let producedCleanupFailure: AnalysisOutputError | undefined;
let cleanupIncompleteBeforeClose: boolean | undefined;
let completionBeforeClose: unknown;
vi.spyOn(service, "inspectWithObjdump").mockImplementation(
async (...args) => {
const result = await inspect(...args);
if (!result.ok && result.error instanceof AnalysisOutputError) {
producedCleanupFailure = result.error;
cleanupIncompleteBeforeClose = result.error.cleanupIncomplete;
const partialEvidence = evidenceSchema.safeParse(
result.error.partialObservation,
);
if (partialEvidence.success)
completionBeforeClose = partialEvidence.data.normalized_result;
}
return result;
},
);
try {
const result = await runObjdump(service, path);
expect(result).toMatchObject({
provider: { id: "gnu.objdump" },
normalized_result: { completion_status: "complete" },
});
expect(producedCleanupFailure?.cleanupOnly).toBe(true);
expect(cleanupIncompleteBeforeClose).toBe(true);
expect(completionBeforeClose).toMatchObject({
completion_status: "complete",
});
expect(producedCleanupFailure).toMatchObject({
cleanupIncomplete: false,
cleanup: { resources: ["owned-run"] },
partialObservation: {
normalized_result: { completion_status: "complete" },
},
});
expect(owner.stop).toHaveBeenCalledOnce();
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("preserves an operation timeout and unknown partial Evidence after cleanup retry", async () => {
const { directory, path } = await createArtifact();
const owner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort({}),
runOwned: vi.fn(async () => {
throw new OwnedCommandFailure(
"timeout",
"Provider command timed out.",
providerSnapshot({ exitCode: null }),
"provider process still running",
undefined,
["owned-run"],
owner,
);
}),
});
let timeout: AnalysisTimeoutError | undefined;
const inspect = service.inspectWithObjdump.bind(service);
vi.spyOn(service, "inspectWithObjdump").mockImplementation(
async (...args) => {
const result = await inspect(...args);
if (!result.ok && result.error instanceof AnalysisTimeoutError)
timeout = result.error;
return result;
},
);
try {
const result = await runObjdump(service, path);
expect(result).toMatchObject({
code: "provider_timeout",
details: {
partial_observation: {
normalized_result: { completion_status: "unknown" },
},
},
});
expect(timeout).toBeInstanceOf(AnalysisTimeoutError);
expect(timeout?.cleanupIncomplete).toBe(false);
expect(owner.stop).toHaveBeenCalledOnce();
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("preserves an independent timeout after cleanup succeeds", async () => {
const evidence = observation("unknown");
const error = new AnalysisTimeoutError("inspect_with_objdump", 1_000, {
cleanup: { reason: "first stop incomplete", resources: ["owned-run"] },
partialObservation: evidence,
});
const service = {
inspectWithObjdump: vi.fn(async () => err(error)),
close: vi.fn(async () => {
error.resolveCleanup();
}),
};
const result = await runObjdump(service);
expect(result).toMatchObject({
code: "provider_timeout",
details: {
partial_observation: {
normalized_result: { completion_status: "unknown" },
},
},
});
expect(error.cleanupIncomplete).toBe(false);
expect(projectAnalysisError(error).details).not.toHaveProperty("cleanup");
});
it("does not project cancellation cleanup as incomplete after a successful retry", async () => {
const error = new AnalysisCancelledError("inspect_with_objdump", {
cleanup: { reason: "first stop incomplete", resources: ["owned-run"] },
partialObservation: observation("unknown"),
});
const service = {
inspectWithObjdump: vi.fn(async () => err(error)),
close: vi.fn(async () => {
error.resolveCleanup();
}),
};
await runObjdump(service);
expect(error.cleanupIncomplete).toBe(false);
expect(projectAnalysisError(error).details).toMatchObject({
cleanup: "complete",
});
});
it("parses the Rizin inferior TTY as an option and passes it to the manager", async () => {
const commands = new Map<
string,
{
run(input: {
args: Record<string, unknown>;
options: Record<string, unknown>;
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: Record<string, unknown>;
options: Record<string, unknown>;
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
const evidence = createEvidence(
undefined,
{ id: "rizin.debugger", name: "Rizin debugger", version: null },
{
predicateType: "rea.debugger.command-observation",
operation: "rizin_debug_command",
parameters: {
session_id: "session-1",
command: "dr",
inferior_tty: "/dev/pts/7",
},
result: { output: "registers" },
rawResult: { output: "registers" },
},
);
const start = vi
.spyOn(RizinDebugSessionManager.prototype, "start")
.mockResolvedValue(ok({ session_id: "session-1", backend: null }));
const execute = vi
.spyOn(RizinDebugSessionManager.prototype, "execute")
.mockResolvedValue(
ok({
evidence,
result: {
command: "dr",
output: "registers",
output_scope: "command_and_interleaved_session_output",
output_truncated: false,
completion_status: "complete",
backend: null,
},
}),
);
vi.spyOn(RizinDebugSessionManager.prototype, "close").mockResolvedValue(
ok({ target_state: "unknown" }),
);
vi.spyOn(RizinDebugSessionManager.prototype, "closeAll").mockResolvedValue(
undefined,
);
registerReverseEngineeringCommands(cli, pino({ enabled: false }), {});
const command = commands.get(CLI_COMMANDS.debugWithRizin);
if (command === undefined)
throw new Error("Rizin CLI command was not registered");
await command.run({
args: { path: "./sample.bin", command: "dr" },
options: { inferiorTty: "/dev/pts/7" },
});
expect(start).toHaveBeenCalledWith(
{ path: "./sample.bin", command: "dr", inferior_tty: "/dev/pts/7" },
expect.any(AbortSignal),
);
expect(execute).toHaveBeenCalledWith(
"session-1",
"dr",
expect.any(AbortSignal),
);
const parserCli = Cli.create("rea-test", { version: "1.0.0", sync: false });
registerReverseEngineeringCommands(
parserCli as unknown as CliInstance,
pino({ enabled: false }),
{},
);
const commandContract = Cli.toCommands
.get(parserCli)
?.get(CLI_COMMANDS.debugWithRizin);
expect(commandContract).toBeDefined();
const argsSchema =
commandContract === undefined
? undefined
: Reflect.get(commandContract, "args");
const optionsSchema =
commandContract === undefined
? undefined
: Reflect.get(commandContract, "options");
if (
!(argsSchema instanceof z.ZodObject) ||
!(optionsSchema instanceof z.ZodObject)
)
throw new Error("Rizin CLI args/options schemas were not registered");
expect(argsSchema.parse({ path: "./sample.bin", command: "dr" })).toEqual({
path: "./sample.bin",
command: "dr",
});
expect(optionsSchema.parse({ inferiorTty: "/dev/pts/7" })).toMatchObject({
inferiorTty: "/dev/pts/7",
});
});
@@ -215,6 +215,146 @@ it("does not charge a documentation PR for unrelated implementation updates on m
});
});
it.each([
"src/gdb/GdbSessionManager.ts",
"src/rizin/RizinDebugSessionManager.ts",
"src/cutter/CutterBridgeClient.ts",
"src/objdump/ObjdumpCommand.ts",
"tests/boundary/providers/GdbSessionManagerCoverage.test.ts",
"tests/boundary/providers/GdbCommandQueue.test.ts",
"tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts",
"tests/boundary/providers/RizinCommandTimeout.test.ts",
"tests/boundary/providers/RizinTimeoutEvidence.test.ts",
"tests/boundary/providers/GdbSessionReviewRegressions.test.ts",
"tests/boundary/providers/gdbTestHelpers.ts",
"tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts",
"tests/boundary/mcp/gdbCancellationMcp.test.ts",
"tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts",
"tests/composition/reverseEngineeringAdmission.test.ts",
"tests/support/reverseEngineeringMcpHarness.ts",
"tests/support/reverseEngineeringCompositionEdgeCases.ts",
"tests/support/reverseEngineeringCompositionFixtures.ts",
"tests/support/reverseEngineeringService.ts",
"tests/support/ownedRizinCommandEvidenceTests.ts",
"tests/support/reverseDebuggerMcpTestHelpers.ts",
"tests/boundary/cli/gdbStartupCleanupCli.test.ts",
"vitest.reverse-tools.config.ts",
"vitest.reverse-tools-semantics.config.ts",
"stryker.config.mjs",
"stryker.semantics.config.mjs",
"tsconfig.reverse-tools-mutation.json",
"scripts/prepare-reverse-tools-mutation.mjs",
"scripts/lib/reverse-tools-mutation-targets.mjs",
])(
"selects the reverse-tool coverage and mutation gate for %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
const reverseToolsVitestConfig = await readFile(
new URL("../../../vitest.reverse-tools.config.ts", import.meta.url),
"utf8",
);
const reverseToolsVitestInputs = [
...reverseToolsVitestConfig.matchAll(/"((?:\.\/)?(?:src|tests)\/[^"]+)"/gu),
].flatMap((match) =>
match[1] === undefined ? [] : [match[1].replace(/^\.\//u, "")],
);
const reverseToolsMutationConfig = JSON.parse(
await readFile(
new URL("../../../tsconfig.reverse-tools-mutation.json", import.meta.url),
"utf8",
),
) as { include: string[] };
const reverseToolsInputs = [
...new Set([
...reverseToolsVitestInputs,
...reverseToolsMutationConfig.include.map((path) =>
path.replace(/^\.\//u, ""),
),
]),
];
it.each(reverseToolsInputs)(
"selects the reverse-tool quality gate for configured input %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
it("requires the reverse-tool gate when its scope is selected", async () => {
const workflow = parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
);
expect(workflow.jobs["reverse-tools-quality"].if).toBe(
"needs.changes.outputs.reverse_tools == 'true'",
);
expect(workflow.jobs.required.needs).toContain("reverse-tools-quality");
const { CI_FLAGS } = await loadScopes();
const outputs = {
...Object.fromEntries(CI_FLAGS.map((flag) => [flag, "false"])),
tier: "fast",
reverse_tools: "true",
};
const command = new URL("../../../scripts/ci/required.mjs", import.meta.url)
.pathname;
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "skipped" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "failure" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "success" },
}),
},
}),
).resolves.toMatchObject({
stdout: expect.stringContaining("Every selected CI lane passed"),
});
});
it.each([
"src/README.md",
"README.md.ts",
@@ -23,10 +23,27 @@ it("threads the selected host and environment into system diagnostics", async ()
environment,
execFileOutput: async (command, arguments_, options) => {
calls.push({ command, arguments: arguments_, environment: options?.env });
if (command === "sw_vers") return { stdout: "15.0\n", stderr: "" };
if (command === "ldd") return { stdout: "linux-vdso.so.1", stderr: "" };
if (command === "sw_vers")
return {
stdout: "15.0\n",
stderr: "",
stdoutBytes: 5,
stderrBytes: 0,
};
if (command === "ldd")
return {
stdout: "linux-vdso.so.1",
stderr: "",
stdoutBytes: Buffer.byteLength("linux-vdso.so.1"),
stderrBytes: 0,
};
if (command === "which")
return { stdout: "/selected/bin/rea\n", stderr: "" };
return {
stdout: "/selected/bin/rea\n",
stderr: "",
stdoutBytes: 18,
stderrBytes: 0,
};
throw new Error(`Unexpected diagnostic command: ${command}`);
},
});
@@ -88,7 +105,12 @@ it.each([
environment: { HOME: join(root, "home") },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -111,7 +133,12 @@ it("reports no Homebrew Hopper when the cask has no receipt", async () => {
environment: { HOME: caskroom },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -19,6 +19,9 @@ import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_OPERATIONS,
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
import { OBJDUMP_PROVIDER_IDENTITY } from "../../../src/objdump/ObjdumpCommand.js";
import { RIZIN_PROVIDER_IDENTITY } from "../../../src/rizin/RizinCommand.js";
import { GDB_PROVIDER_IDENTITY } from "../../../src/gdb/GdbSessionManager.js";
import {
documentationFactIssues,
skillReferenceIssues,
@@ -118,6 +121,16 @@ describe("canonical product catalog", () => {
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
);
expect(catalog.cli.commands).toHaveLength(CLI_COMMAND_NAMES.length);
expect(catalog.providers.map(({ id }) => id)).toEqual(
expect.arrayContaining(
[
OBJDUMP_PROVIDER_IDENTITY,
RIZIN_PROVIDER_IDENTITY,
GDB_PROVIDER_IDENTITY,
].map(({ id }) => id),
),
);
expect(
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
@@ -0,0 +1,78 @@
import { execFileSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const root = fileURLToPath(new URL("../../../", import.meta.url));
const runNode = (source: string, ...arguments_: string[]): string =>
execFileSync(
process.execPath,
["--input-type=module", "-e", source, ...arguments_],
{ cwd: root, encoding: "utf8" },
);
describe("reverse-tools mutation configuration", () => {
it("loads nonempty targets from both actual Stryker configs", () => {
const result = runNode(
`const [mainUrl, semanticsUrl] = process.argv.slice(1);
const main = await import(mainUrl);
const semantics = await import(semanticsUrl);
process.stdout.write(JSON.stringify({
main: main.default.mutate.length,
semantics: semantics.default.mutate.length,
}));`,
pathToFileURL(join(root, "stryker.config.mjs")).href,
pathToFileURL(join(root, "stryker.semantics.config.mjs")).href,
);
const targets = JSON.parse(result) as {
main: number;
semantics: number;
};
expect(targets.main).toBeGreaterThan(0);
expect(targets.semantics).toBeGreaterThan(0);
});
it("fails closed when an owned mutation method is missing", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Present { run() {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Missing", name: "run" }]);
throw new Error("missing owner unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 0")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 0/u);
});
it("fails closed when an owned mutation method is ambiguous", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Owner { run() {} run(value: string) {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Owner", name: "run" }]);
throw new Error("ambiguous target unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 2")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 2/u);
});
});
@@ -0,0 +1,168 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import { registerCutterTools } from "../../../src/server/registerCutterTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import { silentLogger } from "../../../src/logger.js";
it("propagates MCP cancellation into an active Cutter command and reports uncertain completion", async () => {
let markDispatched: (() => void) | undefined;
let observedAbort = false;
const dispatched = new Promise<void>((resolve) => {
markDispatched = resolve;
});
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async ({ signal }) => {
markDispatched?.();
await new Promise<void>((resolve) => {
signal?.addEventListener(
"abort",
() => {
observedAbort = true;
resolve();
},
{ once: true },
);
});
return {
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: null,
documentGeneration: 1,
identityStatus: "partial" as const,
cutterVersion: "Cutter fixture version",
executionState: "unknown" as const,
error: "transport-response-missing",
message: "The command may have completed; do not retry automatically",
outputTruncated: false,
};
},
});
const server = new McpServer({ name: "cutter-cancellation", version: "1" });
registerCutterTools(
server,
service,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "cutter-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const controller = new AbortController();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const request = client.callTool(
{
name: "cutter_command",
arguments: {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 1,
command: "Ps /tmp/possibly-saved.rzdb",
json: false,
},
},
{ signal: controller.signal },
);
await dispatched;
controller.abort();
await expect(request).rejects.toThrow(/abort/iu);
await expect.poll(() => observedAbort).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("shares one cleanup proof across concurrent Cutter MCP commands without BinarySession", async () => {
let releaseProof!: () => void;
let enterProof!: () => void;
const proof = new Promise<void>((resolve) => {
releaseProof = resolve;
});
const entered = new Promise<void>((resolve) => {
enterProof = resolve;
});
let confirmations = 0;
let dispatches = 0;
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion: async () => {
confirmations += 1;
if (confirmations > 1) {
await proof;
await new Promise<void>((resolve) => setImmediate(resolve));
return { ok: true, value: false };
}
enterProof();
await proof;
return { ok: true, value: true };
},
execute: async ({ command }) => {
dispatches += 1;
return {
requestId: `00000000-0000-4000-8000-${String(dispatches).padStart(12, "0")}`,
output: command,
currentFile: null,
documentGeneration: 1,
identityStatus: "partial",
cutterVersion: "fixture",
executionState: dispatches === 1 ? "unknown" : "complete",
error: dispatches === 1 ? "transport-response-missing" : null,
message: null,
outputTruncated: false,
};
},
});
const server = new McpServer({ name: "cutter-cleanup-race", version: "1" });
registerCutterTools(
server,
service,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "cutter-cleanup-race", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const call = (command: string) =>
client.callTool({
name: "cutter_command",
arguments: {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 1,
command,
},
});
let pending: Promise<unknown>[] = [];
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect((await call("lost response")).isError).toBe(true);
const first = call("first queued command");
const second = call("second queued command");
pending = [first, second];
await entered;
await new Promise<void>((resolve) => setImmediate(resolve));
releaseProof();
const results = await Promise.all([first, second]);
for (const result of results) expect(result.isError).not.toBe(true);
expect(confirmations).toBe(1);
expect(dispatches).toBe(3);
} finally {
releaseProof();
await Promise.allSettled(pending);
await Promise.allSettled([client.close(), server.close()]);
}
});
+260
View File
@@ -0,0 +1,260 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { chmod, writeFile } from "node:fs/promises";
import { createServer as createNetServer } from "node:net";
import { createHmac } from "node:crypto";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import {
createTestBinarySession,
createCacheProvider,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { silentLogger } from "../../../src/logger.js";
const assertUncertainEvidence = async (
client: Client,
session: ReturnType<typeof createTestBinarySession>,
sessionId: string,
): Promise<void> => {
const uncertain = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "Ps /tmp/uncertain.rzdb",
},
});
expect(uncertain.isError).toBe(true);
const uncertainText = uncertain.content
.filter(
(block): block is { type: "text"; text: string } => block.type === "text",
)
.map((block) => block.text)
.join("\n");
const uncertainError = JSON.parse(uncertainText) as {
error: { details: { partial_observation: { evidence_id: string } } };
};
const uncertainEvidence = session.evidenceById(
uncertainError.error.details.partial_observation.evidence_id,
);
expect(uncertainEvidence).toBeDefined();
if (uncertainEvidence === undefined)
throw new Error("partial Evidence missing");
expect(uncertainEvidence.normalized_result).toMatchObject({
execution_state: "unknown",
error: "transport-response-missing",
message: expect.stringContaining("do not retry automatically"),
document_generation: 3,
});
expect(uncertainEvidence.limitations).toContain(
"Command completion or its output could not be confirmed; " +
"do not retry automatically because the command may have produced " +
"partial or persistent effects.",
);
};
const assertNotStartedEvidenceAndAdmission = async (
client: Client,
sessionId: string,
): Promise<void> => {
const rejected = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "Ps /tmp/not-started.rzdb",
},
});
expect(rejected.isError, JSON.stringify(rejected)).not.toBe(true);
expect(
parseEvidence(rejected.structuredContent).normalized_result,
).toMatchObject({
execution_state: "not_started",
error: "session-poisoned-after-ui-timeout",
});
const admitted = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "iI",
},
});
expect(admitted.isError).not.toBe(true);
};
const createMcpBridge = async (
directory: string,
sessionId: string,
token: string,
): Promise<ReturnType<typeof createNetServer>> => {
let connectionOrdinal = 0;
const bridge = createNetServer((connection) => {
const ordinal = ++connectionOrdinal;
let payload = "";
let clientNonce = "";
let serverNonce = "";
connection.setEncoding("utf8");
connection.on("data", (chunk: string) => {
payload += chunk;
const newline = payload.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(payload.slice(0, newline)) as Record<
string,
unknown
>;
payload = payload.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce = `${ordinal.toString(16).padStart(16, "0")}${"c".repeat(48)}`;
const proof = createHmac("sha256", token)
.update(
`rea-cutter-server-v2:${sessionId}:${clientNonce}:${serverNonce}`,
)
.digest("hex");
connection.write(
`${JSON.stringify({ session_id: sessionId, nonce: serverNonce, proof })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
const expected = createHmac("sha256", token)
.update(
`rea-cutter-client-v2:${sessionId}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex");
if (frame.proof !== expected) {
connection.destroy();
return;
}
if (request.command === "Ps /tmp/uncertain.rzdb") {
connection.destroy();
return;
}
const notStarted = request.command === "Ps /tmp/not-started.rzdb";
const status = request.kind === "status";
const response = JSON.stringify(
request.kind === "ack"
? { ok: true, acknowledged: false }
: {
ok: !notStarted,
...(notStarted
? {
execution_state: "not_started",
error: "session-poisoned-after-ui-timeout",
}
: {}),
session_id: request.session_id,
output: status ? undefined : "synthetic Cutter command output",
current_file: "/fixtures/sample.bin",
document_generation: 3,
...(status
? {
completed_connection: (ordinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: {}),
cutter_version: "Cutter fixture version",
identity_status: "partial",
},
);
const responseProof = createHmac("sha256", token)
.update(
`rea-cutter-response-v2:${sessionId}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof: responseProof })}\n`);
});
});
await new Promise<void>((resolve) => bridge.listen(0, "127.0.0.1", resolve));
const address = bridge.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral IPv4 Cutter test bridge.");
await writeFile(
join(directory, `cutter-${process.pid}-${sessionId}.json`),
JSON.stringify({
session_id: sessionId,
pid: process.pid,
host: "127.0.0.1",
port: address.port,
token,
document_generation: 2,
current_file: null,
cutter_version: "Cutter fixture version",
identity_status: "partial",
}),
{ mode: 0o600 },
);
return bridge;
};
it("preserves live Cutter command Evidence and parity through the MCP boundary", async () => {
const directory = await createTestTempDirectory("rea-cutter-mcp-");
if (process.platform !== "win32") await chmod(directory, 0o700);
const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const token = "synthetic-cutter-bridge-token-for-mcp-test";
const bridge = await createMcpBridge(directory, sessionId, token);
onTestFinished(
async () => new Promise<void>((resolve) => bridge.close(() => resolve())),
);
const session = createTestBinarySession(createCacheProvider([]));
const server = createServer(
{ kind: "session", session },
{
logger: silentLogger,
providerEnvironment: { ...process.env, REA_CUTTER_BRIDGE_DIR: directory },
},
);
const client = new Client({ name: "cutter-mcp-boundary", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const discovery = await client.callTool({
name: "list_cutter_sessions",
arguments: {},
});
expect(discovery.isError).not.toBe(true);
expect(discovery.structuredContent).toMatchObject({
discovery_status: "sessions_found",
sessions: [{ session_id: sessionId, document_generation: 3 }],
});
const command = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "iI",
},
});
expect(command.isError).not.toBe(true);
const evidence = parseEvidence(command.structuredContent);
expect(evidence).toMatchObject({
operation: "cutter_command",
provider: { id: "cutter.python-plugin" },
normalized_result: {
command: "iI",
output: "synthetic Cutter command output",
document_generation: 3,
cutter_version: "Cutter fixture version",
},
});
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
await assertNotStartedEvidenceAndAdmission(client, sessionId);
await assertUncertainEvidence(client, session, sessionId);
});
@@ -0,0 +1,532 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisTimeoutError,
} from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { err, ok } from "../../../src/domain/result.js";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
import { silentLogger } from "../../../src/logger.js";
import { registerGdbTools } from "../../../src/server/registerGdbTools.js";
import type { GdbToolManager } from "../../../src/server/registerGdbTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
validateDebuggerStatusResponse,
waitForStartedFile,
} from "../../support/reverseDebuggerMcpTestHelpers.js";
it.skipIf(process.platform === "win32")(
"propagates MCP cancellation into a running GDB command",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-cancel-"));
const provider = join(directory, "fake-gdb.mjs");
const commandPath = join(directory, "command-started");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("auto-load off")) process.stdout.write(match[1] + "^done\\n");
else await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(commandPath)}, "started"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-cancellation", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const controller = new AbortController();
const command = client.callTool(
{
name: "gdb_console",
arguments: { session_id: sessionId, command: "shell sleep 600" },
},
{ signal: controller.signal },
);
await waitForStartedFile(commandPath);
controller.abort();
await expect(command).rejects.toThrow(/abort/iu);
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status.state).toBe("closed");
expect(status).toHaveProperty("diagnostics_truncated");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32")(
"accepts caller-selected inferior_tty and exposes verified sink status through MCP",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-tty-"));
const provider = join(directory, "fake-gdb.mjs");
const tty = `${directory}/inferior-"terminal-Ω"`;
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("inferior-tty-show")) process.stdout.write(match[1] + "^done,inferior_tty_terminal=" + ${JSON.stringify(JSON.stringify(tty))} + "\\n");
else if (line.includes("list-thread-groups")) process.stdout.write(match[1] + "^done,groups=[]\\n");
else process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-inferior-tty", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-inferior-tty", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const contract = toolContract("start_gdb_session");
expect(contract.inputSchema.safeParse({}).success).toBe(true);
expect(
contract.inputSchema.safeParse({ inferior_tty: tty }).success,
).toBe(true);
expect(contract.inputSchema.safeParse({ inferior_tty: "" }).success).toBe(
false,
);
const listed = (await client.listTools()).tools.find(
(tool) => tool.name === "start_gdb_session",
);
expect(listed?.inputSchema).toBeDefined();
expect(
new Ajv2020({ strict: false, validateFormats: false }).validate(
z.record(z.string(), z.unknown()).parse(listed?.inputSchema),
{ inferior_tty: tty },
),
).toBe(true);
const started = await client.callTool({
name: "start_gdb_session",
arguments: { inferior_tty: tty },
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status).toMatchObject({
inferior_tty: tty,
inferior_tty_verified: true,
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32")(
"exposes lossy GDB MI decoding through the strict status MCP contract",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-mi-utf8-"));
const provider = join(directory, "fake-gdb.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("auto-load off")) {
process.stdout.write(match[1] + "^done\\n");
process.stdout.write(Buffer.from([0xff, 0x0a]));
} else if (line.includes("list-thread-groups")) process.stdout.write(match[1] + "^done,groups=[]\\n");
else process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-mi-utf8", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-mi-utf8", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
await expect
.poll(() => manager.status(sessionId)?.mi_invalid_utf8)
.toBe(true);
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status.mi_invalid_utf8).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it("records partial GDB Evidence from an MCP command error", async () => {
const evidence = createEvidence(
undefined,
{
id: "gnu.gdb",
name: "GNU GDB",
version: null,
},
{
predicateType: "rea.debugger.console-observation",
operation: "gdb_console",
parameters: {
session_id: "00000000-0000-4000-8000-000000000001",
command: "info registers",
},
result: {
command: "info registers",
mi: "",
records: ["~partial"],
console: "~partial",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
rawResult: {
command: "info registers",
mi: "",
records: ["~partial"],
console: "~partial",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
subjectUnavailableReason:
"The debugger session does not identify an inferior.",
},
);
expect(
toolContract("gdb_console").outputSchema.parse(evidence),
).toMatchObject({
normalized_result: {
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
},
});
const manager = {
start: async () =>
ok({
session_id: "00000000-0000-4000-8000-000000000001",
mi_version: "mi3" as const,
}),
execute: async () =>
err(
new AnalysisTimeoutError("gdb_console", 10, {
partialObservation: evidence,
cleanup: {
reason: "MI output was unsynchronized",
resources: [evidence.parameters.session_id as string],
},
}),
),
status: () => undefined,
close: async () => ok({ target_state: "unknown" as const }),
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const recorded: string[] = [];
const server = new McpServer({ name: "gdb-partial-evidence", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
(value) => {
recorded.push(value.evidence_id);
return ok("added");
},
);
const client = new Client({ name: "gdb-partial-evidence", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "gdb_console",
arguments: {
session_id: "00000000-0000-4000-8000-000000000001",
command: "info registers",
},
});
expect(recorded).toEqual([evidence.evidence_id]);
expect(response.isError).toBe(true);
expect(response.structuredContent).toMatchObject({
error: {
details: { partial_observation: { evidence_id: evidence.evidence_id } },
},
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("recovers only the owning debugger cleanup and reopens admitted analysis", async () => {
const [fixture] = await createBinarySessionTargets();
const target = fixture.replace(/first\.hop$/u, "first.macho");
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const analysisSession = createTestBinarySession(createCacheProvider([]));
expect((await analysisSession.open(target)).ok).toBe(true);
const ownerId = "00000000-0000-4000-8000-000000000001";
const otherId = "00000000-0000-4000-8000-000000000002";
const closeCalls: string[] = [];
const retainedFailure = new AnalysisCapabilityUnavailableError(
"gdb",
"gdb_console",
"The owned debugger process could not be confirmed stopped.",
{
cleanup: { reason: "owned writer remains", resources: [ownerId] },
},
);
const manager = {
start: async () => ok({ session_id: ownerId, mi_version: "mi3" as const }),
execute: async () => err(retainedFailure),
status: () => undefined,
close: async (sessionId: string) => {
closeCalls.push(sessionId);
if (sessionId === ownerId) retainedFailure.resolveCleanup();
return ok({ target_state: "unknown" as const });
},
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const server = new McpServer({ name: "gdb-owned-cleanup", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
undefined,
analysisSession,
);
const client = new Client({ name: "gdb-owned-cleanup", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const command = await client.callTool({
name: "gdb_console",
arguments: { session_id: ownerId, command: "shell writer" },
});
expect(command.isError).toBe(true);
const wrongOwner = await client.callTool({
name: "close_gdb_session",
arguments: { session_id: otherId },
});
expect(wrongOwner.isError).toBe(true);
expect(closeCalls).toEqual([]);
expect((await analysisSession.open(target)).ok).toBe(false);
const recovered = await client.callTool({
name: "close_gdb_session",
arguments: { session_id: ownerId },
});
expect(recovered.isError ?? false).toBe(false);
expect(closeCalls).toEqual([ownerId]);
expect(retainedFailure.cleanupIncomplete).toBe(false);
expect((await analysisSession.open(target)).ok).toBe(true);
expect(analysisSession.activeTarget()?.path).toBe(target);
expect(
(await analysisSession.execute("address_name", { address: "0x1" })).ok,
).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await analysisSession.close();
}
});
it("records partial GDB startup Evidence from an MCP start error", async () => {
const evidence = createEvidence(
undefined,
{
id: "gnu.gdb",
name: "GNU GDB",
version: null,
},
{
predicateType: "rea.debugger.startup-observation",
operation: "start_gdb_session",
parameters: { command: "GDB startup" },
result: {
command: "GDB startup",
mi: "",
records: ["~startup output"],
console: "~startup output",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
rawResult: {
command: "GDB startup",
mi: "",
records: ["~startup output"],
console: "~startup output",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
subjectUnavailableReason:
"No debugger session became ready before GDB exited.",
},
);
const manager = {
start: async () =>
err(
new AnalysisTimeoutError("start_gdb_session", 10, {
partialObservation: evidence,
}),
),
execute: async () =>
err(new AnalysisCapabilityUnavailableError("gdb", "unused", "unused")),
status: () => undefined,
close: async () => ok({ target_state: "unknown" as const }),
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const recorded: string[] = [];
const server = new McpServer({
name: "gdb-startup-partial-evidence",
version: "1",
});
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
(value) => {
recorded.push(value.evidence_id);
return ok("added");
},
);
const client = new Client({
name: "gdb-startup-partial-evidence",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
expect(recorded).toEqual([evidence.evidence_id]);
expect(response.isError).toBe(true);
expect(response.structuredContent).toMatchObject({
error: {
details: { partial_observation: { evidence_id: evidence.evidence_id } },
},
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
@@ -0,0 +1,121 @@
import { chmod, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Client } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createProviderEnvironmentMcpHarness } from "../../support/reverseDebuggerMcpTestHelpers.js";
const writeProvider = async (path: string, output: string): Promise<void> => {
await writeFile(
path,
`#!${process.execPath}\nprocess.stdout.write('${output}');\n`,
);
await chmod(path, 0o755);
};
const connectProviderClient = (options: {
readonly directory: string;
readonly clientName: string;
readonly configuredProvider: string;
readonly providerEnvironment?: { REA_RIZIN_COMMAND: string };
}) =>
createProviderEnvironmentMcpHarness({
directory: options.directory,
clientName: options.clientName,
serverOptions: {
environment: { REA_RIZIN_COMMAND: options.configuredProvider },
...(options.providerEnvironment === undefined
? {}
: { providerEnvironment: options.providerEnvironment }),
},
});
const executeRizinCommand = async (
client: Client,
artifact: string,
): Promise<Awaited<ReturnType<Client["callTool"]>>> => {
const response = await client.callTool({
name: "execute_rizin_command",
arguments: { path: artifact, command: "iI" },
});
expect(response.isError).not.toBe(true);
return response;
};
it("uses the captured server environment to resolve reverse-engineering providers", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-environment-"));
const provider = join(directory, "selected-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
await writeProvider(provider, "captured-environment-provider");
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-environment",
configuredProvider: provider,
});
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"captured-environment-provider",
);
});
it("prefers an explicit provider environment over the captured server environment", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-override-"));
const configured = join(directory, "captured-rizin");
const override = join(directory, "override-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
for (const [path, output] of [
[configured, "captured"],
[override, "explicit-override"],
] as const) {
await writeProvider(path, output);
}
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-override",
configuredProvider: configured,
providerEnvironment: { REA_RIZIN_COMMAND: override },
});
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"explicit-override",
);
expect(JSON.stringify(response.structuredContent)).not.toContain(
'"captured"',
);
});
it("snapshots an explicit provider environment when the server is created", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-snapshot-"));
const configured = join(directory, "captured-rizin");
const override = join(directory, "explicit-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
for (const [path, output] of [
[configured, "captured"],
[override, "explicit-snapshot"],
] as const) {
await writeProvider(path, output);
}
const providerEnvironment = { REA_RIZIN_COMMAND: override };
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-snapshot",
configuredProvider: configured,
providerEnvironment,
});
providerEnvironment.REA_RIZIN_COMMAND = configured;
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"explicit-snapshot",
);
expect(JSON.stringify(response.structuredContent)).not.toContain(
'"captured"',
);
});
@@ -0,0 +1,507 @@
import pino from "pino";
import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { expect, it, vi } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "../../support/reverseEngineeringService.js";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
import { err, ok } from "../../../src/domain/result.js";
import type { WithAdmittedAnalysis } from "../../../src/server/analysisAdmission.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import { registerReverseEngineeringTools } from "../../../src/server/registerReverseEngineeringTools.js";
import {
createReverseEngineeringMcpHarness,
invokeWithLiveSignal,
} from "../../support/reverseEngineeringMcpHarness.js";
const createTimedOutRizinService = (): ReverseEngineeringService =>
new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("timed out"), {
stdout: "partial provider output",
stderr: "",
code: "ETIMEDOUT",
signal: null,
killed: true,
});
},
});
it("records partial Evidence and references it in the original MCP error", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = createTimedOutRizinService();
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError).toBe(true);
expect(recordEvidence).toHaveBeenCalledTimes(1);
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: {
kind: "retained-evidence",
evidence_id: expect.any(String),
},
});
});
it("admits Rizin mutation after invalidating before dispatch", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const events: string[] = [];
const service = new ReverseEngineeringService({
run: async () => {
events.push("dispatch");
return { stdout: "rizin output", stderr: "" };
},
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
() => events.push("invalidate"),
async (_path, _signal, operation) => {
events.push("admit");
return ok(await operation());
},
);
const invoke = handler("execute_rizin_command");
await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
);
expect(events).toEqual(["admit", "invalidate", "dispatch"]);
});
it("invalidates the snapshot in the legacy Rizin admission path", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidateSnapshot = vi.fn();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "rizin output", stderr: "" }),
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
invalidateSnapshot,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as { readonly isError?: boolean };
expect(response.isError).not.toBe(true);
expect(invalidateSnapshot).toHaveBeenCalledOnce();
});
it("skips snapshot invalidation for malformed Rizin input", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidateSnapshot = vi.fn();
const executeRizinCommand = vi.fn(async () =>
err(new AnalysisInputError("execute_rizin_command")),
);
const service = {
executeRizinCommand,
} as unknown as ReverseEngineeringService;
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
invalidateSnapshot,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
})) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(executeRizinCommand).toHaveBeenCalledOnce();
expect(invalidateSnapshot).not.toHaveBeenCalled();
});
it("delivers failed Rizin execution after external admission", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => {
throw new Error("Rizin command failed");
},
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
undefined,
async (_path, _signal, operation) => ok(await operation()),
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
});
it("preserves the Rizin operation error when analysis retirement also fails", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = {
retryCleanup: async () => ok(null),
executeRizinCommand: async () =>
err(new AnalysisInputError("execute_rizin_command")),
} as unknown as ReverseEngineeringService;
const observedOperationResult = vi.fn();
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
undefined,
async (_path, _signal, operation, rebindFailure) => {
const result = await operation();
observedOperationResult(result);
return err(rebindFailure(result, new AnalysisInputError("rebind")));
},
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly code?: string;
readonly details?: { readonly reason?: string };
};
};
};
expect(response.isError).toBe(true);
expect(observedOperationResult).toHaveBeenCalledWith(
expect.objectContaining({ ok: false }),
);
expect(response.structuredContent?.error).toMatchObject({
code: "invalid_request",
});
});
it.each(["success", "timeout"])(
"retains %s output and requires reopening after a symlink command",
async (outcome) => {
const [target] = await createBinarySessionTargets();
const alias = join(dirname(target), "active-target-alias.hop");
await symlink(target, alias);
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.path).toBe(target);
const originalDigest = session.activeTarget()?.sha256;
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => {
await writeFile(alias, "changed by Rizin");
if (outcome === "timeout")
throw Object.assign(new Error("timed out"), {
stdout: "partial analysis output",
stderr: "timeout diagnostics",
code: "ETIMEDOUT",
signal: null,
killed: true,
});
return { stdout: "partial analysis output", stderr: "" };
},
});
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
undefined,
() => session.invalidateSnapshotForExternalMutation(),
(path, signal, operation, rebindFailure) =>
session.withAdmittedExternalMutation(
path,
signal,
operation,
rebindFailure,
),
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: alias, command: "wx 00 @ 0" },
{ mcpReq: { signal: new AbortController().signal } },
)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly code?: string;
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError ?? false).toBe(outcome === "timeout");
if (outcome === "timeout") {
expect(response.structuredContent?.error?.code).toBe("provider_timeout");
expect(response.structuredContent?.error?.details).toMatchObject({
captured_output: {
stdout: "partial analysis output",
stderr: "timeout diagnostics",
},
});
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: {
kind: "retained-evidence",
evidence_id: expect.any(String),
},
});
}
expect(recordEvidence).toHaveBeenCalledTimes(1);
expect(session.activeTarget()).toBeUndefined();
expect((await session.execute("address_name", {})).ok).toBe(false);
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
await session.close();
await rm(dirname(target), { recursive: true, force: true });
},
);
it("preserves a partial MCP error without claiming failed Evidence retention", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = createTimedOutRizinService();
const recordEvidence = vi.fn((_evidence: unknown) =>
err(new EvidenceIntegrityError("retention failed")),
);
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError).toBe(true);
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: expect.objectContaining({
operation: "execute_rizin_command",
}),
});
expect(
JSON.stringify(response.structuredContent?.error?.details),
).not.toContain("retained-evidence");
});
it("delivers pathless objdump capability Evidence and input errors through its named tool", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "objdump output", stderr: "" }),
});
const delivery = createToolResultDelivery(2 * 1024 * 1024);
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
delivery,
);
const context = { mcpReq: { signal: new AbortController().signal } };
const objdump = handler("inspect_with_objdump");
const rizin = handler("execute_rizin_command");
const success = (await objdump(
{ path: "package.json", operation: "file_headers" },
context,
)) as { readonly isError?: boolean };
const architectures = (await objdump(
{ operation: "architectures" },
context,
)) as {
readonly isError?: boolean;
};
const objdumpFailure = (await objdump({}, context)) as {
readonly isError?: boolean;
};
const failure = (await rizin({}, context)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: { readonly code?: string };
};
};
const cancelled = new AbortController();
cancelled.abort();
const cancelledContext = { mcpReq: { signal: cancelled.signal } };
const cancelledObjdump = (await objdump(
{ path: "package.json", operation: "file_headers" },
cancelledContext,
)) as { readonly isError?: boolean };
const cancelledRizin = (await rizin(
{ path: "package.json", command: "iI" },
cancelledContext,
)) as { readonly isError?: boolean };
expect(success.isError).not.toBe(true);
expect(architectures.isError).not.toBe(true);
expect(objdumpFailure.isError).toBe(true);
expect(failure.isError).toBe(true);
expect(cancelledObjdump.isError).toBe(true);
expect(cancelledRizin.isError).toBe(true);
});
it("does not treat a malformed partial observation as retained Evidence", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidError = Object.assign(
new AnalysisInputError("execute_rizin_command"),
{ partialObservation: { evidence_id: 42 } },
);
const service = {
inspectWithObjdump: async () => err(invalidError),
executeRizinCommand: async () => err(invalidError),
} as unknown as ReverseEngineeringService;
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
)) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(recordEvidence).not.toHaveBeenCalled();
});
it("keeps provider execution and Evidence recording inside analysis admission", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const events: string[] = [];
const service = new ReverseEngineeringService({
run: async () => {
events.push("provider");
return { stdout: "objdump output", stderr: "" };
},
});
const recordEvidence = vi.fn(() => {
events.push("record");
return ok("added" as const);
});
const admission: WithAdmittedAnalysis = async (_name, _signal, operation) => {
events.push("admission-start");
const result = await operation({} as AnalysisOperationPort);
events.push("admission-end");
return ok(result);
};
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
admission,
);
const invoke = handler("inspect_with_objdump");
await invoke(
{ path: "package.json", operation: "file_headers" },
{ mcpReq: { signal: new AbortController().signal } },
);
expect(events).toEqual([
"admission-start",
"provider",
"record",
"admission-end",
]);
});
it("returns admission failures without invoking a reverse-engineering provider", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const inspectWithObjdump = vi.fn();
const service = {
inspectWithObjdump,
executeRizinCommand: vi.fn(),
} as unknown as ReverseEngineeringService;
const admission: WithAdmittedAnalysis = async () =>
err(new AnalysisInputError("inspect_with_objdump"));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
admission,
);
const invoke = handler("inspect_with_objdump");
const response = (await invoke(
{ path: "package.json", operation: "file_headers" },
{ mcpReq: { signal: new AbortController().signal } },
)) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(inspectWithObjdump).not.toHaveBeenCalled();
});
@@ -0,0 +1,84 @@
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createServer } from "../../../src/server/createServer.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
const analysis = {
execute: async () =>
ok(
createAnalysisExecution({}, { id: "test", name: "Test", version: null }),
),
};
const writeRizin = async (directory: string, output: string): Promise<void> => {
const executable = join(directory, "rizin");
await writeFile(executable, `#!/bin/sh\nprintf '%s\\n' '${output}'\n`);
await chmod(executable, 0o755);
};
it("uses the server-selected environment unless a provider environment overrides it", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-env-"));
const selectedPath = join(directory, "selected");
const overridePath = join(directory, "override");
const artifactPath = join(directory, "sample.bin");
await Promise.all([mkdir(selectedPath), mkdir(overridePath)]);
await Promise.all([
writeRizin(selectedPath, "selected environment"),
writeRizin(overridePath, "provider override"),
writeFile(artifactPath, "fixture"),
]);
try {
for (const scenario of [
{
environment: selectedPath,
expected: "selected environment",
},
{
environment: selectedPath,
provider: overridePath,
expected: "provider override",
},
]) {
const server = createServer(
{ kind: "fixed", analysis },
{
environment: { ...process.env, PATH: scenario.environment },
...(scenario.provider === undefined
? {}
: {
providerEnvironment: {
...process.env,
PATH: scenario.provider,
},
}),
},
);
const client = new Client({ name: "reverse-env-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "execute_rizin_command",
arguments: { path: artifactPath, command: "iI" },
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
raw_result: { stdout: `${scenario.expected}\n` },
});
} finally {
await Promise.all([client.close(), server.close()]);
}
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
@@ -0,0 +1,251 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "../providers/RizinTestInferiorTty.js";
import { silentLogger } from "../../../src/logger.js";
import { registerRizinDebugTools } from "../../../src/server/registerRizinDebugTools.js";
import type { RizinDebugToolManager } from "../../../src/server/registerRizinDebugTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
validateDebuggerStatusResponse,
waitForStartedFile,
} from "../../support/reverseDebuggerMcpTestHelpers.js";
it.skipIf(process.platform === "win32")(
"reports Rizin launch provenance and lossy frame decoding through MCP",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-provenance-"));
const provider = join(directory, "fake-rizin-provenance.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write(Buffer.from([0xff, 0]));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
const server = new McpServer({
name: "rizin-evidence-provenance",
version: "1",
});
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({
name: "rizin-evidence-provenance",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const callerPath = "./relative/../rizin-fixture.bin";
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: {
path: callerPath,
inferior_tty: await rizinTestInferiorTty(),
},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const command = await client.callTool({
name: "rizin_debug_command",
arguments: { session_id: sessionId, command: "dr" },
});
expect(command.isError).not.toBe(true);
const evidence = evidenceSchema.parse(command.structuredContent);
expect(evidence.parameters.launch_provenance).toEqual({
caller_selected_path: callerPath,
resolved_path: resolve(callerPath),
});
expect(evidence.normalized_result).toMatchObject({
output_invalid_utf8: true,
});
expect(evidence.limitations).toContain(
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
);
const status = await validateDebuggerStatusResponse(
client,
"rizin_debug_session_status",
sessionId,
);
expect(status.output_invalid_utf8).toBe(true);
expect(status.recent_output).toContain("�");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it("admits Rizin startup across a bound analysis session", async () => {
const [fixture] = await createBinarySessionTargets();
const target = fixture.replace(/first\.hop$/u, "first.macho");
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const analysisSession = createTestBinarySession(createCacheProvider([]));
expect((await analysisSession.open(target)).ok).toBe(true);
const initialRunId = z
.object({ analysis_run: z.object({ run_id: z.string() }) })
.parse(analysisSession.status()).analysis_run.run_id;
const manager = {
start: async () => ({
ok: true,
value: {
session_id: "00000000-0000-4000-8000-000000000001",
backend: null,
},
}),
execute: async () =>
err(new AnalysisCapabilityUnavailableError("rizin", "unused", "unused")),
status: () => undefined,
close: async () => ({ ok: true, value: { target_state: "unknown" } }),
retryCleanupFailures: async () => ok(null),
} satisfies RizinDebugToolManager;
const server = new McpServer({ name: "rizin-start-admission", version: "1" });
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
undefined,
analysisSession,
);
const client = new Client({ name: "rizin-start-admission", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: { path: target, inferior_tty: "/dev/null" },
});
expect(started.isError ?? false).toBe(false);
expect(
z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id,
).toBe("00000000-0000-4000-8000-000000000001");
expect(analysisSession.activeTarget()).toBeUndefined();
expect((await analysisSession.open(target)).ok).toBe(true);
const currentRunId = z
.object({ analysis_run: z.object({ run_id: z.string() }) })
.parse(analysisSession.status()).analysis_run.run_id;
expect(currentRunId).not.toBe(initialRunId);
expect(analysisSession.activeTarget()?.path).toBe(target);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await analysisSession.close();
}
});
it.skipIf(process.platform === "win32")(
"propagates MCP cancellation into a running Rizin debugger command",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-mcp-cancel-"));
const provider = join(directory, "fake-rizin.mjs");
const commandPath = join(directory, "command-started");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
for (const line of chunk.split("\\n")) {
if (line.startsWith("!echo ")) continue;
await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(commandPath)}, "started"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
const server = new McpServer({ name: "rizin-cancellation", version: "1" });
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "rizin-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: {
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const controller = new AbortController();
const command = client.callTool(
{
name: "rizin_debug_command",
arguments: { session_id: sessionId, command: "dr" },
},
{ signal: controller.signal },
);
await waitForStartedFile(commandPath);
controller.abort();
await expect(command).rejects.toThrow(/abort/iu);
const status = await validateDebuggerStatusResponse(
client,
"rizin_debug_session_status",
sessionId,
);
expect(status.state).toBe("closed");
expect(status).toHaveProperty("diagnostics_truncated");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
@@ -112,6 +112,12 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
idempotentHint: false,
openWorldHint: false,
},
start_gdb_session: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
export_web_scripts: {
readOnlyHint: false,
destructiveHint: false,
@@ -143,6 +149,12 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
readOnlyHint: false,
destructiveHint: false,
},
execute_rizin_command: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true,
},
} as const;
for (const [name, annotations] of Object.entries(expected))
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { access, chmod, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -21,6 +21,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import { ok } from "../../../src/domain/result.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
@@ -41,6 +42,114 @@ afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
});
describe("MCP external command snapshot retirement", () => {
it.skipIf(process.platform === "win32")(
"rejects a queued snapshot after mutation and preserves Evidence through explicit reopening",
async () => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
"rea-mcp-admitted-reverse-",
["target.hop"],
);
const targetPath = targetPaths[0];
if (targetPath === undefined)
throw new Error("Expected one workflow target");
const fixtureDirectory = dirname(snapshotPath);
const startedPath = join(fixtureDirectory, "rizin-started");
const releasePath = join(fixtureDirectory, "rizin-release");
const providerPath = join(fixtureDirectory, "rizin-fixture.mjs");
await writeFile(
providerPath,
`#!${process.execPath}\nimport { existsSync, writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(startedPath)}, "started");\nwhile (!existsSync(${JSON.stringify(releasePath)})) await new Promise((resolve) => setTimeout(resolve, 5));\nprocess.stdout.write("Rizin fixture output\\n");\n`,
);
await chmod(providerPath, 0o755);
const session = createWorkflowSession(makeProvider([], []));
const { mcp } = await connectWorkflowMcp(
session,
"admitted-reverse-engineering",
{ REA_RIZIN_COMMAND: providerPath },
);
await openWorkflowTarget(mcp, targetPath);
const analysisRequest = mcp.callTool({
name: "execute_rizin_command",
arguments: { path: targetPath, command: "iI" },
});
const readyDeadline = Date.now() + 5_000;
while (Date.now() < readyDeadline) {
try {
await access(startedPath);
break;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
await expect(access(startedPath)).resolves.toBeUndefined();
let closeSettled = false;
const closeRequest = mcp
.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
})
.finally(() => {
closeSettled = true;
});
await new Promise((resolve) => setTimeout(resolve, 50));
expect(closeSettled).toBe(false);
await expect(access(snapshotPath)).rejects.toMatchObject({
code: "ENOENT",
});
await writeFile(releasePath, "release");
const analyzed = await analysisRequest;
expect(analyzed.isError, JSON.stringify(analyzed.content)).not.toBe(true);
const evidence = toolContract("execute_rizin_command").outputSchema.parse(
analyzed.structuredContent,
);
const closed = await closeRequest;
expect(closed.isError).toBe(true);
expect(JSON.stringify(closed.content)).toContain(
"Analysis snapshots are unavailable",
);
expect(session.activeTarget()).toBeUndefined();
await expect(access(snapshotPath)).rejects.toMatchObject({
code: "ENOENT",
});
const exported = await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: join(fixtureDirectory, "observations.json") },
});
expect(exported.isError ?? false).toBe(false);
const observations = evidenceBundleSchema.parse(
JSON.parse(
await readFile(join(fixtureDirectory, "observations.json"), "utf8"),
),
);
expect(observations.records).toContainEqual(
expect.objectContaining({ evidence_id: evidence.evidence_id }),
);
// The provider process has completed; explicitly open fresh analysis
// before saving an immutable snapshot of the new binding.
await openWorkflowTarget(mcp, targetPath);
const saved = await mcp.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
});
expect(saved.isError ?? false).toBe(false);
const snapshot = await readAnalysisSnapshot(snapshotPath);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.evidence_bundle.records).toContainEqual(
expect.objectContaining({
evidence_id: evidence.evidence_id,
operation: "execute_rizin_command",
subject: expect.objectContaining({ local_path: targetPath }),
}),
);
},
);
});
describe("MCP composed workflow target admission", () => {
it("keeps a composed result and snapshot on its admitted target across queued close and open", async () => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
@@ -448,10 +557,14 @@ const createWorkflowSession = (provider: AnalysisProvider) =>
const connectWorkflowMcp = async (
session: ReturnType<typeof createWorkflowSession>,
clientName: string,
providerEnvironment?: Readonly<NodeJS.ProcessEnv>,
): Promise<{ readonly mcp: Client }> => {
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
{
logger: silentLogger,
...(providerEnvironment === undefined ? {} : { providerEnvironment }),
},
);
const mcp = new Client({ name: clientName, version: "1.0.0" });
const [clientTransport, serverTransport] =
+125 -1
View File
@@ -12,7 +12,10 @@ import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../../src/process/ProcessOwnershipObservation.js";
import {
prepareProcessOwnershipInspection,
systemProcessOwnershipHost,
} from "../../../src/process/ProcessOwnershipObservation.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
const command = (script: string) => ({
@@ -152,6 +155,127 @@ it("fails an accepted nonzero command when an output stream errors and cleans it
expect(cleanup).toHaveBeenCalledOnce();
});
it("marks an output collection error when the process itself exits zero", async () => {
const stdout = new PassThrough();
const stderr = new PassThrough();
class FakeProcess extends EventEmitter {
readonly stdout = stdout;
readonly stderr = stderr;
exitCode: number | null = null;
signalCode: NodeJS.Signals | null = null;
readonly pid = 41235;
kill(): boolean {
return true;
}
}
const child = new FakeProcess();
const request = command("unused fake launcher command");
const failure = runOwnedCommand(
request,
{ timeoutMs: 2_000, diagnosticBytes: 1024, acceptNonZeroExit: true },
{
launcher: async () => {
setImmediate(() => {
stdout.write("partial output");
stdout.destroy(new Error("fixture read failure"));
stderr.end();
child.exitCode = 0;
child.emit("exit", 0, null);
child.emit("close", 0, null);
});
return {
process: child,
ownership: {
runId: request.runId,
leaderPid: child.pid,
processGroupId: child.pid,
},
cleanup: async () => ({ cleaned: true, signaled: false }),
};
},
},
);
await expect(failure).rejects.toMatchObject({
reason: "process",
collectionFailure: true,
message: "stdout stream failed: fixture read failure",
snapshot: { stdout: { text: "partial output" }, exitCode: 0 },
});
});
it.skipIf(process.platform === "win32")(
"sweeps detached run-token descendants and preserves a pre-existing unrelated process",
async () => {
const runId = `rea-owned-descendant-test-${randomUUID()}`;
const unrelated = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: ["-e", "setInterval(() => undefined, 1000)"],
runId: `${runId}-unrelated`,
hostEnvironment: process.env,
});
let descendantPid: number | undefined;
try {
const result = await runOwnedCommand(
{
...command(`
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "setInterval(() => undefined, 1000)"], {
detached: true,
stdio: "ignore",
});
child.unref();
process.stdout.write(String(child.pid));
`),
runId,
sweepTokenOwnedProcesses: true,
},
{ timeoutMs: 5_000, diagnosticBytes: 1024 },
);
descendantPid = Number(result.stdout.text);
expect(Number.isSafeInteger(descendantPid)).toBe(true);
let remainsLive = true;
const deadline = Date.now() + 2_000;
while (remainsLive && Date.now() < deadline) {
remainsLive = (await systemProcessOwnershipHost.listProcesses()).some(
({ pid }) => pid === descendantPid,
);
if (remainsLive) await delay(25);
}
expect(remainsLive).toBe(false);
expect(() => process.kill(unrelated.process.pid!, 0)).not.toThrow();
} finally {
if (descendantPid !== undefined) {
try {
process.kill(descendantPid, "SIGKILL");
} catch {
// The run-token sweep may already have removed it.
}
}
await cleanupOwnedProcessGroup(unrelated.ownership);
}
},
);
it.skipIf(process.platform === "win32")(
"fails before provider spawn when a requested ownership baseline cannot be captured",
async () => {
const baseline = vi
.spyOn(systemProcessOwnershipHost, "captureBaseline")
.mockRejectedValue(new Error("baseline unavailable"));
try {
await expect(
runOwnedCommand(
{ ...command("process.exit(0)"), sweepTokenOwnedProcesses: true },
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
),
).rejects.toThrow("baseline unavailable");
} finally {
baseline.mockRestore();
}
},
);
it("cancels a real acquired process and independently releases it", async () => {
const controller = new AbortController();
let pid: number | undefined;
File diff suppressed because it is too large Load Diff
@@ -188,6 +188,40 @@ describe("provider process runtime and wait primitives", () => {
});
describe("provider process output and cleanup primitives", () => {
it("marks retained provider output that cannot be represented as UTF-8", async () => {
const child = spawnProviderProcessFixture("invalid-utf8");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "a�b", invalidUtf8: true },
stderr: { text: "c�d", invalidUtf8: true },
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("marks a retained byte prefix that cuts a valid multibyte UTF-8 character", async () => {
const child = spawnProviderProcessFixture("valid-multibyte");
const supervisor = new ProviderProcessSupervisor(
{ process: child, ownsProcessLifetime: true },
{ maxDiagnosticBytes: 2 },
);
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "�", bytes: 2, observedBytes: 3, invalidUtf8: true },
diagnosticTruncated: true,
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("retains complete stdout and stderr beyond the former fixed ceiling", async () => {
const outputBytes = 70_000;
const child = spawnProviderProcessFixture("burst", outputBytes);
@@ -1,4 +1,7 @@
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import type { Socket } from "node:net";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import {
ProviderProcessSupervisor,
type ProviderProcessDiagnostic,
@@ -8,6 +11,26 @@ import {
stopProviderProcessFixture,
} from "../../fixtures/providerProcess.js";
it("unreferences inherited output streams without closing them", async () => {
const child = spawnProviderProcessFixture("stubborn");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
const stdoutUnref = vi.spyOn(child.stdout as Socket, "unref");
const stderrUnref = vi.spyOn(child.stderr as Socket, "unref");
try {
supervisor.unrefOutputStreams();
expect(stdoutUnref).toHaveBeenCalledOnce();
expect(stderrUnref).toHaveBeenCalledOnce();
expect(child.stdout!.destroyed).toBe(false);
expect(child.stderr!.destroyed).toBe(false);
} finally {
await supervisor.stop();
await stopProviderProcessFixture(child);
}
});
it("bounds capture before diagnostic callbacks while draining both output streams", async () => {
const child = spawnProviderProcessFixture("burst", 70_000);
const diagnostics: ProviderProcessDiagnostic[] = [];
@@ -46,3 +69,30 @@ it("bounds capture before diagnostic callbacks while draining both output stream
await stopProviderProcessFixture(child);
}
});
it("bounds additional late output while retaining observed byte counts", () => {
const child = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null as number | null,
signalCode: null as NodeJS.Signals | null,
kill: vi.fn(() => true),
});
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("abc");
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("defgh");
child.stderr.write("ijkl");
const snapshot = supervisor.snapshot();
expect(snapshot.stdout.text + snapshot.stderr.text).toHaveLength(5);
expect(snapshot.stdout.observedBytes).toBe(8);
expect(snapshot.stderr.observedBytes).toBe(4);
expect(snapshot.diagnosticTruncated).toBe(true);
supervisor.dispose();
});
@@ -0,0 +1,132 @@
import { randomUUID } from "node:crypto";
import { chmod, writeFile } from "node:fs/promises";
import { createServer, type Socket } from "node:net";
import { join } from "node:path";
import { expect, it } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import { cutterDiscoverySchema } from "../../../src/contracts/cutterToolContracts.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const descriptor = async (directory: string, port: number): Promise<string> => {
const sessionId = randomUUID();
await writeFile(
join(directory, `cutter-${process.pid}-${sessionId}.json`),
JSON.stringify({
session_id: sessionId,
pid: process.pid,
host: "127.0.0.1",
port,
token: "capacity-test-token-123456789",
document_generation: 0,
current_file: null,
cutter_version: null,
identity_status: "partial",
}),
{ mode: 0o600 },
);
return sessionId;
};
it("reports descriptor capacity without opening candidates or claiming no live sessions", async () => {
const directory = await createTestTempDirectory("rea-cutter-capacity-");
await chmod(directory, 0o700);
const selectedSession = await descriptor(directory, 1);
for (let index = 1; index < 257; index += 1) await descriptor(directory, 1);
const client = new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
);
const result = await client.listSessions();
expect(cutterDiscoverySchema.parse(result)).toMatchObject({
sessions: [],
discovery_status: "bridge_directory_capacity_exceeded",
bridge_directory_security: "private_verified",
});
const service = new CutterBridgeService(client);
expect(
await service.execute({
session_id: selectedSession,
expected_generation: 0,
command: "iI",
json: false,
}),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
cleanupIncomplete: false,
},
});
});
it("bounds simultaneous socket probes while examining every admitted descriptor", async () => {
const directory = await createTestTempDirectory("rea-cutter-probes-");
await chmod(directory, 0o700);
const sockets = new Set<Socket>();
let peak = 0;
let probes = 0;
const server = createServer((socket) => {
sockets.add(socket);
probes += 1;
peak = Math.max(peak, sockets.size);
socket.once("close", () => sockets.delete(socket));
setTimeout(() => socket.destroy(), 20);
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
try {
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("listener missing");
for (let index = 0; index < 24; index += 1)
await descriptor(directory, address.port);
const client = new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
);
expect((await client.listSessions()).discovery_status).toBe(
"no_live_bridge_found",
);
expect(probes).toBe(24);
expect(peak).toBeGreaterThan(1);
expect(peak).toBeLessThanOrEqual(8);
} finally {
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it("rejects expanded authenticated frames before dispatch and retains no cleanup owner", async () => {
const directory = await createTestTempDirectory("rea-cutter-frame-");
await chmod(directory, 0o700);
const sessionId = await descriptor(directory, 1);
const service = new CutterBridgeService(
new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
),
);
const input = { session_id: sessionId, expected_generation: 0, json: false };
const rejected = await service.execute({
...input,
command: '"'.repeat(4 * 1024 * 1024 + 1024),
});
expect(rejected).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
cleanupIncomplete: false,
},
});
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
// A later valid command reaches transport, rather than replaying the resource failure.
expect(await service.execute({ ...input, command: "iI" })).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
cleanupIncomplete: false,
},
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,177 @@
import { createServer } from "node:net";
import { createHmac } from "node:crypto";
import { readFileSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
const SESSION_ID = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const TOKEN = "synthetic-cutter-bridge-token-for-test";
let directory: string | undefined;
let server: ReturnType<typeof createServer> | undefined;
afterEach(async () => {
if (server !== undefined)
await new Promise<void>((resolve) => server?.close(() => resolve()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
server = undefined;
directory = undefined;
});
const listen = async (
listener: ReturnType<typeof createServer>,
): Promise<number> => {
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const address = listener.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral IPv4 listener");
return address.port;
};
const bridgeServer = (
currentFile: string | null,
documentGeneration: number,
): ReturnType<typeof createServer> => {
let ordinal = 0;
return createServer((connection) => {
const connectionOrdinal = ++ordinal;
connection.setEncoding("utf8");
let input = "";
let clientNonce = "";
let serverNonce = "";
connection.on("data", (chunk: string) => {
input += chunk;
const newline = input.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(input.slice(0, newline)) as Record<
string,
unknown
>;
input = input.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce =
connectionOrdinal.toString(16).padStart(16, "0") + "d".repeat(48);
connection.write(
`${JSON.stringify({ session_id: SESSION_ID, nonce: serverNonce, proof: createHmac("sha256", TOKEN).update(`rea-cutter-server-v2:${SESSION_ID}:${clientNonce}:${serverNonce}`).digest("hex") })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
const expected = createHmac("sha256", TOKEN)
.update(
`rea-cutter-client-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex");
if (frame.proof !== expected) {
connection.destroy();
return;
}
if (!["status", "command", "ack"].includes(String(request.kind)))
throw new Error(`Unmodeled bridge request: ${String(request.kind)}`);
const response = JSON.stringify(
request.kind === "ack"
? {
ok: true,
acknowledged: false,
}
: {
ok: true,
session_id: request.session_id,
current_file: currentFile,
document_generation: documentGeneration,
cutter_version: "Cutter fixture version",
identity_status: "partial",
...(request.kind === "status"
? {
completed_connection: (connectionOrdinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: { execution_state: "complete" }),
},
);
const proof = createHmac("sha256", TOKEN)
.update(
`rea-cutter-response-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof })}\n`);
});
});
};
const clientFor = (bridgeDirectory: string): CutterBridgeClient =>
process.platform === "win32"
? new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: bridgeDirectory },
{
windowsPrivateReader: {
verifyDirectory: () => true,
readDescriptor: (root, name, maxBytes) => {
const bytes = readFileSync(join(root, name));
if (bytes.byteLength > maxBytes)
throw new Error("Descriptor too large");
return bytes;
},
},
},
)
: new CutterBridgeClient({ REA_CUTTER_BRIDGE_DIR: bridgeDirectory });
const writeDescriptor = async (port: number): Promise<void> => {
if (directory === undefined) throw new Error("Test directory is unavailable");
await writeFile(
join(directory, `cutter-${process.pid}-${SESSION_ID}.json`),
JSON.stringify({
session_id: SESSION_ID,
pid: process.pid,
host: "127.0.0.1",
port,
token: TOKEN,
document_generation: 1,
current_file: "/old/sample.bin",
cutter_version: "Cutter fixture version",
identity_status: "partial",
}),
{ mode: 0o600 },
);
};
it("preserves a live Cutter status that explicitly has no active document", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-status-"));
server = bridgeServer(null, 2);
await writeDescriptor(await listen(server));
const result = await clientFor(directory).listSessions();
expect(result.sessions[0]).toMatchObject({
session_id: SESSION_ID,
document_generation: 2,
current_file: null,
});
});
it("preserves a null active document returned after a Cutter command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-command-"));
server = bridgeServer(null, 2);
await writeDescriptor(await listen(server));
const result = await clientFor(directory).execute({
sessionId: SESSION_ID,
expectedGeneration: 2,
command: "ij",
json: true,
});
expect(result.currentFile).toBeNull();
});
@@ -0,0 +1,406 @@
import { expect, it, vi } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
const cutterInput = {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "pd 4",
};
it("retains uncertain command completion as Evidence without encouraging a retry", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => ({
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: "unknown",
error: "transport-response-missing",
message: "The command may have completed; do not retry automatically",
outputTruncated: false,
}),
});
const result = await service.execute({
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "Ps /tmp/project.rzdb",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
partialObservation: {
normalized_result: {
command: "Ps /tmp/project.rzdb",
output: null,
execution_state: "unknown",
error: "transport-response-missing",
message: expect.stringContaining("do not retry automatically"),
document_generation: 7,
cutter_version: "Cutter fixture version",
},
limitations: expect.arrayContaining([
"Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.",
]),
provider: { version: "Cutter fixture version" },
},
},
});
});
it("clears a poisoned command only after its exact UI-dispatcher receipt", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const wrongId = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
let receipt: string | undefined;
let uiPending = true;
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipt === id && !uiPending
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: dispatches === 1 ? "unknown" : "complete",
error: dispatches === 1 ? "ui-thread-request-timeout" : null,
message: null,
outputTruncated: false,
};
},
});
const first = await service.execute(cutterInput);
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
for (const unconfirmed of [
undefined,
"ede4bbfd-6348-46aa-963b-0de0e78ccbdc",
wrongId,
]) {
receipt = unconfirmed;
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
}
receipt = requestId;
const pending = await service.execute(cutterInput);
expect(pending).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
expect(confirmCommandCompletion).toHaveBeenLastCalledWith(
cutterInput.session_id,
requestId,
undefined,
);
receipt = requestId;
uiPending = false;
const recovered = await service.execute(cutterInput);
expect(recovered.ok).toBe(true);
expect(dispatches).toBe(2);
});
it("recovers canceled command A after B and does not retain poisoned B", async () => {
const requestA = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const completionTokenA = "0000000000000007";
const requestB = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
const receipts = new Set<string>();
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipts.delete(id)
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const execute = async () => {
dispatches += 1;
if (dispatches === 1) {
receipts.add(requestA);
return {
requestId: requestA,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
completionToken: completionTokenA,
};
}
if (dispatches === 2)
return {
requestId: requestB,
output: "B complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
if (dispatches === 3)
return {
requestId: requestB,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "not_started" as const,
error: "session-poisoned-after-ui-timeout",
message: null,
outputTruncated: false,
};
return {
requestId: "c31130c6-fc6c-46ad-949e-586724d8fd84",
output: "recovered",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
};
const client = {
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found" as const,
bridge_directory_security: "private_verified" as const,
}),
confirmCommandCompletion,
execute,
};
const callerA = new CutterBridgeService(client);
const callerB = new CutterBridgeService(client);
const cancelledA = await callerA.execute(cutterInput);
expect(cancelledA).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(await callerB.execute(cutterInput)).toMatchObject({ ok: true });
expect(receipts.has(requestA)).toBe(true);
const poisonedB = await callerA.execute(cutterInput);
expect(poisonedB).toMatchObject({
ok: true,
value: { normalized_result: { execution_state: "not_started" } },
});
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(confirmCommandCompletion).toHaveBeenCalledWith(
cutterInput.session_id,
requestA,
completionTokenA,
);
expect(await callerA.execute(cutterInput)).toMatchObject({ ok: true });
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(dispatches).toBe(4);
});
it("rejects malformed Cutter commands and pre-aborted calls", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw new Error("must not dispatch");
},
});
const malformed = await service.execute({ ...cutterInput, command: "" });
expect(malformed).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
const controller = new AbortController();
controller.abort();
const cancelled = await service.execute(cutterInput, {
signal: controller.signal,
});
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each([
[new Error("session generation changed"), "AnalysisInputError"],
[new Error("bridge disconnected"), "AnalysisCapabilityUnavailableError"],
["plain failure", "AnalysisCapabilityUnavailableError"],
])("maps a Cutter bridge failure to %s", async (failure, tag) => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw failure;
},
});
const result = await service.execute(cutterInput);
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
});
it("preserves cancellation unless the bridge reports an ambiguous completion", async () => {
const createService = (message: string, controller: AbortController) =>
new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
controller.abort();
throw new Error(message);
},
});
const cancelledController = new AbortController();
const cancelled = await createService(
"transport cancelled",
cancelledController,
).execute(cutterInput, { signal: cancelledController.signal });
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
const uncertainController = new AbortController();
const uncertain = await createService(
"command may have completed",
uncertainController,
).execute(cutterInput, { signal: uncertainController.signal });
expect(uncertain).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
it("shares one cleanup attempt when commands retry the same receipt together", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
let receiptPresent = false;
let releaseConfirm: (() => void) | undefined;
let confirms = 0;
const confirmCommandCompletion = vi.fn(async () => {
confirms += 1;
if (!receiptPresent) return { ok: true as const, value: false };
if (confirms === 1) {
await new Promise<void>((resolve) => {
releaseConfirm = resolve;
});
}
if (!receiptPresent) return { ok: true as const, value: false };
receiptPresent = false;
return { ok: true as const, value: true };
});
let dispatches = 0;
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
if (dispatches === 1) {
receiptPresent = true;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
};
}
return {
requestId: "8ca93d11-107d-41ed-8b40-31dd53cd26a6",
output: "complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
},
});
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const concurrent = [
service.execute(cutterInput),
service.execute(cutterInput),
];
if (releaseConfirm === undefined) throw new Error("cleanup did not start");
releaseConfirm();
const recovered = await Promise.all(concurrent);
expect(recovered.every((result) => result.ok)).toBe(true);
expect(confirms).toBe(1);
expect(dispatches).toBe(3);
});
@@ -0,0 +1,145 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
let directory: string | undefined;
const managers: GdbSessionManager[] = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("bounds active and queued GDB commands, including cancelled placeholders", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-command-queue-limit-"));
const provider = join(directory, "fake-gdb-queue.mjs");
const activePath = join(directory, "active-command");
const releasePath = join(directory, "release-command");
await writeFile(
provider,
`#!${process.execPath}
import { access, writeFile } from "node:fs/promises";
process.stdout.write("(gdb)\\n");
let input = "";
let firstConsoleCommand = true;
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("-interpreter-exec console") && firstConsoleCommand) {
firstConsoleCommand = false;
await writeFile(${JSON.stringify(activePath)}, "active");
for (;;) {
try { await access(${JSON.stringify(releasePath)}); break; }
catch { await new Promise((resolve) => setTimeout(resolve, 10)); }
}
}
process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(true);
if (!started.ok) return;
const active = manager.execute(started.value.session_id, "hold");
let activeSeen = false;
for (let attempt = 0; attempt < 100 && !activeSeen; attempt += 1) {
try {
await readFile(activePath, "utf8");
activeSeen = true;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
expect(activeSeen).toBe(true);
const controllers = Array.from({ length: 15 }, () => new AbortController());
const queued = controllers.map((controller, index) =>
manager.execute(
started.value.session_id,
`queued-${index}`,
controller.signal,
),
);
const safetyRelease = setTimeout(() => {
void writeFile(releasePath, "safety release");
}, 250);
const overflow = await manager.execute(started.value.session_id, "overflow");
clearTimeout(safetyRelease);
expect(overflow).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
operation: "gdb_console",
resource: "transport",
reportedLimits: {
max_pending_commands: 16,
active_or_queued_commands: 16,
},
},
});
for (const controller of controllers) controller.abort();
const cancelled = await Promise.all(queued);
expect(cancelled).toHaveLength(15);
expect(
cancelled.every(
(result) => !result.ok && result.error._tag === "AnalysisCancelledError",
),
).toBe(true);
const cancellationSafetyRelease = setTimeout(() => {
void writeFile(releasePath, "safety release after cancellation");
}, 250);
try {
await expect(
manager.execute(
started.value.session_id,
"cannot-bypass-cancelled-placeholders",
),
).resolves.toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
reportedLimits: { active_or_queued_commands: 16 },
},
});
} finally {
clearTimeout(cancellationSafetyRelease);
}
await writeFile(releasePath, "release");
expect((await active).ok).toBe(true);
const admittedAfterDrain = await manager.execute(
started.value.session_id,
"admitted-after-drain",
);
expect(admittedAfterDrain.ok).toBe(true);
await expect(
manager.execute(started.value.session_id, "after-drain"),
).resolves.toMatchObject({
ok: true,
value: { result: { completion_status: "complete" } },
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,109 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
describe("persistent debugger session managers", () => {
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("runs a correlated GDB MI command, reports status, and closes its owned process", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-manager-"));
const provider = join(directory, "fake-gdb.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
const match = /^(\\d+)/.exec(line);
if (match && line.includes("list-thread-groups"))
process.stdout.write(match[1] + "^done,groups=[]\\n");
else if (match) process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(true);
if (!started.ok) return;
expect(manager.status(started.value.session_id)?.state).toBe("ready");
const result = await manager.execute(
started.value.session_id,
"show version",
);
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.mi).toMatch(/^\d+\^done/u);
const closed = await manager.close(started.value.session_id);
expect(closed.ok).toBe(true);
expect(manager.status(started.value.session_id)).toBeUndefined();
});
it("does not start GDB when it rejects the required auto-load setting", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-autoload-"));
const provider = join(directory, "fake-gdb-reject.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
const match = /^(\\d+)(.*)/.exec(line);
if (match) process.stdout.write(match[1] + (match[2].includes("-gdb-set auto-load off") ? "^error,msg=\\"rejected\\"\\n" : "^done\\n"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(false);
if (!started.ok)
expect(JSON.stringify(started.error)).toContain(
"automatic-loading disable command",
);
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import {
createRizinCommandTimeoutError,
isRizinCommandDeadlineExpired,
RizinCommandTimeoutError,
} from "../../../src/rizin/RizinDebugSessionManager.js";
describe("Rizin command timeout semantics", () => {
it("treats zero and negative remaining time as expired", () => {
expect(isRizinCommandDeadlineExpired(1)).toBe(false);
expect(isRizinCommandDeadlineExpired(0)).toBe(true);
expect(isRizinCommandDeadlineExpired(-1)).toBe(true);
});
it("retains partial frames separated by newlines in the timeout error", () => {
const error = createRizinCommandTimeoutError([
"first frame",
"second frame",
]);
expect(error).toBeInstanceOf(RizinCommandTimeoutError);
expect(error.partialOutput).toBe("first frame\nsecond frame");
expect(error.message).toBe(
"Timed out waiting for Rizin's command-completion marker",
);
});
});
@@ -0,0 +1,245 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { EventEmitter } from "node:events";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough, Writable } from "node:stream";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
import type {
ProviderProcessHandle,
SpawnedOwnedProviderProcess,
} from "../../../src/process/ProviderProcess.js";
interface InjectedProcessControl {
output(chunk: Buffer | string): void;
stdinError(): void;
closeStdin(): void;
exitLeader(signal?: NodeJS.Signals): void;
closeOutput(): void;
exit(signal?: NodeJS.Signals): void;
}
type InjectedSpawnProcess = NonNullable<
NonNullable<
ConstructorParameters<typeof RizinDebugSessionManager>[1]
>["spawnProcess"]
>;
export const incompleteStop: typeof stopOwnedDebuggerProcess = async (
session,
name,
) => {
await stopOwnedDebuggerProcess(session, name);
return { status: "incomplete", reason: "injected stop uncertainty" };
};
export const abortOnCheck = (targetCheck: number): AbortSignal => {
let checks = 0;
let aborted = false;
type Listener = Parameters<AbortSignal["addEventListener"]>[1];
const listeners = new Set<Listener>();
return {
get aborted() {
checks += 1;
if (checks >= targetCheck) aborted = true;
return aborted;
},
addEventListener: (
_type: Parameters<AbortSignal["addEventListener"]>[0],
listener: Listener,
) => {
if (listener !== null) listeners.add(listener);
},
removeEventListener: (
_type: Parameters<AbortSignal["removeEventListener"]>[0],
listener: Parameters<AbortSignal["removeEventListener"]>[1],
) => {
if (listener !== null) listeners.delete(listener);
},
dispatchEvent: () => true,
onabort: null,
reason: undefined,
throwIfAborted: () => undefined,
} as AbortSignal;
};
export const createInjectedProcess = (
options: {
readonly stdin?:
| "normal"
| "null"
| "destroyed"
| "throws"
| "throws-opaque"
| "write-error";
readonly onWrite?: (text: string, control: InjectedProcessControl) => void;
readonly startup?: (control: InjectedProcessControl) => void;
readonly beforeSpawnReturns?: () => void;
readonly spawnError?: unknown;
} = {},
): {
readonly spawnProcess: InjectedSpawnProcess;
readonly control: InjectedProcessControl;
} => {
const stdout = new PassThrough();
const stderr = new PassThrough();
let exitCode: number | null = null;
let signalCode: NodeJS.Signals | null = null;
const processHandle = new EventEmitter() as EventEmitter & {
pid: number;
stdout: PassThrough;
stdin: Writable | null;
stderr: PassThrough;
exitCode: number | null;
signalCode: NodeJS.Signals | null;
kill(signal?: NodeJS.Signals | number): boolean;
};
processHandle.pid = process.pid;
processHandle.stdout = stdout;
processHandle.stderr = stderr;
processHandle.exitCode = exitCode;
processHandle.signalCode = signalCode;
const control: InjectedProcessControl = {
output: (chunk) => stdout.emit("data", Buffer.from(chunk)),
stdinError: () => stdin?.emit("error", new Error("injected stdin error")),
closeStdin: () => stdin?.destroy(),
exitLeader: (signal = "SIGTERM") => {
exitCode = null;
signalCode = signal;
processHandle.exitCode = exitCode;
processHandle.signalCode = signalCode;
processHandle.emit("exit", exitCode, signalCode);
},
closeOutput: () => {
stdout.destroy();
stderr.destroy();
processHandle.emit("close", exitCode, signalCode);
},
exit: (signal = "SIGTERM") => {
control.exitLeader(signal);
control.closeOutput();
},
};
const stdin =
options.stdin === "null"
? null
: new Writable({
write(chunk, _encoding, callback) {
options.onWrite?.(Buffer.from(chunk).toString("utf8"), control);
callback(
options.stdin === "write-error"
? new Error("injected write callback failure")
: undefined,
);
},
});
if (stdin !== null) {
if (options.stdin === "destroyed")
Object.defineProperty(stdin, "destroyed", { value: true });
if (options.stdin === "throws" || options.stdin === "throws-opaque")
stdin.write = (() => {
if (options.stdin === "throws-opaque")
throw "injected opaque write failure";
throw new Error("injected synchronous write failure");
}) as typeof stdin.write;
processHandle.stdin = stdin;
} else processHandle.stdin = null;
processHandle.kill = (signal = "SIGTERM") => {
if (exitCode !== null || signalCode !== null) return false;
control.exit(typeof signal === "string" ? signal : "SIGTERM");
return true;
};
const spawnProcess: InjectedSpawnProcess = async (spawnOptions) => {
options.beforeSpawnReturns?.();
if (options.spawnError !== undefined) throw options.spawnError;
setImmediate(() => {
if (options.startup !== undefined) options.startup(control);
else control.output(Buffer.from([0]));
});
return {
process: processHandle as unknown as ProviderProcessHandle,
ownership: {
runId: spawnOptions.runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
} satisfies SpawnedOwnedProviderProcess;
};
return { spawnProcess, control };
};
export const createRizinCoverageHarness = () => {
let directory: string | undefined;
const managers: RizinDebugSessionManager[] = [];
const track = (manager: RizinDebugSessionManager): void => {
managers.push(manager);
};
const makeProvider = async (
body: string,
shebang = "#!/usr/bin/env node",
): Promise<string> => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-coverage-"));
const provider = join(directory, "fake-rizin.mjs");
await writeFile(provider, `${shebang}\n${body}\n`);
await chmod(provider, 0o700);
return provider;
};
const start = async (
provider: string,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
): Promise<{ manager: RizinDebugSessionManager; sessionId: string }> => {
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
options,
);
track(manager);
const result = await manager.start({
path: "/tmp/coverage-target",
inferior_tty: await rizinTestInferiorTty(),
});
if (!result.ok) throw result.error;
return { manager, sessionId: result.value.session_id };
};
const startInjected = async (
spawnProcess: InjectedSpawnProcess,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
) => {
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ ...options, spawnProcess },
);
track(manager);
const started = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
return { manager, started };
};
const cleanup = async (): Promise<void> => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
};
const missingProviderPath = (): string => join(directory!, "does-not-exist");
return {
cleanup,
makeProvider,
missingProviderPath,
start,
startInjected,
track,
};
};
@@ -0,0 +1,422 @@
import { afterEach, expect, it, vi } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
stopFakeNoInferior,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { rizinCommand } from "../../../src/rizin/RizinCommand.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import {
createRizinCoverageHarness,
createInjectedProcess,
abortOnCheck,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const {
cleanup,
makeProvider,
missingProviderPath,
start,
startInjected,
track,
} = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"builds the one-shot command with the caller's path and command",
() => {
expect(rizinCommand({ path: "./sample file", command: "izz" })).toEqual([
"-N",
"-q",
"-c",
"izz",
expect.stringMatching(/sample file/u),
]);
},
);
it.skipIf(process.platform === "win32")(
"rejects unsupported, pre-cancelled, and failed startup requests",
async () => {
const windows = createRizinTestManager({}, { platform: "win32" });
expect(
(
await windows.start({
path: "/tmp/a",
inferior_tty: "unused-before-platform-admission",
})
).ok,
).toBe(false);
const aborted = new AbortController();
aborted.abort();
expect(
(
await windows.start(
{ path: "/tmp/a", inferior_tty: await rizinTestInferiorTty() },
aborted.signal,
)
).ok,
).toBe(false);
const failed = await makeProvider("process.exit(9);");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: failed,
});
track(manager);
const result = await manager.start({
path: "/tmp/a",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
const missing = createRizinTestManager({
REA_RIZIN_COMMAND: missingProviderPath(),
});
track(missing);
const spawnFailure = await missing.start({
path: "/tmp/a",
inferior_tty: await rizinTestInferiorTty(),
});
expect(spawnFailure.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"returns a startup timeout when Rizin exits before its initial frame",
async () => {
const provider = await makeProvider("process.exit(0);");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
track(manager);
const result = await manager.start({
path: "/tmp/early-exit",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"times out startup through the frame wait when Rizin never emits a frame",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const injected = createInjectedProcess({
startup: () => undefined,
beforeSpawnReturns: resolveSpawned,
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: injected.spawnProcess,
stopProcess: async () => ({ status: "stopped" }),
},
);
track(manager);
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const starting = manager.start({
path: "/tmp/no-startup-frame",
inferior_tty: await rizinTestInferiorTty(),
});
await spawned;
await vi.advanceTimersByTimeAsync(30_001);
const result = await starting;
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.message).toContain("timed out");
} finally {
vi.useRealTimers();
}
},
);
it.skipIf(process.platform === "win32")(
"does not spawn Rizin when cancellation arrives during TTY validation",
async () => {
let spawned = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn after cancellation");
},
},
);
const result = await manager.start(
{
path: "/tmp/cancel-before-spawn",
inferior_tty: await rizinTestInferiorTty(),
},
abortOnCheck(2),
);
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"rejects a non-TTY path before spawning Rizin",
async () => {
let spawned = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn with an invalid TTY");
},
},
);
const result = await manager.start({
path: "/tmp/not-a-tty-target",
inferior_tty: "/dev/null",
});
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"closeAll drains concurrent startups and blocks later admission",
async () => {
let spawnCount = 0;
let resolveSpawnCalls!: () => void;
const bothSpawnsCalled = new Promise<void>((resolve) => {
resolveSpawnCalls = resolve;
});
let releaseSpawns!: () => void;
const spawnGate = new Promise<void>((resolve) => {
releaseSpawns = resolve;
});
const injected = createInjectedProcess();
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async (options) => {
spawnCount += 1;
if (spawnCount === 2) resolveSpawnCalls();
await spawnGate;
return injected.spawnProcess(options);
},
stopProcess: async () => ({ status: "stopped" }),
},
);
const tty = await rizinTestInferiorTty();
const starts = [
manager.start({ path: "/tmp/start-one", inferior_tty: tty }),
manager.start({ path: "/tmp/start-two", inferior_tty: tty }),
];
await bothSpawnsCalled;
let closeAllResolved = false;
const closing = manager.closeAll().then(() => {
closeAllResolved = true;
});
await Promise.resolve();
expect(closeAllResolved).toBe(false);
releaseSpawns();
const started = await Promise.all(starts);
expect(started.every((result) => result.ok)).toBe(true);
await closing;
expect(
manager.status(started[0]!.ok ? started[0]!.value.session_id : "missing"),
).toBeUndefined();
expect(
(await manager.start({ path: "/tmp/after-close-all", inferior_tty: tty }))
.ok,
).toBe(false);
expect((await manager.close("missing")).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"rejects an oversized initial frame instead of marking the session ready",
async () => {
const provider = await makeProvider(
'process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0"); process.stdin.resume();',
);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
track(manager);
const result = await manager.start({
path: "/tmp/oversized-startup",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels startup while waiting for the initial NUL frame",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const provider = await makeProvider(
'setTimeout(() => process.stdout.write("\\0"), 500); process.stdin.resume();',
);
const manager = createRizinTestManager(
{
REA_RIZIN_COMMAND: provider,
},
{
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
resolveSpawned();
return launched;
},
},
);
track(manager);
const abort = new AbortController();
const starting = manager.start(
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
await spawned;
abort.abort();
expect((await starting).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"preserves startup cleanup uncertainty after cancellation",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const provider = await makeProvider(
"process.stdin.resume(); setInterval(() => {}, 1000);",
);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{
stopProcess: incompleteStop,
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
resolveSpawned();
return launched;
},
},
);
track(manager);
const abort = new AbortController();
const starting = manager.start(
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
await spawned;
abort.abort();
const result = await starting;
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"rejects commands for missing and pre-cancelled sessions",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
expect((await manager.execute("missing", "dr")).ok).toBe(false);
const aborted = new AbortController();
aborted.abort();
expect((await manager.execute(sessionId, "dr", aborted.signal)).ok).toBe(
false,
);
expect(manager.status(sessionId)?.state).toBe("ready");
expect((await manager.close("missing")).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"retains close failures and resolves their owner after cleanup retry",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
let stopCalls = 0;
const { manager, sessionId } = await start(provider, {
stopProcess: async (session, name, options) => {
stopCalls += 1;
if (stopCalls === 1) {
session.launched.process.kill("SIGTERM");
return {
status: "incomplete",
reason: "first stop result is uncertain",
};
}
await session.supervisor.waitForExit(1000);
return stopFakeNoInferior(session, name, options);
},
});
const closed = await manager.close(sessionId);
expect(closed.ok).toBe(false);
if (!closed.ok) {
expect(closed.error.cleanupIncomplete).toBe(true);
expect(closed.error.cleanup?.resources).toEqual([sessionId]);
const retainedFailure = closed.error;
expect(await manager.retryCleanupFailures()).toEqual({
ok: true,
value: null,
});
expect(retainedFailure.cleanupIncomplete).toBe(false);
}
expect(stopCalls).toBe(2);
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"retains a Rizin close owner until inherited output writers close",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const sessionId = started.value.session_id;
injected.control.exitLeader();
const firstClose = await manager.close(sessionId);
expect(firstClose.ok).toBe(false);
if (!firstClose.ok) {
expect(firstClose.error.cleanupIncomplete).toBe(true);
expect(firstClose.error.message).toMatch(/inherited output streams/i);
}
expect(manager.status(sessionId)).toBeDefined();
injected.control.closeOutput();
const retried = await manager.retryCleanupFailures();
expect(retried).toEqual({ ok: true, value: null });
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"closes a session after unsolicited frames make command correlation unsafe",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); setTimeout(() => process.stdout.write("unexpected\\0"), 20); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
await new Promise((resolve) => setTimeout(resolve, 50));
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
expect((await manager.close(sessionId)).ok).toBe(true);
},
);
@@ -0,0 +1,210 @@
import { afterEach, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
abortOnCheck,
createInjectedProcess,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start, startInjected, track } =
createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"stops the session when the provider closes its stdin pipe",
async () => {
const provider = await makeProvider(
'printf "\\000"; exec 0<&-; while :; do :; done',
"#!/bin/sh",
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 500,
});
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
},
);
it
.skipIf(process.platform === "win32")
.each([
"null",
"destroyed",
"throws",
"throws-opaque",
"write-error",
] as const)(
"fails safely when injected Rizin stdin is %s",
async (stdinMode) => {
const injected = createInjectedProcess({ stdin: stdinMode });
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"fails an active command when the injected stdin stream closes",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
injected.control.closeStdin();
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"uses protocol cleanup when an injected write callback fails (incomplete=%s)",
async (incomplete) => {
const injected = createInjectedProcess({ stdin: "write-error" });
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: incomplete
? incompleteStop
: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
if (!result.ok && incomplete)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"maps injected spawn errors and startup protocol failure",
async () => {
for (const spawnError of [new Error("injected spawn failure"), "opaque"]) {
const injected = createInjectedProcess({ spawnError });
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
}
const injected = createInjectedProcess({
startup: (control) => control.closeStdin(),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("stdin stream closed");
},
);
it.skipIf(process.platform === "win32")(
"maps spawn rejection as cancellation when the signal changes during spawn",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
beforeSpawnReturns: () => abort.abort(),
spawnError: new Error("spawn interrupted"),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.message).toContain("cancelled");
},
);
it.skipIf(process.platform === "win32")(
"cancels startup after receiving its initial frame",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
startup: (control) => {
control.output(Buffer.from([0]));
abort.abort();
},
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"observes startup cancellation before the first frame waiter is installed",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
beforeSpawnReturns: () => abort.abort(),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after its turn is granted",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"dr",
abortOnCheck(3),
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels while waiting for the previous command turn",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"dr",
abortOnCheck(2),
);
expect(result.ok).toBe(false);
},
);
@@ -0,0 +1,291 @@
import { afterEach, expect, it, vi } from "vitest";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
abortOnCheck,
createInjectedProcess,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, startInjected, track } = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"times out when an active command produces no frame",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 10,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.parameters.launch_provenance).toEqual({
caller_selected_path: "/tmp/injected",
resolved_path: "/tmp/injected",
});
expect(result.value.evidence.limitations).toEqual([
"The current debugger target identity is not established by the Rizin session identifier.",
"The command timed out before its completion marker; retained output is partial and completion is unknown.",
"The owned debugger session was stopped because output correlation could no longer be guaranteed.",
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
]);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves frame separators in partial output when a command times out",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("first frame\0second frame\0");
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"preserves queued partial frames when the command deadline reaches zero",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("first frame\0second frame\0third frame\0");
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const clock = vi.spyOn(Date, "now");
clock
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValue(1100);
let result;
try {
result = await manager.execute(started.value.session_id, "wait");
} finally {
clock.mockRestore();
}
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"does not convert an unexpected frame waiter error into a timeout",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
setImmediate(() => control.stdinError());
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 100,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("Rizin stdin stream failed");
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after capturing its completion frame",
async () => {
let signal: AbortSignal;
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined) control.output(Buffer.from(`${marker}\0`));
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
signal = abortOnCheck(5);
const result = await manager.execute(
started.value.session_id,
"dr",
signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"handles cancellation observed immediately after installing the frame waiter",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"wait",
abortOnCheck(5),
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"maps a frame-wait listener installation failure without losing cleanup (incomplete=%s)",
async (incomplete) => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () =>
incomplete
? { status: "incomplete", reason: "injected stop uncertainty" }
: { status: "stopped" },
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const controller = new AbortController();
let registrations = 0;
const signal = {
get aborted() {
return false;
},
addEventListener(
type: Parameters<AbortSignal["addEventListener"]>[0],
listener: Parameters<AbortSignal["addEventListener"]>[1],
options?: Parameters<AbortSignal["addEventListener"]>[2],
) {
registrations += 1;
if (registrations === 2)
throw new Error("injected frame waiter registration failure");
controller.signal.addEventListener(type, listener, options);
},
removeEventListener: controller.signal.removeEventListener.bind(
controller.signal,
),
dispatchEvent: controller.signal.dispatchEvent.bind(controller.signal),
onabort: null,
reason: undefined,
throwIfAborted: () => undefined,
} as AbortSignal;
const result = await manager.execute(
started.value.session_id,
"wait",
signal,
);
expect(result.ok).toBe(false);
if (!result.ok && incomplete)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"correlates an injected command frame with its generated marker",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => control.output(Buffer.from(`output${marker}\0`)));
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.output).toBe("output");
},
);
it.skipIf(process.platform === "win32")(
"preserves process-exit evidence when exit occurs before frame waiting",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => control.exit(),
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.result).toMatchObject({
command: "dr",
output: "",
output_truncated: false,
completion_status: "unknown",
backend: null,
});
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.limitations).toEqual([
"The current debugger target identity is not established by the Rizin session identifier.",
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
]);
}
},
);
it.skipIf(process.platform === "win32")(
"rejects a queued command when the process exits before its frame wait begins",
async () => {
const writes: string[] = [];
const injected = createInjectedProcess({
onWrite: (text, control) => {
writes.push(text);
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined) setImmediate(() => control.exit());
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const first = manager.execute(started.value.session_id, "first");
const queued = manager.execute(started.value.session_id, "second");
expect((await first).ok).toBe(true);
const second = await queued;
expect(second.ok).toBe(false);
if (!second.ok) expect(second.error).toBeInstanceOf(AnalysisInputError);
expect(writes.some((text) => text.includes("second\n"))).toBe(false);
},
);
@@ -0,0 +1,266 @@
import { afterEach, expect, it } from "vitest";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
createInjectedProcess,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start, startInjected, track } =
createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"assembles a multi-chunk NUL frame once and preserves its command output",
async () => {
const chunk = Buffer.alloc(64 * 1024, 0x61);
const chunkCount = 32;
const outputBytes = chunk.length * chunkCount;
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => {
for (let index = 0; index < chunkCount; index += 1)
control.output(chunk);
control.output(Buffer.from([0]));
control.output(Buffer.from(`${marker}\0`));
});
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "chunked");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output)).toBe(outputBytes);
expect(result.value.result.output).toBe("a".repeat(outputBytes));
expect(result.value.result.completion_status).toBe("complete");
}
},
);
it.skipIf(process.platform === "win32")(
"discards an oversized frame split across deterministic stream chunks",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => {
control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
control.output(Buffer.from("discard tail"));
control.output(Buffer.from([0]));
control.output(Buffer.from(`${marker}\0`));
});
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "large");
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.output_truncated).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"closes an injected session on an oversized unsolicited frame",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
injected.control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves unsolicited history and marks oversized recent frames",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume(); setTimeout(() => process.stdout.write("x".repeat(17000) + "\\0"), 20);',
);
const { manager, sessionId } = await start(provider);
await new Promise((resolve) => setTimeout(resolve, 100));
const status = manager.status(sessionId);
expect(status?.recent_output_truncated).toBe(true);
expect(status?.recent_output.at(-1)).toContain("[recent frame truncated]");
},
);
it.skipIf(process.platform === "win32")(
"bounds recent history after many unsolicited frames",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0" + Array.from({ length: 70 }, (_, i) => "frame" + i + "\\0").join("")); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
const status = manager.status(sessionId);
expect(status?.recent_output).toHaveLength(64);
expect(status?.recent_output_truncated).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"returns partial unknown evidence when the process exits mid-command",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", () => { process.stdout.write("partial\\0"); process.exit(0); });',
);
const { manager, sessionId } = await start(provider);
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output: "partial",
completion_status: "unknown",
});
expect(result.value.evidence.limitations.join(" ")).toContain(
"Rizin exited before",
);
}
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after sending it and stops its owned session",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
const abort = new AbortController();
const execution = manager.execute(sessionId, "slow", abort.signal);
setTimeout(() => abort.abort(), 30);
expect((await execution).ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves partial timeout evidence when cleanup cannot be confirmed",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", (chunk) => { if (chunk.includes("slow")) process.stdout.write("partial\\0"); });',
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 25,
stopProcess: incompleteStop,
});
const result = await manager.execute(sessionId, "slow");
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(result.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
completion_status: "unknown",
});
expect(evidence.limitations.join(" ")).toContain(
"injected stop uncertainty",
);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves truncated output when cleanup cannot be confirmed",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 1000,
stopProcess: incompleteStop,
});
const result = await manager.execute(sessionId, "many");
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(result.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
completion_status: "unknown",
});
expect(evidence.limitations.join(" ")).toContain(
"injected stop uncertainty",
);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves the cleanup uncertainty when cancellation cannot confirm process stop",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider, {
stopProcess: incompleteStop,
});
const abort = new AbortController();
const execution = manager.execute(sessionId, "slow", abort.signal);
setTimeout(() => abort.abort(), 30);
const result = await execution;
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"cancels a queued command without sending it after the prior command completes",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "first") setTimeout(() => {}, 100);
else if (line.startsWith("!echo ")) setTimeout(() => process.stdout.write(line.slice(6) + "\\0"), 100);
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 300,
});
const first = manager.execute(sessionId, "first");
const abort = new AbortController();
const queued = manager.execute(sessionId, "second", abort.signal);
setTimeout(() => abort.abort(), 20);
expect((await queued).ok).toBe(false);
expect((await first).ok).toBe(true);
},
);
@@ -0,0 +1,198 @@
import { afterEach, expect, it } from "vitest";
import { createRizinCoverageHarness } from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start } = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"keeps command output bounded when many frames arrive for a command",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 1000,
});
const result = await manager.execute(sessionId, "many");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
},
);
it.skipIf(process.platform === "win32")(
"returns partial evidence when the command frame deadline is already expired",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 0,
});
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output: "",
output_truncated: true,
completion_status: "unknown",
});
},
);
it.skipIf(process.platform === "win32")(
"does not exceed the exact command byte cap when marker output follows a full frame",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "full") process.stdout.write(Buffer.alloc(16 * 1024 * 1024, 0x61).toString() + "\\0");
else if (line.startsWith("!echo ")) process.stdout.write("x" + line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 3000,
});
const result = await manager.execute(sessionId, "full");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
16 * 1024 * 1024,
);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
}
},
);
it.skipIf(process.platform === "win32")(
"caps aggregate output across multiple valid NUL frames",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
let aggregatePending = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "aggregate") {
process.stdout.write("a".repeat(10 * 1024 * 1024) + "\\0");
aggregatePending = true;
} else if (line.startsWith("!echo ")) {
process.stdout.write((aggregatePending ? "b".repeat(7 * 1024 * 1024) : "") + line.slice(6) + "\\0");
aggregatePending = false;
}
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 3000,
});
const result = await manager.execute(sessionId, "aggregate");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
16 * 1024 * 1024,
);
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"truncates an oversized NUL frame without decoding a split UTF-8 character",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "large") {
process.stdout.write("prefix\\0");
process.stdout.write(Buffer.alloc(16 * 1024 * 1024 + 1, 0xF0));
} else if (line.startsWith("!echo ")) process.stdout.write("\\0" + line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 2000,
});
const result = await manager.execute(sessionId, "large");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
expect(result.value.result.output.startsWith("prefix\n")).toBe(true);
}
},
);
it.skipIf(process.platform === "win32")(
"truncates an oversized frame when its NUL boundary arrives with the crossing chunk",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "large") {
const frame = Buffer.alloc(16 * 1024 * 1024 + 2, 0x61);
frame[frame.length - 1] = 0;
process.stdout.write(frame);
} else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 2000,
});
const result = await manager.execute(sessionId, "large");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
},
);
@@ -0,0 +1,196 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
describe.skipIf(process.platform === "win32")(
"persistent Rizin debugger session manager",
() => {
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("uses an absolute target path and waits for Rizin's completion marker", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-manager-"));
const provider = join(directory, "fake-rizin.mjs");
const argsFile = join(directory, "args.json");
await writeFile(
provider,
`#!/usr/bin/env node
const fs = await import("node:fs");
fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write("backend-event\\0rax=0x1234\\0");
else if (line === "olj") process.stdout.write("[]\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "-target.bin",
inferior_tty: await rizinTestInferiorTty(),
backend: "test-backend",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const providerArgs = await import("node:fs/promises").then(
({ readFile }) => readFile(argsFile, "utf8"),
);
expect(JSON.parse(providerArgs)).toEqual([
"-N",
"-0",
"-d",
"-R",
`stdout=${await rizinTestInferiorTty()}`,
"-R",
`stderr=${await rizinTestInferiorTty()}`,
"-e",
"dbg.exitkills=false",
"-D",
"test-backend",
resolve("-target.bin"),
]);
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("backend-event\nrax=0x1234");
expect(result.value.result.output_scope).toBe(
"command_and_interleaved_session_output",
);
expect(result.value.result.backend).toBe("test-backend");
}
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(manager.status(started.value.session_id)).toBeUndefined();
});
it("stops and invalidates a Rizin session after its completion-marker timeout", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-"));
const provider = join(directory, "fake-rizin-stall.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write("rax=0x1234\\0");
else if (line === "slow") {
stalled = true;
process.stdout.write("partial-timeout\\0");
}
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 50 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const timedOut = await manager.execute(started.value.session_id, "slow");
expect(timedOut.ok).toBe(true);
if (timedOut.ok) {
expect(timedOut.value.result).toMatchObject({
output: "partial-timeout",
output_truncated: true,
completion_status: "unknown",
});
expect(timedOut.value.evidence.limitations.join(" ")).toContain(
"timed out",
);
}
expect(manager.status(started.value.session_id)?.state).toBe("closed");
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
false,
);
expect((await manager.close(started.value.session_id)).ok).toBe(true);
});
},
);
it.skipIf(process.platform === "win32")(
"stops Rizin when empty unsolicited NUL frames exhaust the bounded queue",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-empty-frames-"));
const provider = join(directory, "fake-rizin-empty.mjs");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
try {
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
setTimeout(() => process.stdout.write("\\0".repeat(5000)), 10);
process.stdin.resume();
`,
);
await chmod(provider, 0o700);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
expect(manager.status(started.value.session_id)?.state).toBe("closed");
expect((await manager.close(started.value.session_id)).ok).toBe(true);
} finally {
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
@@ -0,0 +1,894 @@
import { spawn, type ChildProcess } from "node:child_process";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
spawnOwnedProviderProcess,
type ProviderProcessHandle,
} from "../../../src/process/ProviderProcess.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
const inferiorProcesses: ChildProcess[] = [];
const startRizinWithProvider = async (
provider: string,
): Promise<{
manager: RizinDebugSessionManager;
sessionId: string | undefined;
}> => {
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
return {
manager,
sessionId: started.ok ? started.value.session_id : undefined,
};
};
const startRizinWithOwnedStop = async (provider: string) => {
let debuggerProcess: ProviderProcessHandle | undefined;
const manager = new RizinDebugSessionManager(
{ ...process.env, REA_RIZIN_COMMAND: provider },
{
platform: "linux",
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
debuggerProcess = launched.process;
return launched;
},
},
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
if (!started.ok) throw started.error;
return {
manager,
sessionId: started.value.session_id,
exitDebugger: async () => {
if (debuggerProcess === undefined)
throw new Error("Provider did not spawn");
const exited = new Promise<void>((resolve) =>
debuggerProcess?.once("exit", () => resolve()),
);
debuggerProcess.kill("SIGTERM");
await exited;
},
};
};
const expectOwnedProcessExited = async (pidText: string): Promise<void> => {
const pid = Number(pidText);
expect(Number.isInteger(pid)).toBe(true);
expect(() => process.kill(pid, 0)).toThrow();
};
afterEach(async () => {
for (const inferior of inferiorProcesses.splice(0)) {
if (inferior.exitCode !== null || inferior.signalCode !== null) continue;
const exited = new Promise<void>((resolveExit) =>
inferior.once("exit", () => resolveExit()),
);
inferior.kill("SIGTERM");
await exited;
}
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
const spawnTestInferior = async (): Promise<ChildProcess> => {
const inferior = spawn(
process.execPath,
["-e", "setInterval(() => {}, 1000)"],
{
stdio: "ignore",
},
);
inferiorProcesses.push(inferior);
await new Promise<void>((resolveSpawn, rejectSpawn) => {
inferior.once("spawn", resolveSpawn);
inferior.once("error", rejectSpawn);
});
return inferior;
};
const createInferiorInventoryProvider = async (
rows: readonly { readonly fd: number; readonly pid: number }[],
): Promise<string> => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-owned-inferior-"));
const provider = join(directory, "fake-rizin-owned-inferior.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "olj") process.stdout.write(JSON.stringify(${JSON.stringify(rows.map(({ fd, pid }) => ({ fd, raised: true, uri: `ptrace://${pid}` })))} ) + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write("true\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
else process.stdout.write("\\0");
}
});
`,
);
await chmod(provider, 0o700);
return provider;
};
it("keeps persistent Rizin sessions unavailable on Windows", async () => {
const rizin = await createRizinTestManager(
{ REA_RIZIN_COMMAND: "/missing/rizin" },
{ platform: "win32" },
).start({
path: "/tmp/fixture.bin",
inferior_tty: "unused-before-platform-admission",
});
expect(rizin.ok).toBe(false);
if (!rizin.ok) {
expect(rizin.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(rizin.error.message).toContain("Linux /proc descriptor readback");
}
});
it.skipIf(process.platform === "win32")(
"rejects startup when Rizin exits immediately after its initial frame",
async () => {
const injected = createInjectedProcess({
startup: (control) => {
control.output(Buffer.from("startup diagnostic\0partial trailing"));
control.exit();
},
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(false);
if (!started.ok) {
expect(started.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(started.error.message).toContain("exited");
expect(started.error.message).not.toContain("timed out");
expect(started.error.capturedOutput).toMatchObject({
stdout: "startup diagnostic\npartial trailing",
stderr: "",
truncated: false,
});
}
},
);
it.skipIf(process.platform === "win32")(
"preserves partial Rizin stdout when startup times out before its first frame",
async () => {
const injected = createInjectedProcess({
startup: (control) => control.output("partial startup diagnostic"),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess, startupTimeoutMs: 25 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(false);
if (!started.ok) {
expect(started.error._tag).toBe("AnalysisTimeoutError");
expect(started.error.capturedOutput).toMatchObject({
stdout: expect.stringContaining("partial startup diagnostic"),
stderr: "",
truncated: false,
});
}
},
);
it.skipIf(process.platform === "win32")(
"keeps session UTF-8 status cumulative while command evidence reports only its frames",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-utf8-scope-"));
const provider = join(directory, "fake-rizin-command-utf8-scope.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write(Buffer.from([0xff, 0]));
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "invalid-output") process.stdout.write(Buffer.from([0xfe, 0]));
else if (!line.startsWith("!echo ")) process.stdout.write("valid output\\0");
else process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
const firstValid = await manager.execute(sessionId, "valid-before-invalid");
expect(firstValid.ok).toBe(true);
if (firstValid.ok) {
expect(firstValid.value.result).not.toHaveProperty("output_invalid_utf8");
expect(firstValid.value.evidence.raw_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(firstValid.value.evidence.normalized_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(firstValid.value.evidence.limitations.join(" ")).not.toContain(
"Collected command frames contained invalid UTF-8 bytes",
);
}
const invalid = await manager.execute(sessionId, "invalid-output");
expect(invalid.ok).toBe(true);
if (invalid.ok) {
expect(invalid.value.result.output_invalid_utf8).toBe(true);
expect(invalid.value.evidence.raw_result).toMatchObject({
output_invalid_utf8: true,
});
expect(invalid.value.evidence.normalized_result).toMatchObject({
output_invalid_utf8: true,
});
expect(invalid.value.evidence.limitations.join(" ")).toContain(
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
);
}
const laterValid = await manager.execute(sessionId, "valid-after-invalid");
expect(laterValid.ok).toBe(true);
if (laterValid.ok) {
expect(laterValid.value.result).not.toHaveProperty("output_invalid_utf8");
expect(laterValid.value.evidence.raw_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(laterValid.value.evidence.normalized_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(laterValid.value.evidence.limitations.join(" ")).not.toContain(
"Collected command frames contained invalid UTF-8 bytes",
);
}
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
},
);
it.skipIf(process.platform !== "linux")(
"clears retained Rizin cleanup after its identified inferior exits",
async () => {
const inferior = await spawnTestInferior();
const pid = inferior.pid;
expect(pid).toBeDefined();
if (pid === undefined) return;
const provider = await createInferiorInventoryProvider([{ fd: 12, pid }]);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
const firstClose = await manager.close(sessionId);
expect(firstClose.ok, JSON.stringify(firstClose)).toBe(false);
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(true);
await exitDebugger();
expect((await manager.retryCleanupFailures()).ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
const inferiorExited = new Promise<void>((resolveExit) =>
inferior.once("exit", () => resolveExit()),
);
inferior.kill("SIGTERM");
await inferiorExited;
const retried = await manager.retryCleanupFailures();
expect(retried).toEqual({ ok: true, value: null });
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(false);
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform !== "linux")(
"keeps Rizin cleanup unknown when an inferior inventory is only partially captured",
async () => {
const inferior = await spawnTestInferior();
const pid = inferior.pid;
expect(pid).toBeDefined();
if (pid === undefined) return;
const provider = await createInferiorInventoryProvider([
{ fd: 12, pid },
{ fd: 13, pid: 999_999_999 },
]);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
expect((await manager.close(sessionId)).ok).toBe(false);
await exitDebugger();
const closed = await manager.close(sessionId);
expect(closed.ok, JSON.stringify(closed)).toBe(false);
if (!closed.ok)
expect(closed.error.message).toContain("no owner proof confirms");
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"retains Rizin cleanup when target state is unknown at debugger exit",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-unknown-target-"));
const provider = join(directory, "fake-rizin-unknown-target.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "olj") process.stdout.write("not-json\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
expect((await manager.close(sessionId)).ok).toBe(false);
await exitDebugger();
const closed = await manager.close(sessionId);
expect(closed.ok, JSON.stringify(closed)).toBe(false);
if (!closed.ok)
expect(closed.error.message).toContain("no owner proof confirms");
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"preserves command parameters in Rizin observation evidence",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-evidence-"));
const provider = join(directory, "fake-rizin-command-evidence.mjs");
const inferiorTty = await rizinTestInferiorTty();
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (!line.startsWith("!echo ")) process.stdout.write("command output\\0");
else process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
managers.push(manager);
const callerSelectedPath = "./relative/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: inferiorTty,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const executed = await manager.execute(started.value.session_id, "dr");
expect(executed.ok).toBe(true);
if (executed.ok)
expect(executed.value.evidence.parameters).toEqual({
session_id: started.value.session_id,
command: "dr",
inferior_tty: inferiorTty,
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
});
if (executed.ok)
expect(executed.value.evidence.limitations).toContain(
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
);
},
);
it.skipIf(process.platform === "win32")(
"keeps queued Rizin commands serialized when a waiting request is cancelled",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-queue-cancel-"));
const provider = join(directory, "fake-rizin-queue-cancel.mjs");
const overlapPath = join(directory, "overlap");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let firstActive = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "first") firstActive = true;
if (line === "third" && firstActive) import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(overlapPath)}, "overlap"));
if (line.startsWith("!echo ")) {
const marker = line.slice(6);
if (firstActive) setTimeout(() => { firstActive = false; process.stdout.write(marker + "\\0"); }, 100);
else process.stdout.write(marker + "\\0");
}
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const first = manager.execute(sessionId, "first");
const controller = new AbortController();
const second = manager.execute(sessionId, "second", controller.signal);
await new Promise((resolveDelay) => setTimeout(resolveDelay, 20));
controller.abort();
const third = manager.execute(sessionId, "third");
expect((await second).ok).toBe(false);
expect((await first).ok).toBe(true);
expect((await third).ok).toBe(true);
await expect(readFile(overlapPath, "utf8")).rejects.toThrow();
},
);
it.skipIf(process.platform === "win32")(
"preserves a truncated single Rizin frame that exceeds the protocol limit",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-frame-overflow-"));
const provider = join(directory, "fake-rizin-frame-overflow.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let sent = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (!line.startsWith("!echo ") && !sent) {
sent = true;
process.stdout.write("z".repeat(16 * 1024 * 1024 + 32) + "\\0");
}
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const result = await manager.execute(sessionId, "px");
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
if (result.ok) {
expect(
Buffer.byteLength(result.value.result.output, "utf8"),
).toBeLessThanOrEqual(16 * 1024 * 1024);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
expect(result.value.evidence.parameters).toMatchObject({
session_id: sessionId,
command: "px",
inferior_tty: expect.any(String),
});
}
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"returns bounded partial Rizin output with unknown completion after overflow",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-output-overflow-"));
const provider = join(directory, "fake-rizin-output-overflow.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
else if (line === "olj") process.stdout.write(JSON.stringify([{ fd: 12, raised: true, uri: "ptrace://" + process.ppid }]) + "\\0");
else if (line === "px") process.stdout.write("x".repeat(10 * 1024 * 1024) + "\\0" + "y".repeat(10 * 1024 * 1024) + "\\0");
else process.stdout.write("\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const result = await manager.execute(sessionId, "px");
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
if (result.ok) {
expect(
Buffer.byteLength(result.value.result.output, "utf8"),
).toBeLessThanOrEqual(16 * 1024 * 1024);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
}
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"waits for the Rizin process to exit when command correlation times out",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-timeout-"));
const provider = join(directory, "fake-rizin-command-timeout.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(join(directory ?? "", "pid"))}, String(process.pid)));
process.stdout.write("\\0");
process.stdin.setEncoding("utf8");
process.stdin.on("data", () => process.stdout.write(Buffer.from([0xff, 0])));
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 40 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output: "�",
output_truncated: true,
completion_status: "unknown",
output_invalid_utf8: true,
});
expect(result.value.evidence.limitations).toContain(
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
);
}
await expectOwnedProcessExited(
await readFile(join(directory, "pid"), "utf8"),
);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"cancels a running Rizin command and retains its closed status",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-cancel-"));
const provider = join(directory, "fake-rizin-command-cancel.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "slow") {
stalled = true;
process.stdout.write(Buffer.from([0xff, 0]));
}
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 5_000 },
);
managers.push(manager);
const callerSelectedPath = "./cancelled/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const controller = new AbortController();
setTimeout(() => controller.abort(), 50);
const result = await manager.execute(
started.value.session_id,
"slow",
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
normalized_result: { output_invalid_utf8: true },
limitations: expect.arrayContaining([
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
]),
parameters: {
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
},
});
}
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"reports bounded Rizin stderr retention in session status",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-diagnostic-limit-"));
const provider = join(directory, "fake-rizin-diagnostic-limit.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stderr.write("x".repeat(100000));
process.stdout.write("\\0");
process.stdin.resume();
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
expect(
manager.status(started.value.session_id)?.diagnostics_truncated,
).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"returns cancellation when Rizin startup is cancelled after spawn",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-start-cancel-"));
const provider = join(directory, "fake-rizin-start-cancel.mjs");
await writeFile(
provider,
`#!/usr/bin/env node\nprocess.stdin.resume();\nsetInterval(() => {}, 1000);\n`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const controller = new AbortController();
setTimeout(() => controller.abort(), 50);
const started = await manager.start(
{ path: "/tmp/fixture.bin", inferior_tty: await rizinTestInferiorTty() },
controller.signal,
);
expect(started.ok).toBe(false);
if (!started.ok) expect(started.error._tag).toBe("AnalysisCancelledError");
},
);
it.skipIf(process.platform === "win32")(
"converts a Rizin stdin pipe failure into a provider session error",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-stdin-error-"));
const provider = join(directory, "fake-rizin-stdin-error.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
setTimeout(() => import("node:fs").then((fs) => fs.closeSync(0)), 40);
setInterval(() => {}, 1000);
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 80));
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves Rizin process-exit reason and partial command output",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-exit-"));
const provider = join(directory, "fake-rizin-command-exit.mjs");
const writerPidPath = join(directory, "writer.pid");
await writeFile(
provider,
`#!/usr/bin/env node
import { spawn } from "node:child_process";
import { writeFileSync } from "node:fs";
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "exit-now") {
const writer = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit" });
writeFileSync(${JSON.stringify(writerPidPath)}, String(writer.pid));
process.stdout.write(Buffer.concat([Buffer.from("partial-before-exit\\0second-partial\\0"), Buffer.from([0xff, 0])]), () => process.exit(7));
}
}
});
`,
);
await chmod(provider, 0o700);
let writerObserved = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{
stopProcess: async () => {
const writerPid = Number(await readFile(writerPidPath, "utf8"));
try {
process.kill(writerPid, 0);
writerObserved = true;
} catch {
writerObserved = false;
}
return {
status: "incomplete",
reason: "owned output writer is still active",
};
},
},
);
managers.push(manager);
const callerSelectedPath = "./exit/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const exited = await manager.execute(started.value.session_id, "exit-now");
expect(exited.ok).toBe(false);
expect(writerObserved).toBe(true);
if (!exited.ok) {
expect(exited.error.cleanup).toEqual({
reason: "owned output writer is still active",
resources: [started.value.session_id],
});
expect(exited.error.partialObservation).toMatchObject({
normalized_result: {
output: ["partial-before-exit", "second-partial", "�"].join("\n"),
completion_status: "unknown",
output_invalid_utf8: true,
},
parameters: {
command: "exit-now",
session_id: started.value.session_id,
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
},
});
const partialEvidence = evidenceSchema.parse(
exited.error.partialObservation,
);
expect(partialEvidence.limitations.join(" ")).toContain(
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
);
}
const writerPid = Number(await readFile(writerPidPath, "utf8"));
process.kill(writerPid, "SIGKILL");
},
);
@@ -0,0 +1,645 @@
import { execFileSync, spawn as spawnChild } from "node:child_process";
import {
chmod,
mkdtemp,
readFile,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "@lydell/node-pty";
import { afterEach, expect, it, vi } from "vitest";
import {
assertRizinProcessStartTimeStable,
parseRizinProcStartTime,
RizinDebugSessionManager,
} from "../../../src/rizin/RizinDebugSessionManager.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { TOOL_EFFECTS } from "../../../src/contracts/toolEffects.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
let terminal: ReturnType<typeof spawn> | undefined;
let manager: RizinDebugSessionManager | undefined;
let testDirectory: string | undefined;
let inferiorPid: number | undefined;
let providerPid: number | undefined;
let providerWatchdogPid: number | undefined;
const rizinBinary = findRizinBinary();
afterEach(async () => {
await manager?.closeAll().catch(() => undefined);
manager = undefined;
if (providerPid !== undefined && testDirectory !== undefined) {
try {
const commandLine = await readFile(
`/proc/${providerPid}/cmdline`,
"utf8",
);
if (commandLine.includes(testDirectory))
process.kill(providerPid, "SIGKILL");
} catch {
// The owned fake provider may already have exited.
}
}
providerPid = undefined;
if (providerWatchdogPid !== undefined) {
try {
process.kill(providerWatchdogPid, "SIGTERM");
} catch {
// The watchdog may already have completed.
}
}
providerWatchdogPid = undefined;
terminal?.kill();
terminal = undefined;
let ownedPid = inferiorPid;
if (ownedPid === undefined && testDirectory !== undefined) {
try {
ownedPid = Number(
await readFile(join(testDirectory, "target.pid"), "utf8"),
);
} catch {
// The target may not have started before the test failed.
}
}
if (
ownedPid !== undefined &&
Number.isSafeInteger(ownedPid) &&
ownedPid > 0
) {
try {
const commandLine = await readFile(`/proc/${ownedPid}/cmdline`, "utf8");
if (testDirectory !== undefined && commandLine.includes(testDirectory))
process.kill(ownedPid, "SIGKILL");
} catch {
// The test target may already have exited.
}
}
inferiorPid = undefined;
if (testDirectory !== undefined)
await rm(testDirectory, { recursive: true, force: true });
testDirectory = undefined;
});
it("requires an explicit inferior TTY before spawning Rizin", async () => {
let spawned = false;
const manager = new RizinDebugSessionManager(
{ REA_RIZIN_COMMAND: "rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn");
},
},
);
const result = await manager.start({ path: "/tmp/fixture.bin" } as never);
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
});
it.skipIf(process.platform === "win32")(
"fails the protocol when a NUL delimiter does not advance the frame parser",
async () => {
const injected = createInjectedProcess({
startup: (control) => control.output(Buffer.from([0, 0])),
});
manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const originalIndexOf = Buffer.prototype.indexOf;
let forcedNonAdvancingBoundary = false;
const indexOf = vi
.spyOn(Buffer.prototype, "indexOf")
.mockImplementation(function (this: Buffer, value, byteOffset, encoding) {
if (
this.length === 2 &&
this[0] === 0 &&
this[1] === 0 &&
byteOffset === 1
) {
forcedNonAdvancingBoundary = true;
return 0;
}
return originalIndexOf.call(this, value, byteOffset, encoding);
});
try {
const started = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(forcedNonAdvancingBoundary).toBe(true);
expect(started.ok).toBe(false);
if (!started.ok)
expect(started.error.message).toContain(
"frame parser failed to advance past a NUL delimiter",
);
} finally {
indexOf.mockRestore();
}
},
);
it("declares that Rizin close can resume target code and mutate target state", () => {
expect(TOOL_EFFECTS.close_rizin_debug_session).toMatchObject({
mutatesTarget: true,
executesForeignCode: true,
});
});
it.skipIf(process.platform !== "linux").each([
{ name: "empty inferior list", response: "[]", closeSucceeds: true },
{ name: "malformed JSON", response: "not-json", closeSucceeds: false },
{ name: "non-array JSON", response: "{}", closeSucceeds: false },
{
name: "valid non-ptrace descriptor",
response: '[{"raised":true,"fd":3,"uri":"file:///tmp/target"}]',
closeSucceeds: true,
},
{
name: "malformed descriptor row",
response: "[null]",
closeSucceeds: false,
},
{
name: "inactive ptrace row",
response: '[{"raised":false,"fd":3,"uri":"ptrace://1"}]',
closeSucceeds: false,
},
{
name: "malformed ptrace URI",
response: '[{"raised":true,"fd":3,"uri":"ptrace://bad"}]',
closeSucceeds: false,
},
{
name: "multiple ptrace rows",
response:
'[{"raised":true,"fd":3,"uri":"ptrace://1"},{"raised":true,"fd":4,"uri":"ptrace://2"}]',
closeSucceeds: false,
},
])(
"validates Rizin `olj` close response: $name",
async ({ response, closeSucceeds }) => {
const tty = await rizinTestInferiorTty();
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-olj-"));
const provider = join(testDirectory, "fake-rizin.cjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let oljCalls = 0;
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "olj") process.stdout.write((++oljCalls === 1 ? ${JSON.stringify(response)} : "[]") + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write("false\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
execFileSync(process.execPath, ["--check", provider]);
await chmod(provider, 0o700);
manager = new RizinDebugSessionManager({ REA_RIZIN_COMMAND: provider });
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: tty,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const closed = await manager.close(started.value.session_id);
expect(closed.ok).toBe(closeSucceeds);
if (!closeSucceeds) {
expect(manager.status(started.value.session_id)?.state).toBe("closed");
await manager.closeAll();
}
},
);
it.skipIf(process.platform !== "linux").each([
{
name: "same descriptor remains listed after detach",
afterDetach: (pid: number) =>
`[{"raised":true,"fd":3,"uri":"ptrace://${pid}"}]`,
},
{
name: "same inferior remains listed under a different FD",
afterDetach: (pid: number) =>
`[{"raised":true,"fd":4,"uri":"ptrace://${pid}"}]`,
},
{
name: "an unexpected ptrace inferior remains listed",
afterDetach: () => '[{"raised":true,"fd":4,"uri":"ptrace://999999999"}]',
},
])(
"retains ownership when o- readback finds $name",
async ({ afterDetach }) => {
const sessionId = await startFakeInferiorSession({ afterDetach });
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"detaches a verified fake inferior before stopping the Rizin debugger",
async () => {
const sessionId = await startFakeInferiorSession();
const closed = await manager!.close(sessionId);
expect(closed.ok).toBe(true);
if (!closed.ok) return;
expect(manager!.status(sessionId)).toBeUndefined();
expect(inferiorPid).toBeDefined();
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
const stat = await readFile(`/proc/${inferiorPid!}/stat`, "utf8");
const commandEnd = stat.lastIndexOf(") ");
expect(commandEnd).toBeGreaterThan(0);
expect(stat.slice(commandEnd + 2).trimStart()[0]).not.toBe("Z");
},
);
it.skipIf(process.platform !== "linux")(
"refuses detach when Rizin reports dbg.exitkills=true",
async () => {
const sessionId = await startFakeInferiorSession({ exitKills: "true" });
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"refuses detach when the inferior stderr is not routed to the selected TTY",
async () => {
const sessionId = await startFakeInferiorSession({
stderrPath: "/dev/null",
});
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"retains ownership when the ptrace PID has no proc identity",
async () => {
const sessionId = await startFakeInferiorSession({
launchTarget: false,
initialRows: '[{"raised":true,"fd":3,"uri":"ptrace://999999999"}]',
startupWatchdogMs: 2_000,
});
await expectCloseRejectedAndReleased(sessionId);
},
4_000,
);
it("parses Rizin's Linux proc stat start time and rejects malformed identity data", () => {
const fields = Array.from({ length: 20 }, (_, index) => String(index + 1));
expect(
parseRizinProcStartTime(`123 (target ) name) ${fields.join(" ")}`),
).toBe("20");
expect(() => parseRizinProcStartTime("malformed stat contents")).toThrow(
"Inferior process identity is malformed",
);
expect(() => parseRizinProcStartTime("123 (target) short")).toThrow(
"Inferior process start time could not be verified",
);
expect(() => assertRizinProcessStartTimeStable("11", "12")).toThrow(
"disappeared or was reused",
);
expect(() => assertRizinProcessStartTimeStable("11", "11")).not.toThrow();
});
it.skipIf(process.platform !== "linux")(
"retains ownership when cleanup cannot read Rizin stdin",
async () => {
const injected = createInjectedProcess({ stdin: "null" });
manager = new RizinDebugSessionManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: injected.spawnProcess,
stopProcess: async (session) => {
try {
await session.detachInferior?.();
} catch {
// This fixture verifies the manager's fail-closed read path only.
}
return { status: "incomplete", reason: "unreachable" };
},
},
);
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
expect((await manager.close(started.value.session_id)).ok).toBe(false);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform !== "linux")(
"retains ownership when an internal Rizin frame is truncated",
async () => {
const sessionId = await startFakeInferiorSession({
truncateCleanupFrame: true,
maxCommandOutputBytes: 1_024,
});
expect((await manager!.close(sessionId)).ok).toBe(false);
expect(manager!.status(sessionId)?.state).toBe("closed");
await expect(manager!.closeAll()).rejects.toThrow("did not stop cleanly");
},
);
it.skipIf(process.platform !== "linux")(
"retains a verified active inferior after public command output truncation makes protocol state ambiguous",
async () => {
const sessionId = await startFakeInferiorSession({
overflowPxCommand: true,
maxCommandOutputBytes: 1_024,
});
let watchdog: ReturnType<typeof setTimeout> | undefined;
const completed = await Promise.race([
manager!.execute(sessionId, "px"),
new Promise<never>((_, reject) => {
watchdog = setTimeout(
() => reject(new Error("detach watchdog expired")),
3_000,
);
}),
])
.catch(async (error: unknown) => {
if (providerPid !== undefined) {
try {
process.kill(providerPid, "SIGKILL");
} catch {
// The watchdog may race with provider exit.
}
}
// The mutated path can leave commandTail permanently held. Prevent cleanup
// from awaiting that same tail; afterEach still kills both child processes.
manager = undefined;
throw error;
})
.finally(() => {
if (watchdog !== undefined) clearTimeout(watchdog);
});
expect(completed.ok).toBe(false);
if (completed.ok) return;
expect(completed.error.cleanupIncomplete).toBe(true);
expect(completed.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(completed.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
output_truncated: true,
});
expect(evidence.limitations.join(" ")).toContain(
"The owned debugger session remains retained because cleanup could not be verified",
);
expect(manager!.status(sessionId)?.state).toBe("closed");
},
);
it.skipIf(
process.platform !== "linux" ||
rizinBinary === undefined ||
!rizinAvailable(rizinBinary),
)(
"routes the inferior to the selected TTY and verifies detach with Rizin 0.7.4 protocol",
async () => {
let terminalOutput = "";
terminal = spawn("sh", ["-c", "tty; exec sleep 60"], {
name: "xterm",
cols: 80,
rows: 24,
encoding: "utf8",
});
const ttyPath = await new Promise<string>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error("TTY path not printed")),
2_000,
);
terminal!.onData((data) => {
terminalOutput += data;
const match = /\/dev\/pts\/\d+/u.exec(terminalOutput);
if (match) {
clearTimeout(timer);
resolve(match[0]);
}
});
});
const tty = await realpath(ttyPath);
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-tty-"));
const wrapper = join(testDirectory, "rizin-with-long-lived-inferior.sh");
const pidPath = join(testDirectory, "target.pid");
const releasePath = join(testDirectory, "emit-output");
const target = join(testDirectory, "target.py");
await writeFile(
target,
`import os, sys, time\nopen(${JSON.stringify(pidPath)}, "w").write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(releasePath)}): time.sleep(0.02)\nprint("REA_RIZIN_STDOUT_MARKER", flush=True)\nprint("REA_RIZIN_STDERR_MARKER", file=sys.stderr, flush=True)\ntime.sleep(60)\n`,
);
await writeFile(
wrapper,
`#!/bin/sh\nexec ${shellQuote(rizinBinary!)} -R arg1=${target} "$@"\n`,
);
await chmod(wrapper, 0o700);
manager = new RizinDebugSessionManager({ REA_RIZIN_COMMAND: wrapper });
const started = await manager.start({
path: "/usr/bin/python3",
inferior_tty: tty,
});
expect(started.ok, started.ok ? "" : started.error.message).toBe(true);
if (!started.ok) return;
const closing = manager.close(started.value.session_id);
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
false,
);
const closed = await closing;
expect(closed.ok, closed.ok ? "" : closed.error.message).toBe(true);
const deadline = Date.now() + 5_000;
let pidText = "";
while (Date.now() < deadline) {
try {
pidText = await readFile(pidPath, "utf8");
break;
} catch {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
}
}
inferiorPid = Number(pidText);
expect(Number.isSafeInteger(inferiorPid) && inferiorPid > 0).toBe(true);
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
await writeFile(releasePath, "release after close");
const outputDeadline = Date.now() + 3_000;
while (
Date.now() < outputDeadline &&
(!terminalOutput.includes("REA_RIZIN_STDOUT_MARKER") ||
!terminalOutput.includes("REA_RIZIN_STDERR_MARKER"))
)
await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
expect(terminalOutput).toContain("REA_RIZIN_STDOUT_MARKER");
expect(terminalOutput).toContain("REA_RIZIN_STDERR_MARKER");
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
},
);
function findRizinBinary(): string | undefined {
try {
return execFileSync("which", ["rizin"], { encoding: "utf8" }).trim();
} catch {
return undefined;
}
}
function rizinAvailable(binary: string): boolean {
try {
return execFileSync(binary, ["-v"], { encoding: "utf8" }).includes("0.7.4");
} catch {
return false;
}
}
function shellQuote(value: string): string {
return `'${value.replaceAll("'", `'\\''`)}'`;
}
async function startFakeInferiorSession(
options: {
readonly launchTarget?: boolean;
readonly initialRows?: string;
readonly afterDetach?: (pid: number) => string;
readonly exitKills?: string;
readonly stderrPath?: string;
readonly truncateOlj?: boolean;
readonly truncateCleanupFrame?: boolean;
readonly overflowPxCommand?: boolean;
readonly startupWatchdogMs?: number;
readonly maxCommandOutputBytes?: number;
} = {},
): Promise<string> {
const tty = await realpath(await rizinTestInferiorTty());
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-protocol-"));
const targetPath = join(testDirectory, "inferior.mjs");
const pidPath = join(testDirectory, "target.pid");
const provider = join(testDirectory, "fake-rizin.cjs");
const launchTarget = options.launchTarget ?? true;
await writeFile(targetPath, "setInterval(() => {}, 1000);\n");
const initialRows = options.initialRows ?? null;
const afterDetach = options.afterDetach ?? (() => "[]");
const stderrPath = options.stderrPath ?? tty;
await writeFile(
provider,
`#!/usr/bin/env node
const fs = require("node:fs");
const { spawn } = require("node:child_process");
process.stdout.write("\\0");
${launchTarget ? `const ttyFlags = fs.constants.O_WRONLY | fs.constants.O_NOCTTY | fs.constants.O_NONBLOCK; const stdoutFd = fs.openSync(${JSON.stringify(tty)}, ttyFlags); const stderrFd = fs.openSync(${JSON.stringify(stderrPath)}, ttyFlags); const target = spawn(process.execPath, [${JSON.stringify(targetPath)}], { detached: true, stdio: ["ignore", stdoutFd, stderrFd] }); fs.closeSync(stdoutFd); fs.closeSync(stderrFd); target.unref(); const inferiorPid = target.pid; fs.writeFileSync(${JSON.stringify(pidPath)}, String(inferiorPid));` : "const inferiorPid = 999999999;"}
const initialRows = ${JSON.stringify(initialRows)} ?? JSON.stringify([{ raised: true, fd: 3, uri: "ptrace://" + inferiorPid }]);
const afterDetach = ${JSON.stringify(afterDetach(inferiorPid ?? 999999999))};
const exitKills = ${JSON.stringify(options.exitKills ?? "false")};
const truncateOlj = ${JSON.stringify(options.truncateOlj ?? false)};
const truncateCleanupFrame = ${JSON.stringify(options.truncateCleanupFrame ?? false)};
const overflowPxCommand = ${JSON.stringify(options.overflowPxCommand ?? false)};
let oljCalls = 0;
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "olj") {
oljCalls += 1;
if (truncateOlj && oljCalls === 1) process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0");
else process.stdout.write((oljCalls === 1 ? initialRows : oljCalls === 2 ? afterDetach : "[]") + "\\0");
}
else if (overflowPxCommand && line === "px") process.stdout.write("x".repeat(2_048) + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write(exitKills + "\\0");
else if (line.startsWith("!echo ")) process.stdout.write((truncateCleanupFrame ? "x".repeat(2_048) : "") + line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
let providerStderr = "";
manager = new RizinDebugSessionManager(
{ REA_RIZIN_COMMAND: provider },
{
spawnProcess: async (spawnOptions) => {
const launched = await spawnOwnedProviderProcess(spawnOptions);
providerPid = launched.process.pid;
if (options.startupWatchdogMs !== undefined) {
const watchdog = spawnChild(
process.execPath,
[
"-e",
`const fs = require("node:fs"); const provider = Number(process.argv[1]); const directory = process.argv[2]; const targetFile = process.argv[3]; const delay = Number(process.argv[4]); setTimeout(() => { let target; try { target = Number(fs.readFileSync(targetFile, "utf8")); } catch {} for (const pid of [provider, target]) { if (!Number.isSafeInteger(pid) || pid <= 0) continue; try { const commandLine = fs.readFileSync("/proc/" + pid + "/cmdline", "utf8"); if (commandLine.includes(directory)) process.kill(pid, "SIGKILL"); } catch {} } }, delay);`,
String(launched.process.pid),
testDirectory!,
join(testDirectory!, "target.pid"),
String(options.startupWatchdogMs),
],
{ detached: true, stdio: "ignore" },
);
providerWatchdogPid = watchdog.pid;
watchdog.unref();
}
launched.process.stderr?.on("data", (chunk) => {
providerStderr += Buffer.from(chunk).toString("utf8");
});
return launched;
},
...(options.maxCommandOutputBytes === undefined
? {}
: { maxCommandOutputBytes: options.maxCommandOutputBytes }),
},
);
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: tty,
});
expect(
started.ok,
started.ok ? "" : `${started.error.message} ${providerStderr}`,
).toBe(true);
if (!started.ok) throw started.error;
if (launchTarget) {
let pidText: string | undefined;
const deadline = Date.now() + 2_000;
while (pidText === undefined && Date.now() < deadline) {
try {
pidText = await readFile(pidPath, "utf8");
} catch {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
}
}
const parsedInferiorPid =
pidText === undefined ? Number.NaN : Number(pidText);
if (!Number.isSafeInteger(parsedInferiorPid) || parsedInferiorPid <= 0)
throw new Error("The test inferior did not publish a valid PID.");
inferiorPid = parsedInferiorPid;
}
return started.value.session_id;
}
async function expectCloseRejectedAndReleased(
sessionId: string,
): Promise<void> {
expect((await manager!.close(sessionId)).ok).toBe(false);
expect(manager!.status(sessionId)?.state).toBe("closed");
await manager!.closeAll();
expect(manager!.status(sessionId)).toBeUndefined();
}
@@ -0,0 +1,73 @@
import { afterAll } from "vitest";
import { spawn } from "@lydell/node-pty";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
let ttyPathPromise: Promise<string> | undefined;
let terminal: ReturnType<typeof spawn> | undefined;
export const rizinTestInferiorTty = (): Promise<string> => {
if (process.platform === "win32")
return Promise.reject(
new Error("The Rizin test TTY requires a POSIX host."),
);
ttyPathPromise ??= new Promise<string>((resolve, reject) => {
terminal = spawn("sh", ["-c", "tty; exec sleep 600"], {
name: "xterm",
cols: 80,
rows: 24,
encoding: "utf8",
});
let output = "";
const timer = setTimeout(
() => reject(new Error("test TTY path timeout")),
2_000,
);
terminal.onData((chunk) => {
output += chunk;
const pattern =
process.platform === "darwin"
? /\/dev\/ttys[0-9a-z]+/u
: /\/dev\/pts\/\d+/u;
const match = pattern.exec(output);
if (match !== null) {
clearTimeout(timer);
resolve(match[0]);
}
});
});
return ttyPathPromise;
};
afterAll(() => terminal?.kill());
/** These fixture processes do not launch or attach an inferior. */
export const stopFakeNoInferior = async (
session: Parameters<typeof stopOwnedDebuggerProcess>[0],
debuggerName: string,
options?: Parameters<typeof stopOwnedDebuggerProcess>[2],
) =>
stopOwnedDebuggerProcess(
{
...session,
inferiorStateUnknown: () => false,
detachInferior: async () => ({ status: "no-inferior" }),
},
debuggerName,
options,
);
export const createRizinTestManager = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
): RizinDebugSessionManager =>
new RizinDebugSessionManager(
{ ...process.env, ...environment },
{
// These fake-provider tests model Linux protocol behavior independently of
// the host running the suite. Real-provider coverage checks the host platform.
platform: "linux",
stopProcess: stopFakeNoInferior,
...options,
},
);
@@ -0,0 +1,45 @@
import { expect, it } from "vitest";
import { createRizinCommandTimeoutEvidence } from "../../../src/rizin/RizinDebugSessionManager.js";
it("preserves every field of partial Rizin timeout Evidence", () => {
const result = {
command: "dr",
output: "partial register output",
output_scope: "command_and_interleaved_session_output" as const,
output_truncated: true,
completion_status: "unknown" as const,
backend: null,
};
const evidence = createRizinCommandTimeoutEvidence({
sessionId: "session-123",
command: "dr",
result,
inferiorTty: "/dev/pts/7",
cleanupFailure: undefined,
launchProvenance: {
caller_selected_path: "./sample/../program",
resolved_path: "/workspace/program",
},
});
expect(evidence.parameters).toEqual({
session_id: "session-123",
command: "dr",
inferior_tty: "/dev/pts/7",
launch_provenance: {
caller_selected_path: "./sample/../program",
resolved_path: "/workspace/program",
},
});
expect(evidence.raw_result).toEqual(result);
expect(evidence.normalized_result).toEqual(result);
expect(evidence.limitations).toEqual([
"The current debugger target identity is not established by the Rizin session identifier.",
"The command timed out before its completion marker; retained output is partial and completion is unknown.",
"The owned debugger session was stopped because output correlation could no longer be guaranteed.",
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
]);
});
@@ -47,9 +47,12 @@ const fixture = async (duringCollection?: (root: string) => Promise<void>) => {
let reportedPath = "";
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
expect(args).toEqual(["version"]);
const stdout = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`;
return {
stdout: `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`,
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
};
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
@@ -0,0 +1,264 @@
import { execFileSync } from "node:child_process";
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { expect, it } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import {
createTestProcessRegistry,
waitForExit,
} from "../../../tests/support/process/processFixture.js";
const startPythonBridge = async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-cutter-receipt-"));
await chmod(directory, 0o700);
const processes = createTestProcessRegistry();
const child = processes.spawn(
"python3",
[resolve("tests/fixtures/cutter_bridge_protocol_test.py"), "--serve"],
{ env: { ...process.env, REA_CUTTER_BRIDGE_DIR: directory } },
);
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk: string) => {
stdout += chunk;
});
child.stderr.on("data", (chunk: string) => {
stderr += chunk;
});
try {
await new Promise<void>((resolveReady, rejectReady) => {
const timeout = setTimeout(
() =>
rejectReady(
new Error(`Python bridge did not become ready: ${stderr}`),
),
5_000,
);
const onData = (_chunk: string): void => {
if (!stdout.includes("ready\n")) return;
clearTimeout(timeout);
child.stdout.off("data", onData);
resolveReady();
};
child.stdout.on("data", onData);
child.once("error", (error) => {
clearTimeout(timeout);
rejectReady(error);
});
child.once("exit", (code, signal) => {
if (stdout.includes("ready\n")) return;
clearTimeout(timeout);
rejectReady(
new Error(
`Python bridge exited before ready (${code ?? signal}): ${stderr}`,
),
);
});
if (stdout.includes("ready\n")) onData("");
});
const client = new CutterBridgeClient({
...process.env,
REA_CUTTER_BRIDGE_DIR: directory,
});
const discovery = await client.listSessions();
const session = discovery.sessions[0];
if (session === undefined) throw new Error("Python bridge session missing");
return {
client,
directory,
session,
stderr: () => stderr,
async close(): Promise<void> {
child.stdin.end("shutdown\n");
const exited = await waitForExit(child, 3_000);
try {
await processes.shutdown();
} finally {
await rm(directory, { recursive: true, force: true });
}
if (!exited) throw new Error(`Python bridge did not exit: ${stderr}`);
},
};
} catch (error) {
child.stdin.end("shutdown\n");
await waitForExit(child, 3_000);
await processes.shutdown();
await rm(directory, { recursive: true, force: true });
throw error;
}
};
it("authenticates bridge peers before payloads and permits status recovery after a poisoned UI timeout", () => {
execFileSync(
"python3",
[resolve("tests/fixtures/cutter_bridge_protocol_test.py")],
{
encoding: "utf8",
timeout: 10_000,
},
);
});
it("round-trips authenticated status and command bytes across the Python producer boundary", async () => {
const bridge = await startPythonBridge();
try {
const { client, session } = bridge;
expect(session.document_generation).toBe(4);
expect(session.current_file).toBe("/tmp/cutter-interop-雪.bin");
for (let index = 0; index <= 64; index += 1) {
await expect(
client.execute({
sessionId: session.session_id,
expectedGeneration: 3,
command: "iI",
json: false,
}),
).rejects.toThrow("List sessions again");
}
const result = await client.execute({
sessionId: session.session_id,
expectedGeneration: session.document_generation,
command: 'print("雪 ☃️ \\\"quoted\\\" \\\\ slash\\nline\\ttab")',
json: false,
});
expect(result.output).toBe(
'round-trip: 雪 ☃️ quote=" slash=\\\\ line=\\n tab=\\t',
);
expect(result.executionState).toBe("complete");
expect(result.documentGeneration).toBe(4);
expect(result.currentFile).toBe("/tmp/cutter-interop-雪.bin");
expect(result.outputTruncated).toBe(false);
} finally {
await bridge.close();
}
});
it("preserves caller A service cleanup proof after caller B acknowledges A", async () => {
const bridge = await startPythonBridge();
try {
const commandInput = {
session_id: bridge.session.session_id,
expected_generation: bridge.session.document_generation,
command: "fixture-unknown",
json: false,
};
const callerA = new CutterBridgeService(bridge.client);
const executionA = await callerA.execute(commandInput);
expect(executionA).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const callerB = new CutterBridgeService(
new CutterBridgeClient({
...process.env,
REA_CUTTER_BRIDGE_DIR: bridge.directory,
}),
);
await expect(
callerB.execute({
...commandInput,
command: "iI",
json: false,
}),
).resolves.toMatchObject({ ok: true });
await expect(callerA.retryCleanup()).resolves.toEqual({
ok: true,
value: null,
});
await expect(
callerA.execute({ ...commandInput, command: "iI" }),
).resolves.toMatchObject({ ok: true });
} finally {
await bridge.close();
}
});
it("recovers orphan receipts across more than 64 fresh CLI clients", async () => {
const bridge = await startPythonBridge();
try {
for (let index = 0; index < 65; index += 1) {
const freshClient = new CutterBridgeClient({
...process.env,
REA_CUTTER_BRIDGE_DIR: bridge.directory,
});
const execution = await freshClient.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "fixture-unknown",
json: false,
});
expect(execution.executionState, `orphan ${index}`).toBe("unknown");
}
const nextInvocation = new CutterBridgeClient({
...process.env,
REA_CUTTER_BRIDGE_DIR: bridge.directory,
});
await expect(
nextInvocation.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "iI",
json: false,
}),
).resolves.toMatchObject({ executionState: "complete" });
} finally {
await bridge.close();
}
});
it("retains failed receipt acknowledgements and retries before another command", async () => {
const bridge = await startPythonBridge();
try {
await expect(
bridge.client.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "fixture-fail-ack",
json: false,
}),
).resolves.toMatchObject({ executionState: "complete" });
await expect(
bridge.client.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "iI",
json: false,
}),
).resolves.toMatchObject({ executionState: "complete" });
} finally {
await bridge.close();
}
});
it("retains a receipt when an ACK reply omits its acknowledgement field", async () => {
const bridge = await startPythonBridge();
try {
await expect(
bridge.client.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "fixture-malformed-ack",
json: false,
}),
).resolves.toMatchObject({ executionState: "complete" });
await expect(
bridge.client.execute({
sessionId: bridge.session.session_id,
expectedGeneration: bridge.session.document_generation,
command: "iI",
json: false,
}),
).resolves.toMatchObject({ executionState: "complete" });
} finally {
await bridge.close();
}
});
@@ -0,0 +1,16 @@
import { expect } from "vitest";
import type { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
type GdbSessionStart = Awaited<ReturnType<GdbSessionManager["start"]>>;
type StartedGdbSession = Extract<GdbSessionStart, { readonly ok: true }>;
export const expectGdbSessionStarted = async (
manager: GdbSessionManager,
...arguments_: Parameters<GdbSessionManager["start"]>
): Promise<StartedGdbSession> => {
const started = await manager.start(...arguments_);
expect(started.ok).toBe(true);
if (!started.ok) throw new Error(started.error.message);
return started;
};
@@ -42,7 +42,7 @@ it("retains the delayed dependency in the complete real framed otool output", as
it("rejects a repeated options field even when the duplicate has no value", async () => {
const output = (await nativeFixture("otool-dylib-use.txt")).replace(
" options delay-init ",
" options delay-init",
" options delay-init\n options",
);
expect(() => parseOtoolLoadCommands(output)).toThrow(/otool/u);
@@ -14,6 +14,7 @@ import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.j
import { err, ok as resultOk } from "../../../src/domain/result.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import {
ControllableAnalysisClient,
@@ -23,9 +24,16 @@ import {
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { copyFile, writeFile } from "node:fs/promises";
import { extname, join } from "node:path";
import { describe, expect, it } from "vitest";
import {
copyFile,
link,
mkdir,
realpath,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, extname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
const client = (fail = false): AnalysisClient => ({
execute: () => Promise.resolve(fail ? err(new HopperStartError()) : ok(null)),
@@ -165,6 +173,247 @@ describe("detached provider and target metadata", () => {
});
});
it("drains session calls and retires analysis after an admitted external mutation", async () => {
const [target] = await createBinarySessionTargets();
const alias = join(dirname(target), "first-alias.hop");
await symlink(target, alias);
const calls: string[] = [];
const clients: { closed: number; targetSha256: string }[] = [];
const base = createCacheProvider(calls);
const session = createTestBinarySession({
...base,
createClient: (...arguments_) => {
const client = base.createClient(...arguments_);
const tracked = { closed: 0, targetSha256: arguments_[0].sha256 };
clients.push(tracked);
return {
...client,
close: async () => {
tracked.closed += 1;
return client.close();
},
};
},
});
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.path).toBe(target);
const originalDigest = session.activeTarget()?.sha256;
const started = createDeferred<void>();
const release = createDeferred<void>();
const mutation = session.withAdmittedExternalMutation(
alias,
undefined,
async () => {
expect(session.activeTarget()?.path).toBe(target);
started.resolve();
await release.promise;
await writeFile(alias, "changed by external provider");
return resultOk("provider finished");
},
(_value, error) => error,
);
await started.promise;
const queuedAnalysis = session.execute("address_name", {});
expect(calls).toEqual([]);
release.resolve();
await expect(mutation).resolves.toMatchObject({
ok: true,
value: { ok: true, value: "provider finished" },
});
expect((await queuedAnalysis).ok).toBe(false);
expect(session.activeTarget()).toBeUndefined();
expect(calls).toEqual([]);
expect(clients).toHaveLength(0);
expect((await session.open(target)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
expect(clients.at(-1)?.targetSha256).toBe(session.activeTarget()?.sha256);
expect(calls).toEqual(["address_name"]);
await session.close();
});
it("leaves analysis unbound when a command returns before its writer finishes", async () => {
const [target] = await createBinarySessionTargets();
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
const originalDigest = session.activeTarget()?.sha256;
const releaseWriter = createDeferred<void>();
let writer: Promise<void> | undefined;
const result = await session.withAdmittedExternalMutation(
target,
undefined,
async () => {
writer = releaseWriter.promise.then(() =>
writeFile(target, "delayed write"),
);
return resultOk("command replied");
},
(_value, error) => error,
);
expect(result).toEqual(resultOk(resultOk("command replied")));
expect(session.activeTarget()).toBeUndefined();
releaseWriter.resolve();
await writer;
expect((await session.execute("address_name", {})).ok).toBe(false);
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
await session.close();
});
it("retires analysis when an external mutation uses a hard link", async () => {
const [target] = await createBinarySessionTargets();
const alias = join(dirname(target), "hard-link-alias.hop");
await link(target, alias);
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
const before = session.activeTarget()?.sha256;
const result = await session.withAdmittedExternalMutation(
alias,
undefined,
async () => {
await writeFile(alias, "changed through hard link");
return resultOk("changed");
},
(_value, error) => error,
);
expect(result).toMatchObject({
ok: true,
value: { ok: true, value: "changed" },
});
expect(session.activeTarget()).toBeUndefined();
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.sha256).not.toBe(before);
await session.close();
});
it("preserves Evidence records while retiring the client after an external mutation", async () => {
const [target] = await createBinarySessionTargets();
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
expect(
(await session.execute("address_name", { address: "0x1000" })).ok,
).toBe(true);
recordNetworkReachabilityUnknown(session, "medium");
const before = session.exportEvidenceBundle();
const result = await session.withAdmittedExternalMutation(
target,
undefined,
async () => resultOk("observed"),
(_value, error) => error,
);
expect(result.ok).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual(before.records);
expect(session.listUnknowns()).toHaveLength(1);
await session.close();
});
it("requires explicitly reopening an app bundle after a session mutation", async () => {
const directory = await createTestTempDirectory("rea-session-app-rebind-");
const app = join(directory, "Fixture.app");
const executable = join(app, "Fixture");
await mkdir(app, { recursive: true });
await writeFile(
join(app, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
);
await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c));
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(app)).ok).toBe(true);
const initial = session.activeTarget();
expect(initial?.sourcePath).toBe(await realpath(app));
const result = await session.withAdmittedExternalMutation(
initial?.path ?? executable,
undefined,
async () => resultOk("observed"),
(_value, error) => error,
);
if (!result.ok) throw result.error;
expect(result).toMatchObject({
ok: true,
value: { ok: true, value: "observed" },
});
expect(session.activeTarget()).toBeUndefined();
expect((await session.open(app)).ok).toBe(true);
expect(session.activeTarget()).toMatchObject({
path: await realpath(executable),
sourcePath: await realpath(app),
bundleInfoPlist: await realpath(join(app, "Info.plist")),
});
await session.close();
});
it("retires an auxiliary-only session after an external mutation", async () => {
const [target] = await createBinarySessionTargets();
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(resultOk(null)),
}));
expect((await session.open(target)).ok).toBe(true);
const result = await session.withAdmittedExternalMutation(
target,
undefined,
async () => resultOk("observed"),
(_value, error) => error,
);
expect(result).toMatchObject({
ok: true,
value: { ok: true, value: "observed" },
});
expect(session.activeTarget()).toBeUndefined();
await session.close();
});
it("keeps an externally mutated session unbound until cleanup is retried", async () => {
const [target] = await createBinarySessionTargets();
const cleanupError = new ProviderCleanupError("fixture", ["provider-child"], {
reason: "process group is still alive",
});
let created = 0;
let closeAttempts = 0;
const session = createTestBinarySession(() => {
created += 1;
return {
execute: () => Promise.resolve(ok(null)),
close: () =>
Promise.resolve(
++closeAttempts === 1 ? err(cleanupError) : resultOk(null),
),
};
});
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()).toBeDefined();
expect(created).toBe(1);
const mutation = await session.withAdmittedExternalMutation(
target,
undefined,
async () => resultOk("dispatched"),
(_value, error) => error,
);
expect(closeAttempts).toBe(1);
expect(mutation.ok).toBe(false);
if (mutation.ok) throw new Error("Expected cleanup failure");
expect(mutation.error).toBeInstanceOf(ProviderCleanupError);
expect(mutation.error.cleanupIncomplete).toBe(true);
expect(session.activeTarget()).toBeUndefined();
expect((await session.execute("address_name", {})).ok).toBe(false);
expect(created).toBe(1);
expect((await session.open(target)).ok).toBe(true);
expect(created).toBe(2);
await session.close();
});
describe("opening previewed targets", () => {
it("rechecks the active target after another serialized transition", async () => {
const [first, second] = await createBinarySessionTargets();
@@ -1279,6 +1528,77 @@ describe("selector origin forwarding", () => {
});
});
it("blocks analysis rebinding until the external writer cleanup settles", async () => {
const [target] = await createBinarySessionTargets();
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
const failure = new ProviderCleanupError("rizin", ["writer"], {
reason: "writer remains alive",
});
const result = await session.withAdmittedExternalMutation(
target,
undefined,
async () => err(failure),
(_value, error) => error,
);
expect(result).toEqual(resultOk(err(failure)));
expect(session.activeTarget()).toBeUndefined();
expect(await session.open(target)).toEqual(err(failure));
const anotherMutation = vi.fn(async () => resultOk("unrelated command"));
expect(
await session.withAdmittedExternalMutation(
target,
undefined,
anotherMutation,
(_value, error) => error,
),
).toEqual(err(failure));
expect(anotherMutation).not.toHaveBeenCalled();
// Only the resource owner may acknowledge completed cleanup.
failure.resolveCleanup();
expect((await session.open(target)).ok).toBe(true);
await session.close();
});
it("requires explicit close before an external mutation of an active Ghidra session", async () => {
const [target] = await createBinarySessionTargets();
const base = createCacheProvider([]);
const identity = { id: "ghidra", name: "Ghidra", version: "fixture" };
const session = createTestBinarySession({
...base,
identity: () => identity,
resolveAnalysisProfile: async () =>
resultOk({
profile: createAnalysisProfile(identity, { fixture: true }),
}),
capabilities: () =>
base.capabilities().map((capability) => ({
...capability,
provider: identity,
})),
});
expect((await session.open(target)).ok).toBe(true);
expect(session.providerIdentity().id).toBe("ghidra");
const mutate = vi.fn(async () => resultOk("mutated"));
const result = await session.withAdmittedExternalMutation(
target,
undefined,
mutate,
(_value, error) => error,
);
expect(result).toMatchObject({
ok: false,
error: {
message: expect.stringContaining(
"Close the active Ghidra session explicitly",
),
},
});
expect(mutate).not.toHaveBeenCalled();
expect(session.activeTarget()?.path).toBe(target);
await session.close();
});
describe("reference truncation forwarding", () => {
const referenceProvider = (
referencesTruncated: boolean | undefined,
@@ -0,0 +1,37 @@
import { expect, it } from "vitest";
import { z } from "zod";
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
import { traceCallPath } from "../../src/application/CallPathTracing.js";
import { ok } from "../../src/domain/result.js";
it("attributes malformed relationship output to the originating provider operation", async () => {
const result = await traceCallPath(
async (operation) =>
ok(operation === "procedure_address" ? "0x1000" : "0x1000"),
async () =>
ok(
createAnalysisExecution(
{ callees: [123] },
{ id: "test", name: "test", version: null },
),
),
{ start: "entry", direction: "forward" },
);
expect(result.ok).toBe(true);
if (result.ok) {
const failures = z
.object({
failures: z.array(
z.object({
error: z.object({
details: z.object({ operation: z.string() }),
}),
}),
),
})
.parse(result.value).failures;
expect(failures[0]?.error.details.operation).toBe("procedure_callees");
}
});
@@ -0,0 +1,95 @@
import { win32 } from "node:path";
import { describe, expect, it } from "vitest";
import { resolveWindowsProviderExecutable } from "../../src/composition/resolveWindowsProviderExecutable.js";
import { createReverseEngineeringCommandPort } from "../../src/composition/reverseEngineering.js";
const windowsLookup = (cwd: string, files: readonly string[]) => {
const existingFiles = new Set(
files.map((path) => win32.normalize(path).toLowerCase()),
);
return {
cwd,
isFile: (path: string): boolean =>
existingFiles.has(win32.normalize(path).toLowerCase()),
};
};
describe("resolveWindowsProviderExecutable", () => {
it("resolves a bare name from quoted and relative Windows PATH entries", () => {
const cwd = "C:\\work";
const expected = "C:\\work\\Program Files\\REA Tools\\objdump.EXE";
expect(
resolveWindowsProviderExecutable(
"objdump",
{
PATH: `.;".\\Program Files\\REA Tools";D:\\unused`,
PATHEXT: ".COM;.EXE;.BAT",
},
windowsLookup(cwd, [expected]),
),
).toBe(expected);
});
it("resolves a relative configured path against the caller's Windows CWD", () => {
expect(
resolveWindowsProviderExecutable(
".\\tools\\objdump.exe",
{},
windowsLookup("D:\\analysis", []),
),
).toBe("D:\\analysis\\tools\\objdump.exe");
});
it("resolves relative PATH hits to absolute drive paths", () => {
const expected = "D:\\analysis\\bin\\rizin.EXE";
expect(
resolveWindowsProviderExecutable(
"rizin",
{ PATH: ".\\bin", PATHEXT: ".EXE" },
windowsLookup("D:\\analysis", [expected]),
),
).toBe(expected);
});
it("skips script extensions and preserves a caller-selected absolute path", () => {
const expected = "C:\\tools\\rizin.EXE";
const selected = "C:\\tools\\rizin.exe";
expect(
resolveWindowsProviderExecutable(
"rizin",
{ PATH: "C:\\tools", PATHEXT: ".CMD;.BAT;.EXE;.COM" },
windowsLookup("C:\\work", ["C:\\tools\\rizin.CMD", expected]),
),
).toBe(expected);
expect(
resolveWindowsProviderExecutable(
selected,
{},
windowsLookup("D:\\work", []),
),
).toBe(selected);
});
it("keeps unresolved bare command names unchanged", () => {
expect(
resolveWindowsProviderExecutable(
"missing-tool",
{ PATH: ".\\tools", PATHEXT: ".EXE" },
windowsLookup("C:\\work", []),
),
).toBe("missing-tool");
});
it("passes an absolute selected command through provider composition", () => {
const commands = createReverseEngineeringCommandPort(
{ REA_OBJDUMP_COMMAND: "C:\\tools\\objdump.exe" },
"win32",
);
expect(
commands.objdump({ path: "artifact", operation: "file_headers" })
.executable,
).toBe("C:\\tools\\objdump.exe");
});
});
@@ -0,0 +1,564 @@
import { createHash } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
import { createReverseEngineeringService } from "../../src/composition/reverseEngineering.js";
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "../../src/contracts/reverseEngineeringToolContracts.js";
describe("reverse engineering command services", () => {
it("documents the shared combined capture limit for both command tools", () => {
for (const contract of REVERSE_ENGINEERING_TOOL_CONTRACTS)
expect(contract.description).toContain("shared 16 MiB combined limit");
expect(REVERSE_ENGINEERING_TOOL_CONTRACTS[0]?.description).toContain(
"does not follow local debug links by default",
);
});
it("uses compatible local DWARF link flags and disables debuginfod through the environment", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-tools-"));
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
const calls: {
command: string;
args: readonly string[];
env: NodeJS.ProcessEnv | undefined;
}[] = [];
const service = new ReverseEngineeringService({
environment: {
REA_OBJDUMP_COMMAND: "/tools/objdump",
DEBUGINFOD_URLS: "https://debug.example.invalid",
},
run: async (command, args, options) => {
calls.push({ command, args, env: options?.env });
return { stdout: "DWARF output\n", stderr: "diagnostic\n" };
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "dwarf",
follow_debug_links: true,
});
if (!result.ok) throw result.error;
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(calls).toEqual([
{
command: "/tools/objdump",
args: ["-W", "-WK", path],
env: expect.objectContaining({ DEBUGINFOD_URLS: "" }),
},
]);
expect(result.value.raw_result).toMatchObject({
stdout: "DWARF output\n",
stderr: "diagnostic\n",
exit_code: 0,
output_truncated: false,
});
expect(result.value.provider.id).toBe("gnu.objdump");
expect(result.value.subject?.local_path).toBe(path);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects non-regular artifacts without launching the provider", async () => {
const directory = await mkdtemp(
join(tmpdir(), "rea-reverse-special-file-"),
);
let invoked = false;
const service = new ReverseEngineeringService({
run: async () => {
invoked = true;
return { stdout: "", stderr: "" };
},
});
try {
const result = await service.inspectWithObjdump({
path: directory,
operation: "file_headers",
});
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.cause).toMatchObject({
code: "EINVAL",
message: "Artifact digest requires a regular file",
});
expect(invoked).toBe(false);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("classifies captured spawn failures instead of reporting provider evidence", async () => {
const directory = await mkdtemp(
join(tmpdir(), "rea-objdump-spawn-failure-"),
);
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const service = new ReverseEngineeringService({
run: async () => {
const failure = Object.assign(new Error("not found"), {
stdout: "",
stderr: "",
code: "ENOENT",
signal: null,
killed: false,
});
throw failure;
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(result.error.message).toContain("ENOENT");
expect(result.error.message).not.toContain("stdout");
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("marks max-buffer termination as unknown completion while retaining output", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-objdump-max-buffer-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const service = new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("max buffer exceeded"), {
stdout: "captured partial output",
stderr: "",
code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
signal: "SIGTERM",
killed: true,
});
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "wx 00 @ 0",
});
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.raw_result).toMatchObject({
stdout: "captured partial output",
exit_code: null,
output_truncated: true,
completion_status: "unknown",
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
it("uses one selected environment snapshot for provider selection and execution", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-environment-"));
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
const selectedEnvironment = {
REA_RIZIN_COMMAND: "/selected/rizin",
PATH: "/selected/bin",
SELECTED_VALUE: "captured",
};
const calls: { command: string; env: NodeJS.ProcessEnv | undefined }[] = [];
const service = createReverseEngineeringService(selectedEnvironment, {
run: async (command, _args, options) => {
calls.push({ command, env: options?.env });
return { stdout: "headers", stderr: "" };
},
});
selectedEnvironment.REA_RIZIN_COMMAND = "/changed/rizin";
selectedEnvironment.SELECTED_VALUE = "changed after construction";
try {
const result = await service.executeRizinCommand({
path,
command: "iI",
});
expect(result.ok).toBe(true);
expect(calls).toEqual([
{
command: "/selected/rizin",
env: {
REA_RIZIN_COMMAND: "/selected/rizin",
PATH: "/selected/bin",
SELECTED_VALUE: "captured",
},
},
]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("marks signal-terminated provider commands as unknown completion", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-signal-exit-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
let invocation = 0;
const service = new ReverseEngineeringService({
run: async () => {
invocation += 1;
if (invocation === 1)
throw Object.assign(new Error("provider killed by signal"), {
stdout: "partial output",
stderr: "",
code: null,
signal: "SIGKILL",
killed: true,
});
throw Object.assign(new Error("provider exited with status 2"), {
stdout: "ordinary partial output",
stderr: "ordinary diagnostic",
code: 2,
signal: null,
killed: false,
});
},
});
try {
const signaled = await service.executeRizinCommand({
path,
command: "wx 00 @ 0",
});
expect(signaled.ok).toBe(true);
if (signaled.ok) {
expect(signaled.value.raw_result).toMatchObject({
stdout: "partial output",
exit_code: null,
signal: "SIGKILL",
completion_status: "unknown",
});
expect(signaled.value.limitations.join(" ")).toContain("signal");
}
const ordinaryExit = await service.executeRizinCommand({
path,
command: "iI",
});
expect(ordinaryExit.ok).toBe(true);
if (ordinaryExit.ok) {
expect(ordinaryExit.value.raw_result).toMatchObject({
stdout: "ordinary partial output",
exit_code: 2,
signal: null,
completion_status: "complete",
});
expect(ordinaryExit.value.limitations.join(" ")).not.toContain(
"terminated by signal",
);
expect(ordinaryExit.value.limitations).toContain(
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
);
expect(ordinaryExit.value.limitations).toHaveLength(4);
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
describe("Rizin command service", () => {
it("runs Rizin with user scripts suppressed while retaining plugins and preserves nonzero output", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const calls: { command: string; args: readonly string[] }[] = [];
const service = new ReverseEngineeringService({
environment: { REA_RIZIN_COMMAND: "/tools/rizin" },
run: async (command, args) => {
calls.push({ command, args });
const failure = new Error("command exited with status 2") as Error & {
stdout: string;
stderr: string;
code: number;
signal: null;
killed: boolean;
};
Object.assign(failure, {
stdout: "partial data",
stderr: "command error",
code: 2,
signal: null,
killed: false,
});
throw failure;
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(calls).toEqual([
{
command: "/tools/rizin",
args: ["-N", "-q", "-c", "iI", path],
},
]);
expect(result.value.raw_result).toMatchObject({
stdout: "partial data",
stderr: "command error",
exit_code: 2,
completion_status: "complete",
});
expect(result.value.limitations.join(" ")).not.toContain(
"terminated by signal",
);
expect(result.value.limitations).toContain(
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
);
expect(result.value.limitations).toHaveLength(4);
expect(result.value.parameters).toMatchObject({
command: "iI",
provider_executable: "/tools/rizin",
});
expect(result.value.provider.id).toBe("rizin");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects multiline Rizin command input before launching the provider", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-input-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
let invoked = false;
const service = new ReverseEngineeringService({
run: async () => {
invoked = true;
return { stdout: "", stderr: "" };
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "iI\nq",
});
expect(result.ok).toBe(false);
expect(invoked).toBe(false);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves pre and post artifact digests when an unrestricted Rizin command changes the file", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-mutation-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "before");
const service = new ReverseEngineeringService({
run: async () => {
await writeFile(path, "after");
return { stdout: "changed", stderr: "" };
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "wx 00 @ 0",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.subject?.digest.sha256).toBe(
createHash("sha256").update("before").digest("hex"),
);
expect(result.value.raw_result).toMatchObject({
artifact_sha256_after: createHash("sha256")
.update("after")
.digest("hex"),
artifact_changed: true,
});
expect(result.value.limitations).toContain(
"The provider command may have changed the artifact while analysis was running; pre-run and post-run digests are both reported.",
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
it("retains partial Evidence when a provider command times out", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-partial-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "before");
const service = new ReverseEngineeringService({
run: async () => {
const failure = Object.assign(new Error("timeout"), {
stdout: "captured before timeout",
stderr: "still running",
code: "ETIMEDOUT",
signal: "SIGTERM",
killed: true,
});
throw failure;
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "wx 00 @ 0",
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisTimeoutError");
expect(result.error.partialObservation).toMatchObject({
operation: "execute_rizin_command",
raw_result: {
stdout: "captured before timeout",
stderr: "still running",
completion_status: "unknown",
signal: "SIGTERM",
artifact_sha256_after: expect.any(String),
},
});
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
"captured before timeout",
);
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves raw byte counts when cancellation rejects invalid UTF-8 output", async () => {
const directory = await mkdtemp(
join(tmpdir(), "rea-rizin-abort-invalid-utf8-"),
);
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const controller = new AbortController();
const failure = Object.assign(new Error("The operation was aborted"), {
stdout: "�",
stderr: "€",
stdoutBytes: 1,
stderrBytes: 3,
code: "ABORT_ERR",
signal: null,
killed: true,
});
const service = new ReverseEngineeringService({
run: async () => {
controller.abort();
throw failure;
},
});
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.capturedOutput).toMatchObject({
stdout: "�",
stderr: "€",
stdout_bytes: 1,
stderr_bytes: 3,
});
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves provider facts when cancellation interrupts the post-run digest", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-digest-cancel-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const controller = new AbortController();
const service = new ReverseEngineeringService({
run: async () => {
controller.abort();
return {
stdout: "�",
stderr: "�",
stdoutInvalidUtf8: true,
stderrInvalidUtf8: true,
stdoutBytes: 1,
stderrBytes: 1,
};
},
});
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.capturedOutput).toMatchObject({
stdout: "�",
stderr: "�",
stdout_bytes: 1,
stderr_bytes: 1,
exit_code: 0,
signal: null,
});
expect(result.error.partialObservation).toMatchObject({
raw_result: {
stdout: "�",
exit_code: null,
completion_status: "unknown",
artifact_sha256_after: null,
},
limitations: expect.arrayContaining([
expect.stringContaining("cancellation interrupted the digest"),
]),
});
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("marks signal-terminated provider output incomplete", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-signal-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
const service = new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("terminated"), {
stdout: "partial",
stderr: "",
code: null,
signal: "SIGSEGV",
killed: false,
});
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.raw_result).toMatchObject({
signal: "SIGSEGV",
exit_code: null,
completion_status: "unknown",
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
@@ -0,0 +1,103 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import { TestReverseEngineeringService } from "../support/reverseEngineeringService.js";
it("bounds concurrent reverse-engineering provider calls", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-capacity-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let calls = 0;
let mode: "success" | "failure" | "timeout" = "success";
const service = new TestReverseEngineeringService({
run: async () => {
calls += 1;
if (mode === "failure")
throw Object.assign(new Error("provider failed"), { code: "ENOENT" });
if (mode === "timeout")
throw Object.assign(new Error("provider timed out"), {
code: "ETIMEDOUT",
});
await gate;
return { stdout: "", stderr: "" };
},
});
try {
const active = Array.from({ length: 8 }, () =>
service.inspectWithObjdump({ path, operation: "file_headers" }),
);
const preAborted = new AbortController();
preAborted.abort();
await expect(
service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: preAborted.signal },
),
).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
await expect(
service.inspectWithObjdump({ path, operation: "file_headers" }),
).resolves.toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
resource: "transport",
reportedLimits: {
max_concurrent_operations: 8,
active_operations: 8,
},
},
});
release();
const results = await Promise.all(active);
expect(results.every((result) => result.ok)).toBe(true);
expect(calls).toBe(8);
mode = "failure";
const failed = await Promise.all(
Array.from({ length: 8 }, () =>
service.inspectWithObjdump({ path, operation: "file_headers" }),
),
);
expect(failed.every((result) => !result.ok)).toBe(true);
mode = "timeout";
const timedOut = await Promise.all(
Array.from({ length: 8 }, () =>
service.inspectWithObjdump({ path, operation: "file_headers" }),
),
);
expect(timedOut.every((result) => !result.ok)).toBe(true);
const aborted = new AbortController();
aborted.abort();
const cancelled = await Promise.all(
Array.from({ length: 8 }, () =>
service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: aborted.signal },
),
),
);
expect(cancelled.every((result) => !result.ok)).toBe(true);
mode = "success";
await expect(
service.inspectWithObjdump({ path, operation: "file_headers" }),
).resolves.toMatchObject({ ok: true });
} finally {
release();
await service.close();
await rm(directory, { recursive: true, force: true });
}
});
@@ -0,0 +1,288 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
type PromiseOutcome<Value> =
| { readonly status: "fulfilled"; readonly value: Value }
| { readonly status: "rejected"; readonly reason: unknown }
| { readonly status: "timeout" };
const settleWithin = async <Value>(
promise: Promise<Value>,
timeoutMs: number,
): Promise<PromiseOutcome<Value>> => {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise.then(
(value): PromiseOutcome<Value> => ({ status: "fulfilled", value }),
(reason: unknown): PromiseOutcome<Value> => ({
status: "rejected",
reason,
}),
),
new Promise<PromiseOutcome<Value>>((resolve) => {
timer = setTimeout(() => resolve({ status: "timeout" }), timeoutMs);
}),
]);
} finally {
if (timer !== undefined) clearTimeout(timer);
}
};
const processIsRunning = (pid: number): boolean => {
try {
process.kill(pid, 0);
return true;
} catch (cause) {
return !(
cause instanceof Error &&
"code" in cause &&
cause.code === "ESRCH"
);
}
};
const waitForProcessExit = async (
pid: number,
timeoutMs: number,
): Promise<boolean> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (!processIsRunning(pid)) return true;
await new Promise((resolve) => setTimeout(resolve, 10));
}
return !processIsRunning(pid);
};
const killProcessAndWait = async (
pid: number,
timeoutMs: number,
): Promise<boolean> => {
try {
process.kill(pid, "SIGKILL");
} catch (cause) {
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
throw cause;
}
return waitForProcessExit(pid, timeoutMs);
};
type CancellationResult = Awaited<
ReturnType<ReverseEngineeringService["executeRizinCommand"]>
>;
interface CancellationProcessMarkers {
readonly providerPid: string;
readonly descendantPid: string;
readonly descendantStarted: string;
}
interface CancellationProcessIds {
readonly providerPid: number;
readonly descendantPid: number;
}
const readProcessMarker = async (path: string): Promise<number | undefined> => {
const text = await readFile(path, "utf8").catch(() => "");
const pid = Number(text);
return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
};
const waitForCancellationProcesses = async (
markers: CancellationProcessMarkers,
): Promise<CancellationProcessIds> => {
for (let attempt = 0; attempt < 500; attempt += 1) {
const [providerPid, descendantPid, descendantStarted] = await Promise.all([
readProcessMarker(markers.providerPid),
readProcessMarker(markers.descendantPid),
readFile(markers.descendantStarted).then(
() => true,
() => false,
),
]);
if (
providerPid !== undefined &&
descendantPid !== undefined &&
descendantStarted
)
return { providerPid, descendantPid };
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
}
throw new Error("Rizin provider and descendant did not start in time.");
};
const killCancellationProcesses = async (
ids: CancellationProcessIds,
): Promise<void> => {
expect(await killProcessAndWait(ids.providerPid, 2_000)).toBe(true);
expect(await killProcessAndWait(ids.descendantPid, 2_000)).toBe(true);
};
const settleCancelledProvider = async (
pending: Promise<CancellationResult>,
): Promise<CancellationResult> => {
const outcome = await settleWithin(pending, 7_000);
if (outcome.status === "timeout")
throw new Error("Rizin cancellation did not settle before its deadline");
if (outcome.status === "rejected") throw outcome.reason;
return outcome.value;
};
const expectCancelledResult = (result: CancellationResult): void => {
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cleanup).toBeUndefined();
expect(result.error.capturedOutput).toMatchObject({
stdout: "provider output before cancellation",
stderr: "",
truncated: false,
exit_code: null,
signal: "SIGKILL",
});
expect(result.error.cause).toBeInstanceOf(Error);
expect(result.error.partialObservation).toMatchObject({
raw_result: {
stdout: "provider output before cancellation",
completion_status: "unknown",
},
});
};
const cleanupCancellationScenario = async (options: {
readonly controller: AbortController;
readonly pending: Promise<CancellationResult> | undefined;
readonly service: ReverseEngineeringService;
readonly processIds: CancellationProcessIds | undefined;
readonly directory: string;
}): Promise<void> => {
options.controller.abort();
try {
if (options.pending !== undefined) {
try {
if (options.processIds !== undefined)
await settleCancelledProvider(options.pending);
else await settleWithin(options.pending, 10_000);
} catch {
// Main assertions report operation failures; continue cleanup.
}
}
let cleanup = await settleWithin(options.service.close(), 7_000);
if (cleanup.status === "timeout" && options.processIds !== undefined) {
await killCancellationProcesses(options.processIds);
cleanup = await settleWithin(options.service.close(), 3_000);
}
if (cleanup.status === "timeout")
throw new Error("Service cleanup did not settle within its deadline.");
if (cleanup.status === "rejected") throw cleanup.reason;
if (options.processIds !== undefined) {
for (const pid of [
options.processIds.providerPid,
options.processIds.descendantPid,
]) {
if (processIsRunning(pid)) await killProcessAndWait(pid, 2_000);
}
}
} finally {
await rm(options.directory, { recursive: true, force: true });
}
};
it("uses stoppable process mode for caller-selected provider commands", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-stoppable-"));
const path = join(directory, "fixture.bin");
await writeFile(path, "fixture");
let received: Record<string, unknown> | undefined;
const service = new ReverseEngineeringService({
run: async (_command, _args, options) => {
received = options as Record<string, unknown>;
return { stdout: "", stderr: "" };
},
});
try {
await service.executeRizinCommand({ path, command: "iI" });
expect(received?.stopSignal).toBe("SIGTERM");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.skipIf(process.platform === "win32")(
"waits for a cancelled Rizin process to exit before returning",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-cancel-settle-"));
const path = join(directory, "fixture.bin");
const providerPidMarker = join(directory, "provider-pid");
const descendantStartedMarker = join(directory, "descendant-started");
const descendantPidMarker = join(directory, "descendant-pid");
const provider = join(directory, "slow-rizin.mjs");
const descendantScript = [
"const fs = require('node:fs');",
"process.on('SIGTERM', () => {});",
"fs.writeFileSync(process.env.REA_TEST_DESCENDANT_STARTED, 'started');",
"setInterval(() => {}, 1000);",
].join("\n");
await writeFile(path, "before");
await writeFile(
provider,
`#!${process.execPath}
import { spawn } from "node:child_process";
import { writeFileSync } from "node:fs";
writeFileSync(process.env.REA_TEST_PROVIDER_PID, String(process.pid));
process.stdout.write("provider output before cancellation");
const child = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], { env: process.env, stdio: "ignore" });
writeFileSync(process.env.REA_TEST_DESCENDANT_PID, String(child.pid));
setInterval(() => {}, 1000);
`,
);
await chmod(provider, 0o755);
const controller = new AbortController();
const service = new ReverseEngineeringService({
environment: {
REA_RIZIN_COMMAND: provider,
REA_TEST_ARTIFACT: path,
REA_TEST_PROVIDER_PID: providerPidMarker,
REA_TEST_DESCENDANT_STARTED: descendantStartedMarker,
REA_TEST_DESCENDANT_PID: descendantPidMarker,
},
});
let pending: ReturnType<typeof service.executeRizinCommand> | undefined;
let processIds: CancellationProcessIds | undefined;
try {
pending = service.executeRizinCommand(
{ path, command: "sleep" },
{ signal: controller.signal },
);
processIds = await waitForCancellationProcesses({
providerPid: providerPidMarker,
descendantPid: descendantPidMarker,
descendantStarted: descendantStartedMarker,
});
controller.abort();
expectCancelledResult(await settleCancelledProvider(pending));
expect(await readFile(path, "utf8")).toBe("before");
expect(await waitForProcessExit(processIds.descendantPid, 2_000)).toBe(
true,
);
expect(await waitForProcessExit(processIds.providerPid, 2_000)).toBe(
true,
);
} finally {
await cleanupCancellationScenario({
controller,
pending,
service,
processIds,
directory,
});
}
},
);
@@ -0,0 +1,114 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { ReverseEngineeringService } from "../../src/application/reverse/ReverseEngineeringService.js";
import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "../../src/contracts/reverseEngineeringToolContracts.js";
import { execFileOutput } from "../../src/process/ExecFileOutput.js";
type ExecFileOutputOptions = NonNullable<Parameters<typeof execFileOutput>[2]>;
it("documents the shared combined capture limit for both command tools", () => {
for (const contract of REVERSE_ENGINEERING_TOOL_CONTRACTS)
expect(contract.description).toContain("shared 16 MiB combined limit");
});
it("uses provider profiles supplied through the application port", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-port-"));
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
const run = vi.fn(
async (
_command: string,
_args: readonly string[],
_options?: ExecFileOutputOptions,
) => ({ stdout: "injected", stderr: "" }),
);
const service = new ReverseEngineeringService({
environment: { REA_OBJDUMP_COMMAND: "ambient-objdump" },
commands: {
objdump: () => ({
executable: "injected-objdump",
arguments: ["--injected", path],
identity: {
id: "test.objdump",
name: "Injected objdump",
version: null,
},
environmentOverrides: { INJECTED_PROFILE: "yes" },
}),
rizin: () => ({
executable: "injected-rizin",
arguments: ["--injected", path],
identity: { id: "test.rizin", name: "Injected Rizin", version: null },
}),
},
run,
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result.ok).toBe(true);
const call = run.mock.calls[0];
expect(call?.[0]).toBe("injected-objdump");
expect(call?.[1]).toEqual(["--injected", path]);
expect(call?.[2]?.env?.INJECTED_PROFILE).toBe("yes");
if (result.ok) expect(result.value.provider.id).toBe("test.objdump");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("does not reintroduce ambient variables absent from the captured provider environment", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-env-"));
const path = join(directory, "fixture.bin");
const variable = "REA_TEST_LATE_PROVIDER_ENV";
const previous = process.env[variable];
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
process.env[variable] = "late-ambient-value";
const run = vi.fn(
async (
_command: string,
_args: readonly string[],
_options?: ExecFileOutputOptions,
) => ({ stdout: "captured", stderr: "" }),
);
const service = new ReverseEngineeringService({
environment: { REA_OBJDUMP_COMMAND: "captured-objdump" },
commands: {
objdump: () => ({
executable: "captured-objdump",
arguments: [path],
identity: {
id: "test.objdump",
name: "Captured objdump",
version: null,
},
environmentOverrides: { PROFILE_VALUE: "explicit" },
}),
rizin: () => ({
executable: "captured-rizin",
arguments: [path],
identity: { id: "test.rizin", name: "Captured Rizin", version: null },
}),
},
run,
});
try {
await service.inspectWithObjdump({ path, operation: "file_headers" });
expect(run.mock.calls[0]?.[2]?.env).toEqual({
REA_OBJDUMP_COMMAND: "captured-objdump",
PROFILE_VALUE: "explicit",
});
} finally {
if (previous === undefined) delete process.env[variable];
else process.env[variable] = previous;
await rm(directory, { recursive: true, force: true });
}
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
import { rm } from "node:fs/promises";
import { createArtifact } from "../support/reverseEngineeringCompositionFixtures.js";
import { expect, it, vi } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
it("rejects NUL in a Rizin command before touching the provider", async () => {
const { directory, path } = await createArtifact();
let invoked = false;
const service = new ReverseEngineeringService({
run: async () => {
invoked = true;
return { stdout: "", stderr: "" };
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "wx\u0000 00",
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", operation: "execute_rizin_command" },
});
expect(invoked).toBe(false);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
@@ -27,7 +27,7 @@ Relocation section '.rel.data' at offset 0x118 contains 2 entries:
Symbol table '.symtab' contains 4 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 16 FUNC GLOBAL DEFAULT 1 func
2: 00008000 4 OBJECT GLOBAL DEFAULT 3 far_data
3: 00000000 0 NOTYPE GLOBAL DEFAULT UND ext_data
+454
View File
@@ -0,0 +1,454 @@
"""Producer-level regression tests for Cutter's authenticated local protocol."""
import hashlib
import hmac
import importlib.util
import json
import os
import socket
import sys
import tempfile
import threading
import time
import types
import unittest
import uuid
from pathlib import Path
def _install_host_stubs():
cutter = types.ModuleType("cutter")
cutter.CutterPlugin = type("CutterPlugin", (), {})
sys.modules["cutter"] = cutter
qtcore = types.ModuleType("PySide6.QtCore")
qtcore.QObject = type("QObject", (), {})
qtcore.Signal = lambda *_args: object()
pyside = types.ModuleType("PySide6")
pyside.QtCore = qtcore
sys.modules["PySide6"] = pyside
sys.modules["PySide6.QtCore"] = qtcore
_install_host_stubs()
MODULE_PATH = Path(__file__).parents[2] / "bridge" / "cutter" / "rea_bridge.py"
spec = importlib.util.spec_from_file_location("rea_cutter_bridge_test", MODULE_PATH)
bridge = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = bridge
spec.loader.exec_module(bridge)
def _frame(connection):
data = bytearray()
while b"\n" not in data:
data.extend(connection.recv(4096))
if len(data) > bridge.MAX_FRAME_BYTES:
raise AssertionError("oversized test frame")
line, remainder = bytes(data).split(b"\n", 1)
if remainder:
raise AssertionError("unexpected pipelined frame")
return json.loads(line)
def _send(connection, value):
connection.sendall(json.dumps(value, separators=(",", ":")).encode() + b"\n")
class Dispatcher:
generation = 4
current_file = "/tmp/sample.bin"
cutter_version = "test"
def __init__(self):
self.dispatch = self
self.commands = []
self.completed_commands = {}
self.lock = threading.Lock()
self.command_started = threading.Event()
self.finish_command = threading.Event()
self.status_queued = threading.Event()
def _read_current_file(self):
return self.current_file
def can_accept_command(self):
return len(self.completed_commands) < bridge.MAX_COMPLETION_RECEIPTS
def emit(self, request, reply):
def run():
kind = request.get("kind")
if kind == "command":
self.command_started.set()
elif kind == "status":
self.status_queued.set()
with self.lock:
if kind == "command":
self.finish_command.wait(2)
self.commands.append(kind)
if kind == "status":
reply.update({"ok": True, "session_id": request["session_id"], "document_generation": self.generation,
"current_file": self.current_file, "cutter_version": self.cutter_version,
"identity_status": "partial", "completed_commands": [
{"request_id": request_id, "execution_state": state}
for request_id, state in self.completed_commands.items()
]})
elif kind == "ack":
reply.update({"ok": True, "acknowledged": self.completed_commands.pop(request["request_id"], None) is not None})
else:
reply.update({"ok": True, "execution_state": "complete"})
if kind == "command" and isinstance(request.get("request_id"), str):
self.completed_commands[request["request_id"]] = "complete"
request["_event"].set()
threading.Thread(target=run, daemon=True).start()
class ServeDispatcher:
"""Small UI-dispatcher stand-in for real producer/client interoperability."""
generation = 4
current_file = "/tmp/cutter-interop-雪.bin"
cutter_version = "fixture"
def __init__(self):
self.dispatch = self
self.completed_commands = {}
self.fail_next_ack = False
self.malformed_next_ack = False
self.hide_receipts_after_ack_failure = False
def can_accept_command(self):
return len(self.completed_commands) < bridge.MAX_COMPLETION_RECEIPTS
def _read_current_file(self):
return self.current_file
def emit(self, request, reply):
if request.get("kind") == "status":
reply.update({
"ok": True,
"session_id": request["session_id"],
"document_generation": self.generation,
"current_file": self.current_file,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"completed_commands": [
{"request_id": request_id, "execution_state": state}
for request_id, state in self.completed_commands.items()
] if not self.hide_receipts_after_ack_failure else [],
})
elif request.get("kind") == "ack":
if self.malformed_next_ack:
self.malformed_next_ack = False
reply.update({"ok": True, "session_id": request["session_id"]})
request["_event"].set()
return
if self.fail_next_ack:
self.fail_next_ack = False
self.hide_receipts_after_ack_failure = True
reply.update({"ok": False, "acknowledged": False})
request["_event"].set()
return
reply.update({
"ok": True,
"acknowledged": self.completed_commands.pop(request["request_id"], None) is not None,
})
self.hide_receipts_after_ack_failure = False
elif request.get("kind") == "command" and request.get("expected_generation") != self.generation:
reply.update({
"ok": False,
"error": "active-document-generation-changed",
"execution_state": "not_started",
})
self.completed_commands[request["request_id"]] = "not_started"
elif request.get("kind") == "command" and request.get("command") == "fixture-unknown":
reply.update({
"ok": False,
"error": "fixture-response-lost-after-completion",
"execution_state": "unknown",
})
self.completed_commands[request["request_id"]] = "complete"
elif request.get("kind") == "command" and request.get("command") == "fixture-fail-ack":
reply.update({
"ok": True,
"output": "ack will fail once",
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "complete",
})
self.completed_commands[request["request_id"]] = "complete"
self.fail_next_ack = True
elif request.get("kind") == "command" and request.get("command") == "fixture-malformed-ack":
reply.update({
"ok": True,
"output": "ack reply will be malformed once",
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "complete",
})
self.completed_commands[request["request_id"]] = "complete"
self.malformed_next_ack = True
else:
reply.update({
"ok": True,
"output": 'round-trip: 雪 ☃️ quote=" slash=\\\\ line=\\n tab=\\t',
"current_file": self.current_file,
"document_generation": self.generation,
"cutter_version": self.cutter_version,
"identity_status": "partial",
"execution_state": "complete",
})
if request.get("kind") == "command":
self.completed_commands[request["request_id"]] = "complete"
request["_event"].set()
def run_serve_mode():
server = bridge._BridgeServer(ServeDispatcher())
server.start()
try:
deadline = time.monotonic() + 5
while not server.descriptor.exists() and time.monotonic() < deadline:
time.sleep(0.005)
if not server.descriptor.exists():
raise RuntimeError("bridge descriptor was not published")
print("ready", flush=True)
sys.stdin.buffer.readline()
finally:
server.stop()
server.join(timeout=3)
class ProtocolProducerTest(unittest.TestCase):
def test_rejects_legacy_peers_before_ui_dispatch(self):
with socket.create_connection(("127.0.0.1", self.server.port), timeout=2) as connection:
connection.sendall((json.dumps({"kind": "rea-auth-v1", "nonce": "a" * 64}) + "\n").encode())
with connection.makefile("rb") as reader:
reply = json.loads(reader.readline())
self.assertEqual(reply, {"ok": False, "error": "authentication-failed"})
self.assertEqual(self.dispatcher.commands, [])
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
os.environ["REA_CUTTER_BRIDGE_DIR"] = self.temp.name
self.dispatcher = Dispatcher()
self.server = bridge._BridgeServer(self.dispatcher)
bridge.SOCKET_TIMEOUT_SECONDS = 0.1
self.server.start()
deadline = time.monotonic() + 2
while not self.server.descriptor.exists() and time.monotonic() < deadline:
time.sleep(0.005)
self.assertTrue(self.server.descriptor.exists())
def tearDown(self):
self.server.stop()
self.server.join(timeout=2)
os.environ.pop("REA_CUTTER_BRIDGE_DIR", None)
self.temp.cleanup()
def exchange(self, request):
token = self.server.token.encode()
client_nonce = os.urandom(32).hex()
with socket.create_connection(("127.0.0.1", self.server.port), timeout=1) as connection:
_send(connection, {"kind": "rea-auth-v2", "nonce": client_nonce})
challenge = _frame(connection)
self.assertEqual(challenge["session_id"], self.server.session_id)
server_nonce = challenge["nonce"]
expected_server = hmac.new(token, f"rea-cutter-server-v2:{self.server.session_id}:{client_nonce}:{server_nonce}".encode(), hashlib.sha256).hexdigest()
self.assertTrue(hmac.compare_digest(challenge["proof"], expected_server))
request_bytes = json.dumps(request, separators=(",", ":"))
proof = hmac.new(token, f"rea-cutter-client-v2:{self.server.session_id}:{client_nonce}:{server_nonce}:{request_bytes}".encode(), hashlib.sha256).hexdigest()
_send(connection, {"request": request_bytes, "proof": proof})
frame = _frame(connection)
if "response" not in frame:
return frame, client_nonce
response = frame["response"]
expected_response = hmac.new(token, f"rea-cutter-response-v2:{self.server.session_id}:{client_nonce}:{server_nonce}:{response}".encode(), hashlib.sha256).hexdigest()
self.assertTrue(hmac.compare_digest(frame["proof"], expected_response))
return json.loads(response), client_nonce
def test_request_session_uuid_is_checked_after_secret_proof(self):
spoofed = {"kind": "status", "session_id": "client-chosen-session"}
response, _ = self.exchange(spoofed)
self.assertEqual(response["error"], "authentication-failed")
self.assertEqual(self.dispatcher.commands, [])
def test_client_chosen_session_uuid_without_secret_proof_is_not_authenticated(self):
client_nonce = os.urandom(32).hex()
with socket.create_connection(("127.0.0.1", self.server.port), timeout=1) as connection:
_send(connection, {"kind": "rea-auth-v2", "nonce": client_nonce})
_frame(connection)
request_bytes = json.dumps({"kind": "status", "session_id": "client-chosen-session"}, separators=(",", ":"))
_send(connection, {"request": request_bytes, "proof": "0" * 64})
self.assertEqual(_frame(connection)["error"], "authentication-failed")
self.assertEqual(self.dispatcher.commands, [])
def test_cancelled_command_receipt_survives_later_command_until_acknowledged(self):
dispatcher = object.__new__(bridge._RequestDispatcher)
dispatcher.generation = 4
dispatcher.current_file = "/tmp/sample.bin"
dispatcher.cutter_version = "test"
dispatcher.completed_commands = {}
dispatcher._receipt_lock = threading.Lock()
dispatcher._refresh_document_identity = lambda: None
bridge.cutter.cmd = lambda command: f"output:{command}"
def handle(value):
request = {
**value,
"_event": threading.Event(),
"_cancelled": threading.Event(),
}
reply = {}
bridge._RequestDispatcher._handle(dispatcher, request, reply)
self.assertTrue(request["_event"].is_set())
return reply
request_a = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db"
request_b = "8ca93d11-107d-41ed-8b40-31dd53cd26a6"
for request_id, command in ((request_a, "A"), (request_b, "B")):
result = handle({
"kind": "command",
"request_id": request_id,
"expected_generation": 4,
"command": command,
})
self.assertTrue(result["ok"])
status = handle({"kind": "status"})
self.assertEqual(
{receipt["request_id"] for receipt in status["completed_commands"]},
{request_a, request_b},
)
acknowledged = handle({"kind": "ack", "request_id": request_a})
self.assertTrue(acknowledged["acknowledged"])
after_ack = handle({"kind": "status"})
self.assertEqual(
[receipt["request_id"] for receipt in after_ack["completed_commands"]],
[request_b],
)
def test_stale_generation_rejections_are_terminal_and_acknowledged(self):
dispatcher = object.__new__(bridge._RequestDispatcher)
dispatcher.generation = 4
dispatcher.current_file = "/tmp/sample.bin"
dispatcher.cutter_version = "test"
dispatcher.completed_commands = {}
dispatcher._receipt_lock = threading.Lock()
dispatcher._refresh_document_identity = lambda: None
def handle(value):
request = {
**value,
"_event": threading.Event(),
"_cancelled": threading.Event(),
}
reply = {}
bridge._RequestDispatcher._handle(dispatcher, request, reply)
self.assertTrue(request["_event"].is_set())
return reply
invalid_id = str(uuid.UUID(int=bridge.MAX_COMPLETION_RECEIPTS + 10))
invalid = handle({
"kind": "command",
"request_id": invalid_id,
"expected_generation": 4,
"command": "",
})
self.assertEqual(invalid["execution_state"], "not_started")
self.assertTrue(handle({"kind": "ack", "request_id": invalid_id})["acknowledged"])
for index in range(bridge.MAX_COMPLETION_RECEIPTS + 1):
request_id = str(uuid.UUID(int=index + 1))
response = handle({
"kind": "command",
"request_id": request_id,
"expected_generation": 3,
"command": "iI",
})
self.assertEqual(response["execution_state"], "not_started")
self.assertEqual(response["error"], "active-document-generation-changed")
self.assertTrue(handle({"kind": "ack", "request_id": request_id})["acknowledged"])
self.assertEqual(dispatcher.completed_commands, {})
self.assertTrue(dispatcher.can_accept_command())
def test_poisoned_rejection_is_definitively_not_started_without_dispatch(self):
self.server.poisoned = True
response, _ = self.exchange({
"kind": "command",
"session_id": self.server.session_id,
"request_id": "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
})
self.assertEqual(response["error"], "session-poisoned-after-ui-timeout")
self.assertEqual(response["execution_state"], "not_started")
self.assertEqual(self.dispatcher.commands, [])
def test_receipt_capacity_rejects_before_ui_dispatch(self):
self.dispatcher.can_accept_command = lambda: False
response, _ = self.exchange({
"kind": "command",
"session_id": self.server.session_id,
"request_id": "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
})
self.assertEqual(response["error"], "completion-receipt-capacity-exceeded")
self.assertEqual(response["execution_state"], "not_started")
self.assertEqual(self.dispatcher.commands, [])
def test_status_probe_recovers_only_after_timed_out_ui_operation_finishes(self):
timed_out, _ = self.exchange({"kind": "command", "session_id": self.server.session_id})
self.assertEqual(timed_out["error"], "ui-thread-request-timeout")
self.assertTrue(self.server.poisoned)
self.assertTrue(self.dispatcher.command_started.wait(1))
result = {}
status_thread = threading.Thread(target=lambda: result.setdefault(
"response", self.exchange({"kind": "status", "session_id": self.server.session_id})[0]
))
status_thread.start()
self.assertTrue(self.dispatcher.status_queued.wait(1))
self.dispatcher.finish_command.set()
status_thread.join(timeout=2)
self.assertFalse(status_thread.is_alive())
response = result["response"]
self.assertTrue(response["ok"])
self.assertEqual(response["session_id"], self.server.session_id)
self.assertEqual(self.dispatcher.commands, ["command", "status"])
def test_escape_expansion_uses_a_signed_truthful_truncation_fallback(self):
sender, receiver = socket.socketpair()
try:
self.server._send_authenticated(sender, {
"ok": True,
"output": '"' * 6_000_000,
"execution_state": "complete",
"current_file": "/tmp/sample.bin",
"document_generation": 4,
"identity_status": "partial",
}, "a" * 64, "b" * 64)
frame_bytes = receiver.recv(bridge.MAX_FRAME_BYTES + 1)
self.assertLessEqual(len(frame_bytes), bridge.MAX_FRAME_BYTES)
frame = json.loads(frame_bytes)
response = frame["response"]
expected = hmac.new(
self.server.token.encode(),
f"rea-cutter-response-v2:{self.server.session_id}:{'a' * 64}:{'b' * 64}:{response}".encode(),
hashlib.sha256,
).hexdigest()
self.assertTrue(hmac.compare_digest(frame["proof"], expected))
value = json.loads(response)
self.assertEqual(value["ok"], True)
self.assertEqual(value["execution_state"], "complete")
self.assertTrue(value["output_truncated"])
self.assertIsNone(value["output"])
finally:
sender.close()
receiver.close()
if __name__ == "__main__":
if sys.argv[1:] == ["--serve"]:
run_serve_mode()
else:
unittest.main()
+1 -1
View File
@@ -240,7 +240,7 @@ Load command 16
cmd LC_LOAD_DYLIB
cmdsize 56
name @rpath/libdelay.dylib (offset 28)
options delay-init
options delay-init
current version 0.0.0
compatibility version 1.0.0
Load command 17
+7
View File
@@ -32,6 +32,13 @@ switch (mode) {
process.exitCode = 23;
break;
}
case "invalid-utf8":
await write(process.stdout, Buffer.from([0x61, 0xff, 0x62]));
await write(process.stderr, Buffer.from([0x63, 0xfe, 0x64]));
break;
case "valid-multibyte":
await write(process.stdout, Buffer.from([0xe2, 0x82, 0xac]));
break;
case "exit":
process.exitCode = Number(value);
break;
+8 -1
View File
@@ -8,7 +8,14 @@ const fixturePath = fileURLToPath(
/** Spawn one deterministic process-lifecycle fixture with piped diagnostics. */
export const spawnProviderProcessFixture = (
mode: "burst" | "detached-child" | "exit" | "graceful" | "stubborn",
mode:
| "burst"
| "detached-child"
| "exit"
| "graceful"
| "invalid-utf8"
| "valid-multibyte"
| "stubborn",
value?: number,
): ChildProcess =>
spawn(
+5 -1
View File
@@ -26,9 +26,13 @@ it.each(["start_adb_app", "start_adb_activity"] as const)(
"Starting: Intent { act=android.intent.action.MAIN cmp=com.example/.Main }\n";
let stdout = `${starting}Status: ok\nActivity: com.example/.Main\nWaitTime: 315\nComplete\n`;
let stderr = "";
const version =
"Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\n";
vi.mocked(execFileOutput).mockResolvedValue({
stdout: "Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\n",
stdout: version,
stderr: "",
stdoutBytes: Buffer.byteLength(version),
stderrBytes: 0,
});
const calls: string[][] = [];
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
@@ -0,0 +1,204 @@
import { rm } from "node:fs/promises";
import { expect, it, vi } from "vitest";
import { OwnedCommandFailure } from "../../src/process/OwnedCommand.js";
import { TestReverseEngineeringService } from "./reverseEngineeringService.js";
import {
createArtifact,
providerSnapshot,
} from "./reverseEngineeringCompositionFixtures.js";
const registerOwnedRizinCommandOutcomeTests = (options: {
readonly sweepTokenOwnedProcesses: boolean;
}): void => {
it.each([
["normal exit", providerSnapshot(), "complete", 0, false],
[
"non-zero exit",
providerSnapshot({ exitCode: 7, diagnosticTruncated: true }),
"complete",
7,
true,
],
[
"signal termination",
providerSnapshot({
exitCode: null,
signal: "SIGSEGV",
diagnosticTruncated: true,
}),
"unknown",
null,
true,
],
[
"signal termination with a numeric exit snapshot",
providerSnapshot({ exitCode: 7, signal: "SIGSEGV" }),
"unknown",
null,
false,
],
[
"signal termination without truncation",
providerSnapshot({ exitCode: null, signal: "SIGTERM" }),
"unknown",
null,
false,
],
[
"unknown exit status",
providerSnapshot({ exitCode: null }),
"unknown",
null,
false,
],
] as const)(
"maps an owned command %s into provider Evidence",
async (_name, snapshot, completion, exitCode, outputTruncated) => {
const { directory, path } = await createArtifact();
const runOwned = vi.fn(async () => snapshot);
const service = new TestReverseEngineeringService({
runOwned,
environment: { REA_RIZIN_COMMAND: "rizin-test" },
});
try {
const result = await service.executeRizinCommand({
path,
command: "iI",
});
expect(runOwned).toHaveBeenCalledOnce();
expect(runOwned).toHaveBeenCalledWith(
expect.objectContaining({
command: "rizin-test",
arguments: expect.arrayContaining(["-q", "-c", "iI"]),
expectedCommand: null,
env: expect.objectContaining({ REA_RIZIN_COMMAND: "rizin-test" }),
hostEnvironment: {},
...(options.sweepTokenOwnedProcesses
? { sweepTokenOwnedProcesses: true }
: {}),
}),
{
timeoutMs: 120_000,
diagnosticBytes: 16 * 1024 * 1024,
acceptNonZeroExit: true,
},
{ signal: expect.any(AbortSignal) },
);
expect(result).toMatchObject({
ok: true,
value: {
raw_result: {
stdout: "captured owned output",
completion_status: completion,
exit_code: exitCode,
output_truncated: outputTruncated,
},
},
});
if (!result.ok) throw new Error("Expected provider Evidence");
expect(result.value.parameters).toMatchObject({
command: "iI",
provider_executable: "rizin-test",
command_arguments: expect.arrayContaining(["-q", "-c", "iI"]),
});
expect(result.value.locations).toContainEqual({
kind: "artifact-path",
path,
});
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
};
const registerOwnedRizinCommandFailureTests = (): void => {
it.each([
["cancelled", "AnalysisCancelledError", "ABORT_ERR"],
["timeout", "AnalysisTimeoutError", "ETIMEDOUT"],
["output-limit", "evidence", "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"],
["process", "evidence", 7],
] as const)(
"maps an owned command %s failure while retaining its snapshot",
async (reason, expected, mappedCode) => {
const { directory, path } = await createArtifact();
const snapshot = providerSnapshot({
...(reason === "process" ? { exitCode: 7 } : {}),
...(reason === "output-limit"
? {}
: reason === "cancelled"
? {}
: { diagnosticTruncated: true }),
});
const service = new TestReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure(
reason,
"owned command failed",
snapshot,
reason === "timeout" ? "cleanup pending" : null,
undefined,
reason === "timeout" ? ["run-id", "pid:7"] : [],
);
},
});
try {
const result = await service.executeRizinCommand({
path,
command: "iI",
});
if (expected === "evidence") {
expect(result).toMatchObject({
ok: true,
value: {
raw_result: {
stdout: "captured owned output",
exit_code: mappedCode === 7 ? 7 : null,
completion_status:
reason === "output-limit" ? "unknown" : "complete",
output_truncated: true,
},
},
});
} else {
expect(result).toMatchObject({
ok: false,
error: {
_tag: expected,
partialObservation: {
raw_result: {
stdout: "captured owned output",
exit_code: null,
completion_status: "unknown",
output_truncated: reason !== "cancelled",
},
},
...(reason === "timeout"
? {
cleanup: {
reason: "cleanup pending",
resources: ["run-id", "pid:7"],
},
}
: {}),
},
});
if (result.ok) throw new Error("Expected a tagged command failure");
}
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
};
export const registerOwnedRizinCommandEvidenceTests = (options: {
readonly sweepTokenOwnedProcesses: boolean;
}): void => {
registerOwnedRizinCommandOutcomeTests(options);
registerOwnedRizinCommandFailureTests();
};
@@ -0,0 +1,70 @@
import { readFile, rm } from "node:fs/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, onTestFinished } from "vitest";
import { z } from "zod";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { createServer } from "../../src/server/createServer.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
export const waitForStartedFile = async (path: string): Promise<void> => {
await expect
.poll(() => readFile(path, "utf8").catch(() => ""))
.toBe("started");
};
export const validateDebuggerStatusResponse = async (
client: Client,
name: "gdb_session_status" | "rizin_debug_session_status",
sessionId: string,
): Promise<Record<string, unknown>> => {
const listed = (await client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (listed?.outputSchema === undefined)
throw new Error(`Missing advertised ${name} output schema`);
const response = await client.callTool({
name,
arguments: { session_id: sessionId },
});
expect(response.isError).not.toBe(true);
const parsed = toolContract(name).outputSchema.parse(
response.structuredContent,
);
expect(
new Ajv2020({ strict: false, validateFormats: false }).validate(
z.record(z.string(), z.unknown()).parse(listed.outputSchema),
parsed,
),
).toBe(true);
return z.record(z.string(), z.unknown()).parse(parsed);
};
export const createProviderEnvironmentMcpHarness = async (options: {
readonly directory: string;
readonly clientName: string;
readonly serverOptions: NonNullable<Parameters<typeof createServer>[1]>;
}) => {
const session = createTestBinarySession(() => {
throw new Error("No binary analysis provider should start");
});
const server = createServer(
{ kind: "session", session },
options.serverOptions,
);
const client = new Client({ name: options.clientName, version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
await rm(options.directory, { recursive: true, force: true });
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client };
};
@@ -0,0 +1,800 @@
import { rm, truncate, writeFile } from "node:fs/promises";
import { expect, it, vi } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "./reverseEngineeringService.js";
import {
createArtifact,
providerSnapshot,
} from "./reverseEngineeringCompositionFixtures.js";
import { objdumpCommand } from "../../src/objdump/ObjdumpCommand.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../../src/process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../src/process/ProviderProcess.js";
const registerSharedReverseEngineeringEdgeCasesPart1 = (): void => {
it("uses the local-only DWARF option when debug links are disabled", () => {
expect(
objdumpCommand({
path: "./sample.bin",
operation: "dwarf",
follow_debug_links: false,
}),
).toEqual(["-W", "-WN", expect.stringMatching(/sample\.bin$/u)]);
});
it("does not follow DWARF debug links by default", async () => {
const { directory, path } = await createArtifact();
const calls: string[][] = [];
const service = new ReverseEngineeringService({
run: async (_command, args) => {
calls.push([...args]);
return { stdout: "DWARF output", stderr: "" };
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "dwarf",
});
expect(result.ok).toBe(true);
expect(calls[0]).toEqual(["-W", "-WN", path]);
if (result.ok)
expect(result.value.parameters.follow_debug_links).toBe(false);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("marks opted-in external DWARF debug files as unbound Evidence sources", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "DWARF output", stderr: "" }),
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "dwarf",
follow_debug_links: true,
});
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.limitations).toContain(
"DWARF output may include local debug-link files whose identities are not bound to Evidence.",
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects malformed objdump requests before touching the provider", async () => {
let invoked = false;
const service = new ReverseEngineeringService({
run: async () => {
invoked = true;
return { stdout: "", stderr: "" };
},
});
const result = await service.inspectWithObjdump({ path: "/tmp/a" });
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", operation: "inspect_with_objdump" },
});
expect(invoked).toBe(false);
});
it("returns cancellation that arrived before the artifact digest starts", async () => {
const controller = new AbortController();
controller.abort();
const service = new ReverseEngineeringService();
const result = await service.inspectWithObjdump(
{ path: "/tmp/a", operation: "file_headers" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each([
["EACCES", "AnalysisAccessDeniedError"],
["EPERM", "AnalysisAccessDeniedError"],
["ETIMEDOUT", "AnalysisTimeoutError"],
["EINVAL", "AnalysisInputError"],
])(
"maps artifact digest failure %s to its tagged analysis error",
async (code, tag) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
digest: async () => {
throw Object.assign(new Error("digest failure"), { code });
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
};
const registerSharedReverseEngineeringEdgeCasesPart2 = (): void => {
it("retains and retries an owned cleanup after an output-limit failure", async () => {
const { directory, path } = await createArtifact();
const stop = vi
.fn()
.mockResolvedValueOnce({ status: "incomplete", reason: "still running" })
.mockResolvedValueOnce({ status: "incomplete", reason: "still running" })
.mockResolvedValueOnce({ status: "incomplete", reason: "still running" })
.mockResolvedValueOnce({ status: "verified-cleanup" });
await stop(); // The owned-command runner's first cleanup attempt failed.
const cleanupOwner = { stop } as unknown as ProviderProcessSupervisor;
const runOwned = vi.fn<typeof runOwnedCommand>(async () => {
throw new OwnedCommandFailure(
"output-limit",
"output limit",
providerSnapshot({ diagnosticTruncated: true }),
"still running",
undefined,
["run-id", "pid:42"],
cleanupOwner,
);
});
const service = new ReverseEngineeringService({
runOwned,
});
try {
const result = await service.executeRizinCommand({
path,
command: "wx 00",
});
expect(result).toMatchObject({
ok: false,
error: {
cleanupIncomplete: true,
cleanup: { reason: "still running", resources: ["run-id", "pid:42"] },
partialObservation: {
raw_result: {
stdout: "captured owned output",
output_truncated: true,
completion_status: "unknown",
},
},
},
});
expect(stop).toHaveBeenCalledTimes(1);
const blocked = await service.executeRizinCommand({
path,
command: "iI",
});
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(stop).toHaveBeenCalledTimes(2);
expect(runOwned).toHaveBeenCalledTimes(1);
expect(blocked).toMatchObject({
ok: false,
error: {
message: expect.stringContaining(
"A previous provider process still requires cleanup.",
),
},
});
await expect(service.close()).rejects.toMatchObject({
cleanupIncomplete: true,
cleanup: { reason: "still running", resources: ["run-id", "pid:42"] },
});
expect(stop).toHaveBeenCalledTimes(3);
await service.close();
expect(stop).toHaveBeenCalledTimes(4);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("maps cancellation during the initial digest to a cancellation error", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const service = new ReverseEngineeringService({
digest: async () => {
controller.abort();
throw new Error("digest cancelled");
},
});
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
};
const registerSharedReverseEngineeringEdgeCasesPart3 = (): void => {
it("cancels an in-progress file digest through its abort listener", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
Object.defineProperty(controller.signal, "addEventListener", {
value: (
type: string,
listener: Parameters<EventTarget["addEventListener"]>[1],
options?: boolean | AddEventListenerOptions,
): void => {
EventTarget.prototype.addEventListener.call(
controller.signal,
type,
listener,
options,
);
if (type === "abort") {
controller.abort();
}
},
});
const service = new ReverseEngineeringService();
try {
const resultPromise = service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: controller.signal },
);
const result = await resultPromise;
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("maps the artifact digest deadline to a timeout error", async () => {
const { directory, path } = await createArtifact();
await truncate(path, 64 * 1024 * 1024);
const service = new ReverseEngineeringService();
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const resultPromise = service.inspectWithObjdump({
path,
operation: "file_headers",
});
await new Promise<void>((resolve) => setImmediate(resolve));
await vi.advanceTimersByTimeAsync(120_000);
const result = await resultPromise;
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisTimeoutError" },
});
} finally {
vi.useRealTimers();
await rm(directory, { recursive: true, force: true });
}
});
it.each([
["ETIMEDOUT", "AnalysisTimeoutError"],
["EACCES", "AnalysisAccessDeniedError"],
["EPERM", "AnalysisAccessDeniedError"],
["ABORT_ERR", "AnalysisCancelledError"],
["unknown", "AnalysisCapabilityUnavailableError"],
])(
"maps provider failure %s to its tagged analysis error",
async (code, tag) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
run: async () => {
if (code === "unknown") throw new Error("provider failure");
throw Object.assign(new Error("provider failure"), { code });
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: tag,
operation: "inspect_with_objdump",
cause: { message: "provider failure" },
...(code === "ETIMEDOUT" ? { timeoutMs: 120_000 } : {}),
...(code === "EACCES" || code === "EPERM"
? { path: "objdump", systemCode: code }
: {}),
...(code === "unknown"
? {
providerId: "objdump",
reason: "Unable to run configured command (unknown error)",
}
: {}),
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
};
const registerSharedReverseEngineeringEdgeCasesPart4 = (): void => {
it("records a changed artifact and unknown post-run digest separately", async () => {
const { directory, path } = await createArtifact();
const changed = new ReverseEngineeringService({
run: async () => {
await writeFile(path, "changed during provider execution");
return { stdout: "observed", stderr: "" };
},
});
const removed = new ReverseEngineeringService({
run: async () => {
await rm(path);
return { stdout: "observed", stderr: "" };
},
});
try {
const changedResult = await changed.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(changedResult).toMatchObject({
ok: true,
value: {
raw_result: { artifact_changed: true },
limitations: expect.arrayContaining([
expect.stringContaining("may have changed"),
]),
},
});
await writeFile(path, "restore for second digest");
const removedResult = await removed.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(removedResult).toMatchObject({
ok: true,
value: {
raw_result: { artifact_sha256_after: null, artifact_changed: null },
limitations: expect.arrayContaining([
expect.stringContaining("post-run artifact digest"),
]),
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.each(["EACCES", "EPERM"] as const)(
"retains captured output on a permission-denied provider result (%s)",
async (code) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("provider permission denied"), {
stdout: "partial provider output",
stderr: "permission diagnostic",
code,
signal: null,
killed: false,
});
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisAccessDeniedError",
capturedOutput: {
stdout: "partial provider output",
stderr: "permission diagnostic",
},
partialObservation: {
raw_result: { stdout: "partial provider output" },
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
};
const registerSharedReverseEngineeringEdgeCasesPart5 = (): void => {
it("cancels after captured output when a provider reports a non-numeric status", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
let digests = 0;
const service = new ReverseEngineeringService({
digest: async () => {
digests += 1;
if (digests === 2) controller.abort();
return digests === 1 ? "a".repeat(64) : "b".repeat(64);
},
run: async () => {
throw Object.assign(new Error("provider status unavailable"), {
stdout: "captured output",
stderr: "",
code: "provider-status-unknown",
signal: null,
killed: false,
});
},
});
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
partialObservation: {
raw_result: { exit_code: null, completion_status: "unknown" },
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("maps an unavailable Rizin command to the Rizin capability error", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("not found"), { code: "ENOENT" });
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "rizin",
operation: "execute_rizin_command",
reason: "Unable to run configured command (ENOENT)",
cause: { message: "not found" },
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("classifies a captured ENOENT as provider unavailability", async () => {
const { directory, path } = await createArtifact();
const cause = Object.assign(new Error("launch failed"), {
stdout: "",
stderr: "",
code: "ENOENT",
signal: null,
killed: false,
});
const service = new ReverseEngineeringService({
run: async () => {
throw cause;
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "objdump",
reason: "Unable to run configured command (ENOENT)",
cause: { message: "launch failed" },
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
};
const registerSharedReverseEngineeringEdgeCasesPart6 = (): void => {
it("waits for active provider cleanup during shutdown and rejects new work", async () => {
const { directory, path } = await createArtifact();
let signal: AbortSignal | undefined;
let announceStarted: (() => void) | undefined;
const started = new Promise<void>((resolve) => {
announceStarted = resolve;
});
let releaseProvider: (() => void) | undefined;
const providerGate = new Promise<void>((resolve) => {
releaseProvider = resolve;
});
const stop = vi
.fn()
.mockResolvedValueOnce({ status: "incomplete", reason: "still running" })
.mockResolvedValueOnce({ status: "verified-cleanup" });
const cleanupOwner = { stop } as unknown as ProviderProcessSupervisor;
const runOwned = vi.fn<typeof runOwnedCommand>(
async (_spawn, _limits, options) => {
signal = options?.signal;
announceStarted?.();
await providerGate;
throw new OwnedCommandFailure(
"cancelled",
"Command cancelled during shutdown.",
providerSnapshot({ exitCode: null }),
"still running",
undefined,
["run-id", "pid:42"],
cleanupOwner,
);
},
);
const service = new ReverseEngineeringService({ runOwned });
try {
const operation = service.executeRizinCommand({ path, command: "iI" });
await started;
let closeSettled = false;
const closing = service.close().finally(() => {
closeSettled = true;
});
expect(signal?.aborted).toBe(true);
await Promise.resolve();
expect(closeSettled).toBe(false);
releaseProvider?.();
await expect(operation).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cleanupIncomplete: true },
});
await expect(closing).rejects.toMatchObject({
cleanupIncomplete: true,
cleanup: { reason: "still running" },
});
expect(stop).toHaveBeenCalledTimes(1);
await expect(
service.executeRizinCommand({ path, command: "iI" }),
).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
expect(runOwned).toHaveBeenCalledTimes(1);
await service.close();
expect(stop).toHaveBeenCalledTimes(2);
} finally {
releaseProvider?.();
await rm(directory, { recursive: true, force: true });
}
});
};
const registerSharedReverseEngineeringEdgeCasesPart7 = (): void => {
it("maps an uncaptured owned launcher error to provider unavailability", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => {
throw Object.assign(new Error("missing provider"), { code: "ENOENT" });
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "rizin",
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
};
const registerSharedReverseEngineeringEdgeCasesPart8 = (): void => {
it("forwards a caller abort signal to the owned command supervisor", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const runOwned = vi.fn<typeof runOwnedCommand>(async () =>
providerSnapshot(),
);
const service = new ReverseEngineeringService({ runOwned });
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
expect(result.ok).toBe(true);
expect(runOwned.mock.calls[0]?.[2]).toMatchObject({
signal: expect.any(AbortSignal),
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("does not classify a completed provider call as cancelled for a live signal", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "completed output", stderr: "" }),
});
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: true,
value: {
raw_result: {
stdout: "completed output",
completion_status: "complete",
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("classifies an owned launcher failure without a process snapshot", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure("process", "no process snapshot");
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "rizin",
partialObservation: undefined,
reason: "Unable to run configured command (ERR_PROVIDER_LAUNCH)",
cause: {
message:
"Owned provider command did not produce a complete result.",
stdout: "",
stderr: "",
cause: { reason: "process", message: "no process snapshot" },
},
capturedOutput: undefined,
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("retains an owned process failure snapshot with an unknown exit code", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure(
"process",
"process ended before reporting an exit code",
providerSnapshot({ exitCode: null }),
);
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: true,
value: {
raw_result: {
stdout: "captured owned output",
exit_code: null,
completion_status: "unknown",
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
};
const registerSharedReverseEngineeringEdgeCasesPart9 = (): void => {
it("fails with partial unknown Evidence when owned output collection fails after exit 0", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => {
throw Object.assign(
new OwnedCommandFailure(
"process",
"stdout stream failed: fixture read failure",
providerSnapshot({ exitCode: 0 }),
),
{ collectionFailure: true },
);
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
partialObservation: {
raw_result: {
stdout: "captured owned output",
stderr: "diagnostic",
exit_code: null,
completion_status: "unknown",
},
},
capturedOutput: { exit_code: null },
},
});
if (result.ok) throw new Error("Expected collection failure");
expect(result.error.cause).toMatchObject({
collectionFailure: true,
cause: { reason: "process" },
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
};
export const registerSharedReverseEngineeringEdgeCaseTests = (): void => {
registerSharedReverseEngineeringEdgeCasesPart1();
registerSharedReverseEngineeringEdgeCasesPart2();
registerSharedReverseEngineeringEdgeCasesPart3();
registerSharedReverseEngineeringEdgeCasesPart4();
registerSharedReverseEngineeringEdgeCasesPart5();
registerSharedReverseEngineeringEdgeCasesPart6();
registerSharedReverseEngineeringEdgeCasesPart7();
registerSharedReverseEngineeringEdgeCasesPart8();
registerSharedReverseEngineeringEdgeCasesPart9();
};
@@ -0,0 +1,24 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import type { ProviderProcessSnapshot } from "../../src/process/ProviderProcess.js";
import { join } from "node:path";
export const createArtifact = async (): Promise<{
directory: string;
path: string;
}> => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-edge-"));
const path = join(directory, "sample.bin");
await writeFile(path, "initial artifact");
return { directory, path };
};
export const providerSnapshot = (
overrides: Partial<ProviderProcessSnapshot> = {},
): ProviderProcessSnapshot => ({
stdout: { text: "captured owned output", bytes: 21, observedBytes: 21 },
stderr: { text: "diagnostic", bytes: 10, observedBytes: 10 },
exitCode: 0,
signal: null,
...overrides,
});
@@ -0,0 +1,33 @@
import type { McpServer } from "@modelcontextprotocol/server";
type RegisteredHandler = (input: unknown, context: unknown) => Promise<unknown>;
export const invokeWithLiveSignal = (
handler: RegisteredHandler,
input: unknown,
): Promise<unknown> =>
handler(input, { mcpReq: { signal: new AbortController().signal } });
export const createReverseEngineeringMcpHarness = (): {
server: McpServer;
handler: (name: string) => RegisteredHandler;
} => {
const registrations = new Map<string, RegisteredHandler>();
const server = {
registerTool: (
name: string,
_options: unknown,
handler: RegisteredHandler,
) => registrations.set(name, handler),
} as unknown as McpServer;
return {
server,
handler: (name) => {
const registered = registrations.get(name);
if (registered === undefined)
throw new Error(`${name} MCP handler was not registered`);
return registered;
},
};
};
@@ -0,0 +1,21 @@
import { createReverseEngineeringCommandPort } from "../../src/composition/reverseEngineering.js";
import {
ReverseEngineeringService,
type ReverseEngineeringServiceOptions,
} from "../../src/application/reverse/ReverseEngineeringService.js";
type TestServiceOptions = Omit<ReverseEngineeringServiceOptions, "commands"> &
Partial<Pick<ReverseEngineeringServiceOptions, "commands">>;
/** Compose the production provider profiles while allowing service-boundary fakes. */
export class TestReverseEngineeringService extends ReverseEngineeringService {
constructor(options: TestServiceOptions = {}) {
const environment = options.environment ?? process.env;
super({
...options,
environment,
commands:
options.commands ?? createReverseEngineeringCommandPort(environment),
});
}
}