refactor(test): keep coverage at behavioral boundaries (#474)
* refactor(test): keep coverage at behavioral boundaries * fix(ci): restore package workflow temp-root classification
This commit is contained in:
@@ -1,56 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
|
||||
describe("CdpCaptureCompleteness", () => {
|
||||
it("reports attach-window limitations without claiming a complete history", () => {
|
||||
const capture = new CdpCaptureCompleteness([
|
||||
"network_requests",
|
||||
"console_events",
|
||||
]);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
conditions: ["attach_limited"],
|
||||
attach_limited_sections: ["console_events", "network_requests"],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("aggregates sparse exclusions and applies explicit status precedence", () => {
|
||||
const capture = new CdpCaptureCompleteness(["network_requests"]);
|
||||
capture.exclude("scripts", "disallowed_origin");
|
||||
capture.exclude("scripts", "disallowed_origin", 2);
|
||||
capture.exclude("storage_keys", "not_approved", null);
|
||||
capture.drop("console_events", 4);
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "truncated",
|
||||
conditions: ["attach_limited", "policy_filtered", "truncated"],
|
||||
policy_filtered_sections: ["scripts", "storage_keys"],
|
||||
truncated_sections: ["console_events"],
|
||||
excluded: [
|
||||
{ section: "scripts", reason: "disallowed_origin", count: 3 },
|
||||
{ section: "storage_keys", reason: "not_approved", count: null },
|
||||
],
|
||||
dropped_events: { console_events: 4, total: 4 },
|
||||
});
|
||||
});
|
||||
|
||||
it("restores initial attach limitations when reused for a new capture", () => {
|
||||
const capture = new CdpCaptureCompleteness(["websocket_frames"]);
|
||||
capture.drop("scripts");
|
||||
capture.exclude("resources", "provider_unavailable", null);
|
||||
|
||||
capture.reset();
|
||||
|
||||
expect(capture.snapshot()).toMatchObject({
|
||||
status: "attach_limited",
|
||||
attach_limited_sections: ["websocket_frames"],
|
||||
unavailable_sections: [],
|
||||
excluded: [],
|
||||
dropped_events: { total: 0 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,146 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
captureAccessibility,
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
} from "../../../src/browser/CdpCaptureDocuments.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
describe("CDP document capture", () => {
|
||||
it("walks deeply nested frame trees iteratively and retains a bounded prefix", () => {
|
||||
let frameTree: Record<string, unknown> = {
|
||||
frame: { id: "frame-0", url: `${origin}/0` },
|
||||
resources: [{ url: `${origin}/0.js`, type: "Script" }],
|
||||
};
|
||||
for (let index = 1; index < 2_000; index += 1) {
|
||||
frameTree = {
|
||||
frame: {
|
||||
id: `frame-${String(index)}`,
|
||||
url: `${origin}/${String(index)}`,
|
||||
},
|
||||
resources: [{ url: `${origin}/${String(index)}.js`, type: "Script" }],
|
||||
childFrames: [frameTree],
|
||||
};
|
||||
}
|
||||
const result = { frameTree };
|
||||
const frames = captureFrames(result, new Set([origin]), 3);
|
||||
const resources = captureResources(result, new Set([origin]), 2);
|
||||
expect(frames).toMatchObject({ total: 2_000 });
|
||||
expect(frames.items).toHaveLength(3);
|
||||
expect(resources).toMatchObject({ total: 2_000 });
|
||||
expect(resources.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rebases parent indexes when allowed DOM documents are combined", () => {
|
||||
const input = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: [origin],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const snapshot = {
|
||||
strings: [`${origin}/main`, `${origin}/frame`, "#document", "DIV", ""],
|
||||
documents: [
|
||||
{
|
||||
documentURL: 0,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
{
|
||||
documentURL: 1,
|
||||
nodes: {
|
||||
nodeType: [9, 1],
|
||||
nodeName: [2, 3],
|
||||
nodeValue: [4, 4],
|
||||
parentIndex: [-1, 0],
|
||||
attributes: [[], []],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const capture = captureDom(snapshot, new Set([origin]), input);
|
||||
expect(capture.nodes.map((node) => node.parent_index)).toEqual([
|
||||
-1, 0, -1, 2,
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds approved accessibility text by UTF-8 bytes without splitting characters", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
role: { value: "button" },
|
||||
name: { value: "😀a" },
|
||||
description: { value: "éé" },
|
||||
childIds: ["missing-child"],
|
||||
properties: [
|
||||
{ name: "disabled", value: { value: true } },
|
||||
{ name: "valuetext", value: { value: "private value" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: true,
|
||||
maximumFieldBytes: 4,
|
||||
maximumTotalBytes: 7,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({
|
||||
name: "😀",
|
||||
description: "é",
|
||||
states: [{ name: "disabled", value: true }],
|
||||
});
|
||||
expect(capture.treeIncomplete).toBe(true);
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
excluded_fields: 0,
|
||||
truncated_fields: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("counts accessibility fields omitted without text approval", () => {
|
||||
const capture = captureAccessibility(
|
||||
[
|
||||
{
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "node-1",
|
||||
name: { value: "private name" },
|
||||
description: { value: "private description" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
10,
|
||||
{
|
||||
includeText: false,
|
||||
maximumFieldBytes: 1_024,
|
||||
maximumTotalBytes: 64 * 1_024,
|
||||
},
|
||||
);
|
||||
|
||||
expect(capture.nodes[0]).toMatchObject({ name: null, description: null });
|
||||
expect(capture.textCapture).toEqual({
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
excluded_fields: 2,
|
||||
truncated_fields: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,157 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
authEventsByProtocol,
|
||||
authFlowDuration,
|
||||
customProtocolCaptureSchema,
|
||||
correlateProcessIdentity,
|
||||
failedAuthEvents,
|
||||
framesByTransport,
|
||||
looksLikeCredentialFrame,
|
||||
successfulAuthEvents,
|
||||
type AuthFlowEvent,
|
||||
type FrameDirection,
|
||||
type AuthStage,
|
||||
type TokenLifecycleEvent,
|
||||
type CustomProtocolCapture,
|
||||
type ProtocolFrame,
|
||||
} from "../../../src/domain/customProtocolCapture.js";
|
||||
|
||||
const sampleFrames: ProtocolFrame[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
transport: "tcp",
|
||||
direction: "sent",
|
||||
source_pid: 100,
|
||||
dest_pid: 200,
|
||||
source_endpoint: "127.0.0.1:8080",
|
||||
dest_endpoint: "127.0.0.1:9090",
|
||||
raw_data: "hello",
|
||||
decoded_content: "hello",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 200,
|
||||
transport: "udp",
|
||||
direction: "received",
|
||||
source_pid: 200,
|
||||
dest_pid: 100,
|
||||
source_endpoint: "127.0.0.1:9090",
|
||||
dest_endpoint: "127.0.0.1:8080",
|
||||
raw_data: "world",
|
||||
decoded_content: "world",
|
||||
size: 5,
|
||||
truncated: false,
|
||||
},
|
||||
];
|
||||
|
||||
const sampleAuthEvents: AuthFlowEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 100,
|
||||
stage: "init",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: false,
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 500,
|
||||
stage: "success",
|
||||
protocol: "OAuth2",
|
||||
token_type: "Bearer",
|
||||
token_lifecycle: "issued",
|
||||
correlation_id: "abc-123",
|
||||
credentials_redacted: true,
|
||||
succeeded: true,
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("custom protocol capture", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
transport: "tcp" as const,
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = customProtocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("correlates process identity", () => {
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 100)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 200)).toBe(true);
|
||||
expect(correlateProcessIdentity(sampleFrames[0]!, 999)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters frames by transport", () => {
|
||||
const tcpFrames = framesByTransport(sampleFrames, "tcp");
|
||||
expect(tcpFrames).toHaveLength(1);
|
||||
const udpFrames = framesByTransport(sampleFrames, "udp");
|
||||
expect(udpFrames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("detects credential-like frames", () => {
|
||||
const credFrame: ProtocolFrame = {
|
||||
...sampleFrames[0]!,
|
||||
decoded_content: { password: "secret" },
|
||||
};
|
||||
expect(looksLikeCredentialFrame(credFrame)).toBe(true);
|
||||
expect(looksLikeCredentialFrame(sampleFrames[0]!)).toBe(false);
|
||||
});
|
||||
|
||||
it("filters auth events by protocol", () => {
|
||||
const oauthEvents = authEventsByProtocol(sampleAuthEvents, "OAuth2");
|
||||
expect(oauthEvents).toHaveLength(2);
|
||||
const otherEvents = authEventsByProtocol(sampleAuthEvents, "SAML");
|
||||
expect(otherEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("gets successful auth events", () => {
|
||||
const success = successfulAuthEvents(sampleAuthEvents);
|
||||
expect(success).toHaveLength(1);
|
||||
expect(success[0]!.succeeded).toBe(true);
|
||||
});
|
||||
|
||||
it("gets failed auth events", () => {
|
||||
const failed = failedAuthEvents(sampleAuthEvents);
|
||||
expect(failed).toHaveLength(1);
|
||||
expect(failed[0]!.succeeded).toBe(false);
|
||||
});
|
||||
|
||||
it("computes auth flow duration", () => {
|
||||
const duration = authFlowDuration(sampleAuthEvents);
|
||||
expect(duration).toBe(400);
|
||||
});
|
||||
|
||||
it("returns null for empty auth events", () => {
|
||||
expect(authFlowDuration([])).toBeNull();
|
||||
});
|
||||
|
||||
it("uses all exported types", () => {
|
||||
const dir: FrameDirection = "sent";
|
||||
expect(dir).toBe("sent");
|
||||
const stage: AuthStage = "init";
|
||||
expect(stage).toBe("init");
|
||||
const event: TokenLifecycleEvent = "issued";
|
||||
expect(event).toBe("issued");
|
||||
const capture: CustomProtocolCapture = {
|
||||
transport: "tcp",
|
||||
frames: sampleFrames,
|
||||
auth_events: sampleAuthEvents,
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
expect(capture.transport).toBe("tcp");
|
||||
});
|
||||
});
|
||||
@@ -1,159 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
electronActiveObservationInputSchema,
|
||||
electronActiveObservationResultSchema,
|
||||
} from "../../../src/domain/electronActiveObservation.js";
|
||||
import { runElectronActions } from "../../../src/browser/PlaywrightElectronActiveActions.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
|
||||
|
||||
it("parses bounded window, renderer, and deep-link actions for agents", () => {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{ step_id: "first-window", kind: "click", selector: "#run" },
|
||||
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
|
||||
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
|
||||
{
|
||||
step_id: "deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
|
||||
expect(input.actions).toEqual([
|
||||
{
|
||||
step_id: "first-window",
|
||||
kind: "click",
|
||||
selector: "#run",
|
||||
window_index: 0,
|
||||
},
|
||||
{ step_id: "second-window", kind: "renderer-reload", window_index: 1 },
|
||||
{ step_id: "restart", kind: "renderer-crash", window_index: 1 },
|
||||
{
|
||||
step_id: "deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects non-absolute deep-link values", () => {
|
||||
const result = electronActiveObservationInputSchema.safeParse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{
|
||||
step_id: "bad-link",
|
||||
kind: "deep-link",
|
||||
delivery: "open-url",
|
||||
url: "not a URL",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts action inputs from Playwright failures", async () => {
|
||||
const selector = "#secret-selector";
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [{ step_id: "click-step", kind: "click", selector }],
|
||||
approved: true,
|
||||
});
|
||||
const page = {
|
||||
locator: () => ({
|
||||
click: async () => {
|
||||
throw new Error(`locator ${selector} failed with token=raw-secret`);
|
||||
},
|
||||
}),
|
||||
};
|
||||
const application = {
|
||||
windows: () => [page],
|
||||
};
|
||||
|
||||
const result = await runElectronActions(
|
||||
application as never,
|
||||
input,
|
||||
{},
|
||||
Date.now() + 1_000,
|
||||
);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
status: "failed",
|
||||
error: "locator <redacted-input> failed with token=[REDACTED]",
|
||||
});
|
||||
expect(result[0]?.error).not.toContain(selector);
|
||||
expect(result[0]?.error).not.toContain("raw-secret");
|
||||
});
|
||||
|
||||
it("runs an untargeted deep-link without requiring a BrowserWindow", async () => {
|
||||
const input = electronActiveObservationInputSchema.parse({
|
||||
schema_version: 1,
|
||||
executable_path: "/opt/electron",
|
||||
application_path: "/opt/app/main.js",
|
||||
application_root: "/opt/app",
|
||||
actions: [
|
||||
{
|
||||
step_id: "open-deep-link",
|
||||
kind: "deep-link",
|
||||
delivery: "second-instance",
|
||||
url: "rea-fixture://open/item",
|
||||
},
|
||||
],
|
||||
approved: true,
|
||||
});
|
||||
const application = {
|
||||
windows: () => [],
|
||||
evaluate: async () => true,
|
||||
};
|
||||
|
||||
const result = await runElectronActions(
|
||||
application as never,
|
||||
input,
|
||||
{},
|
||||
Date.now() + 1_000,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject([
|
||||
{
|
||||
step_id: "open-deep-link",
|
||||
status: "completed",
|
||||
error: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects action outcomes that disagree with their error state", () => {
|
||||
const result = createElectronActiveObservationFixtureResult("/opt/app");
|
||||
const action = result.actions[0];
|
||||
expect(action).toBeDefined();
|
||||
if (action === undefined) return;
|
||||
|
||||
expect(
|
||||
electronActiveObservationResultSchema.safeParse({
|
||||
...result,
|
||||
actions: [{ ...action, error: "unexpected failure" }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
electronActiveObservationResultSchema.safeParse({
|
||||
...result,
|
||||
actions: [{ ...action, status: "failed", error: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -1,388 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BrowserScenarioSessionPort } from "../../../src/browser/BrowserScenarioSessionPort.js";
|
||||
import { PlaywrightBrowserScenarioProvider } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
import { BrowserScenarioCaptureBudget } from "../../../src/browser/PlaywrightScenarioArtifacts.js";
|
||||
import { sanitizeBrowserUrl } from "../../../src/domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioSchema,
|
||||
type BrowserScenario,
|
||||
type BrowserScenarioAction,
|
||||
} from "../../../src/domain/browserScenario.js";
|
||||
import {
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../../../src/domain/browserScenarioCapture.js";
|
||||
|
||||
const scenario = (
|
||||
options: {
|
||||
readonly mode?: "launch" | "connect";
|
||||
readonly captures?: readonly (
|
||||
| "screenshot"
|
||||
| "dom"
|
||||
| "accessibility"
|
||||
| "url"
|
||||
| "history"
|
||||
| "storage"
|
||||
)[];
|
||||
readonly events?: readonly (
|
||||
| "console"
|
||||
| "page-errors"
|
||||
| "network"
|
||||
| "websockets"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "downloads"
|
||||
)[];
|
||||
readonly actions?: number;
|
||||
} = {},
|
||||
): BrowserScenario =>
|
||||
browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser:
|
||||
options.mode === "connect"
|
||||
? {
|
||||
mode: "connect",
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
target_id: "page-1",
|
||||
ownership: "external",
|
||||
cleanup: "disconnect-only",
|
||||
}
|
||||
: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: Array.from({ length: options.actions ?? 1 }, (_, index) => ({
|
||||
step_id: `wait_${index}`,
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
})),
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: options.captures ?? ["url"],
|
||||
at_end: [],
|
||||
events: options.events ?? [],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 100,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 2,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 16_384,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
|
||||
const artifactState = (
|
||||
kind: SnapshotKind,
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
incomplete: boolean,
|
||||
) => {
|
||||
if (!requested.has(kind)) return { state: "not_requested" as const };
|
||||
if (kind === "url")
|
||||
return {
|
||||
state: "captured" as const,
|
||||
value: sanitizeBrowserUrl("https://app.example.test/current"),
|
||||
};
|
||||
if (incomplete && kind === "screenshot")
|
||||
return {
|
||||
state: "truncated" as const,
|
||||
observed: 2_048,
|
||||
retained: 0,
|
||||
reason: "fixture limit",
|
||||
};
|
||||
return { state: "missing" as const, reason: "fixture unavailable" };
|
||||
};
|
||||
|
||||
class FakeSession implements BrowserScenarioSessionPort {
|
||||
readonly product = "Fake Chromium";
|
||||
readonly version = "1";
|
||||
readonly initialUrl = "about:blank";
|
||||
readonly processOwnership: "provider-owned" | "external";
|
||||
closeCalls = 0;
|
||||
performCalls = 0;
|
||||
captureCalls = 0;
|
||||
eventTruncations: (
|
||||
| "events"
|
||||
| "frames"
|
||||
| "workers"
|
||||
| "popups"
|
||||
| "websockets"
|
||||
)[] = [];
|
||||
onPerform: (() => void) | undefined;
|
||||
private step = 0;
|
||||
|
||||
constructor(
|
||||
readonly mode: "launch" | "connect",
|
||||
private readonly incomplete = false,
|
||||
private readonly failAction = false,
|
||||
private readonly failCapture = false,
|
||||
) {
|
||||
this.processOwnership = mode === "launch" ? "provider-owned" : "external";
|
||||
}
|
||||
|
||||
currentUrl() {
|
||||
return "https://app.example.test/current";
|
||||
}
|
||||
|
||||
setStep(index: number) {
|
||||
this.step = index;
|
||||
}
|
||||
|
||||
nextEventSequence() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
lastEventSequence() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
events(): {
|
||||
readonly retained: number;
|
||||
readonly dropped: number;
|
||||
readonly items: readonly BrowserScenarioEvent[];
|
||||
} {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
|
||||
eventTruncationSections() {
|
||||
return this.eventTruncations;
|
||||
}
|
||||
|
||||
async perform(
|
||||
_action: BrowserScenarioAction,
|
||||
_timeout: number,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
this.performCalls += 1;
|
||||
this.onPerform?.();
|
||||
if (signal?.aborted === true) throw new Error("request cancelled");
|
||||
if (this.failAction) throw new Error("fixture secret action failure");
|
||||
}
|
||||
|
||||
capture(
|
||||
requested: ReadonlySet<SnapshotKind>,
|
||||
_budget: BrowserScenarioCaptureBudget,
|
||||
): Promise<BrowserStepArtifacts> {
|
||||
this.captureCalls += 1;
|
||||
if (this.failCapture) return Promise.reject(new Error("capture failed"));
|
||||
return Promise.resolve(
|
||||
browserStepArtifactsSchema.parse({
|
||||
screenshot: artifactState("screenshot", requested, this.incomplete),
|
||||
dom: artifactState("dom", requested, this.incomplete),
|
||||
accessibility: artifactState(
|
||||
"accessibility",
|
||||
requested,
|
||||
this.incomplete,
|
||||
),
|
||||
url: artifactState("url", requested, this.incomplete),
|
||||
history: artifactState("history", requested, this.incomplete),
|
||||
storage: artifactState("storage", requested, this.incomplete),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closeCalls += 1;
|
||||
return Promise.resolve(
|
||||
this.mode === "launch"
|
||||
? ("terminated-owned-process" as const)
|
||||
: ("disconnected-external" as const),
|
||||
);
|
||||
}
|
||||
|
||||
redactError(error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message.replaceAll("secret", "[REDACTED]")
|
||||
: "fixture failure";
|
||||
}
|
||||
}
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
it("captures initial and action steps and closes its launched session", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ step_index }) => step_index)).toEqual([
|
||||
0, 1,
|
||||
]);
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("makes missing and truncated captures ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch", true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ captures: ["screenshot", "dom"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
it("makes event limit truncation ineligible for equality", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
session.eventTruncations = ["events", "websockets"];
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ events: ["websockets"] }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
truncated_sections: ["events", "websockets"],
|
||||
});
|
||||
});
|
||||
|
||||
it("records one failed step, cancels later actions, and still cleans up", async () => {
|
||||
const session = new FakeSession("launch", false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario({ actions: 2 }));
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps.map(({ status }) => status)).toEqual([
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]);
|
||||
expect(result.value.steps[1]?.error).toBe(
|
||||
"fixture [REDACTED] action failure",
|
||||
);
|
||||
expect(session.performCalls).toBe(1);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
expect(result.value.completeness.equality_eligible).toBe(false);
|
||||
});
|
||||
|
||||
it("disconnects external CDP sessions and marks pre-attach events missing", async () => {
|
||||
const session = new FakeSession("connect");
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(
|
||||
scenario({ mode: "connect" }),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.browser).toMatchObject({
|
||||
process_ownership: "external",
|
||||
cleanup: "disconnected-external",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["events"],
|
||||
});
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("closes the session when initial capture fails", async () => {
|
||||
const session = new FakeSession("launch", false, false, true);
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario());
|
||||
expect(result.ok).toBe(false);
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("does not open a session for an already-cancelled request", async () => {
|
||||
let opens = 0;
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => {
|
||||
opens += 1;
|
||||
return Promise.resolve(new FakeSession("launch"));
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(opens).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels an active action and still closes the session", async () => {
|
||||
const controller = new AbortController();
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => controller.abort();
|
||||
const provider = new PlaywrightBrowserScenarioProvider({
|
||||
open: () => Promise.resolve(session),
|
||||
});
|
||||
const result = await provider.captureScenario(scenario(), {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.steps[1]?.status).toBe("cancelled");
|
||||
expect(session.closeCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("BrowserScenarioCaptureBudget", () => {
|
||||
it("enforces cumulative screenshot and metadata limits", () => {
|
||||
const budget = new BrowserScenarioCaptureBudget(1, 10);
|
||||
expect(budget.claimScreenshot()).toBe(true);
|
||||
expect(budget.claimScreenshot()).toBe(false);
|
||||
expect(budget.claimMetadata(6)).toBe(true);
|
||||
expect(budget.claimMetadata(5)).toBe(false);
|
||||
expect(budget.claimMetadata(4)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { withPlaywrightExecutionBoundary } from "../../../src/browser/PlaywrightExecutionBoundary.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../../../src/domain/errors.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
25,
|
||||
);
|
||||
const rejection =
|
||||
expect(result).rejects.toBeInstanceOf(AnalysisTimeoutError);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
await rejection;
|
||||
});
|
||||
|
||||
it("rejects when the caller cancels active work", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = withPlaywrightExecutionBoundary(
|
||||
() => new Promise<never>(() => undefined),
|
||||
1_000,
|
||||
controller.signal,
|
||||
);
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
});
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Page } from "playwright-core";
|
||||
|
||||
import { BrowserScenarioSecrets } from "../../../src/browser/BrowserScenarioSecrets.js";
|
||||
import { BrowserScenarioCaptureBudget } from "../../../src/browser/PlaywrightScenarioArtifacts.js";
|
||||
import { PlaywrightScenarioEvents } from "../../../src/browser/PlaywrightScenarioEvents.js";
|
||||
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js";
|
||||
|
||||
describe("PlaywrightScenarioEvents", () => {
|
||||
it("bounds oversized page errors before validating captured events", () => {
|
||||
const listeners = new Map<string, (value: Error) => void>();
|
||||
const page = {
|
||||
url: () => "https://app.example.test/",
|
||||
on: (name: string, listener: (value: Error) => void) => {
|
||||
listeners.set(name, listener);
|
||||
},
|
||||
} as unknown as Page;
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: "/opt/chromium",
|
||||
headless: true,
|
||||
user_data: "temporary-owned",
|
||||
cleanup: "close-and-delete-profile",
|
||||
},
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
environment: {
|
||||
viewport: { width: 1_280, height: 720 },
|
||||
locale: "en-US",
|
||||
timezone: "UTC",
|
||||
color_scheme: "light",
|
||||
reduced_motion: "reduce",
|
||||
service_workers: "block",
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
step_id: "wait",
|
||||
action: "wait_for_timeout",
|
||||
duration_ms: 1,
|
||||
},
|
||||
],
|
||||
storage: {},
|
||||
request_replay: { mode: "disabled" },
|
||||
secrets: [],
|
||||
redaction: {
|
||||
secret_values: "replace-with-secret-reference",
|
||||
query_parameter_names: [],
|
||||
},
|
||||
capture: {
|
||||
after_each_step: [],
|
||||
at_end: [],
|
||||
events: ["page-errors"],
|
||||
},
|
||||
limits: {
|
||||
max_duration_ms: 10_000,
|
||||
action_timeout_ms: 1_000,
|
||||
navigation_timeout_ms: 1_000,
|
||||
max_events: 10,
|
||||
max_frames: 10,
|
||||
max_workers: 10,
|
||||
max_popups: 10,
|
||||
max_websockets: 10,
|
||||
max_dom_nodes: 100,
|
||||
max_accessibility_nodes: 100,
|
||||
max_screenshots: 1,
|
||||
max_screenshot_bytes: 1_024,
|
||||
max_storage_entries: 10,
|
||||
max_total_metadata_bytes: 1_000_000,
|
||||
},
|
||||
approved: true,
|
||||
});
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, {});
|
||||
if (secrets === undefined) throw new Error("Expected resolved secrets");
|
||||
const events = new PlaywrightScenarioEvents({
|
||||
page,
|
||||
enabled: new Set(["page-errors"]),
|
||||
limits: scenario.limits,
|
||||
secrets,
|
||||
budget: new BrowserScenarioCaptureBudget(1, 1_000_000),
|
||||
allowedOrigins: scenario.allowed_origins,
|
||||
});
|
||||
const error = new Error("m".repeat(70_000));
|
||||
error.stack = "s".repeat(300_000);
|
||||
|
||||
expect(() => listeners.get("pageerror")?.(error)).not.toThrow();
|
||||
expect(events.result().items[0]).toMatchObject({
|
||||
kind: "page-error",
|
||||
message: "m".repeat(65_536),
|
||||
stack: "s".repeat(262_144),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,207 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyProtocolFamily,
|
||||
decodeGrpcFrame,
|
||||
decodeJsonRpc,
|
||||
decodeMessagePack,
|
||||
inferMessageSchema,
|
||||
looksLikeCredential,
|
||||
protocolCaptureSchema,
|
||||
type ProtocolMessage,
|
||||
type ProtocolCapture,
|
||||
} from "../../../src/domain/protocolCapture.js";
|
||||
|
||||
describe("protocol capture", () => {
|
||||
it("classifies gRPC from content type", () => {
|
||||
expect(classifyProtocolFamily("application/grpc+proto", null)).toBe("grpc");
|
||||
});
|
||||
|
||||
it("classifies protobuf from content type", () => {
|
||||
expect(classifyProtocolFamily("application/x-protobuf", null)).toBe(
|
||||
"protobuf",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies json-rpc from content type", () => {
|
||||
expect(classifyProtocolFamily("application/json-rpc", null)).toBe(
|
||||
"json-rpc",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies msgpack from content type", () => {
|
||||
expect(classifyProtocolFamily("application/msgpack", null)).toBe(
|
||||
"messagepack",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies from path when content type is null", () => {
|
||||
expect(classifyProtocolFamily(null, "/some/grpc/method")).toBe("grpc");
|
||||
expect(classifyProtocolFamily(null, "/api/json-rpc/2.0")).toBe("json-rpc");
|
||||
});
|
||||
|
||||
it("returns null for unknown protocols", () => {
|
||||
expect(classifyProtocolFamily("text/plain", null)).toBeNull();
|
||||
expect(classifyProtocolFamily(null, null)).toBeNull();
|
||||
});
|
||||
|
||||
it("detects credential-like field names", () => {
|
||||
expect(looksLikeCredential("password")).toBe(true);
|
||||
expect(looksLikeCredential("api_key")).toBe(true);
|
||||
expect(looksLikeCredential("authorization")).toBe(true);
|
||||
expect(looksLikeCredential("username")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JSON-RPC decoding", () => {
|
||||
it("decodes a simple JSON-RPC request", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
method: "add",
|
||||
params: [1, 2],
|
||||
id: 1,
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
expect(result.decoded_fields.length).toBe(4);
|
||||
expect(result.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("redacts credential-like fields", () => {
|
||||
const payload = new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
password: "secret123",
|
||||
username: "admin",
|
||||
}),
|
||||
);
|
||||
const result = decodeJsonRpc(payload);
|
||||
const passwordField = result.decoded_fields.find(
|
||||
(f) => f.path === "password",
|
||||
);
|
||||
expect(passwordField?.value).toBe("[REDACTED]");
|
||||
const usernameField = result.decoded_fields.find(
|
||||
(f) => f.path === "username",
|
||||
);
|
||||
expect(usernameField?.value).toBe("admin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MessagePack decoding", () => {
|
||||
it("detects map type", () => {
|
||||
const payload = new Uint8Array([0x82]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("map");
|
||||
});
|
||||
|
||||
it("detects array type", () => {
|
||||
const payload = new Uint8Array([0x92]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("array");
|
||||
});
|
||||
|
||||
it("reports unknown type for other tags", () => {
|
||||
const payload = new Uint8Array([0xff]);
|
||||
const result = decodeMessagePack(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe("unknown");
|
||||
expect(result.decoded_fields[0]?.inferred).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("gRPC frame decoding", () => {
|
||||
it("decodes a valid gRPC frame header", () => {
|
||||
const payload = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x00, 0x05, 1, 2, 3, 4, 5,
|
||||
]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields).toHaveLength(2);
|
||||
expect(result.decoded_fields[0]?.path).toBe("compressed");
|
||||
expect(result.decoded_fields[0]?.value).toBe(false);
|
||||
expect(result.decoded_fields[1]?.path).toBe("message_length");
|
||||
expect(result.decoded_fields[1]?.value).toBe(5);
|
||||
});
|
||||
|
||||
it("detects compressed flag", () => {
|
||||
const payload = new Uint8Array([0x01, 0x00, 0x00, 0x00, 0x0a]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.value).toBe(true);
|
||||
});
|
||||
|
||||
it("handles too-short frames", () => {
|
||||
const payload = new Uint8Array([0x00, 0x01]);
|
||||
const result = decodeGrpcFrame(payload);
|
||||
expect(result.decoded_fields[0]?.path).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("schema inference", () => {
|
||||
it("infers schema from repeated messages", () => {
|
||||
const messages: ProtocolMessage[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
family: "json-rpc",
|
||||
direction: "request",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "method", wire_type: "json", value: "add", inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
family: "json-rpc",
|
||||
direction: "response",
|
||||
endpoint: "/api",
|
||||
content_type: "application/json",
|
||||
raw_payload: null,
|
||||
decoded_fields: [
|
||||
{ path: "result", wire_type: "json", value: 3, inferred: false },
|
||||
{ path: "id", wire_type: "json", value: 1, inferred: false },
|
||||
],
|
||||
schema_hypotheses: [],
|
||||
truncated: false,
|
||||
credentials_redacted: false,
|
||||
},
|
||||
];
|
||||
const hypotheses = inferMessageSchema(messages);
|
||||
expect(hypotheses).toHaveLength(3);
|
||||
const idHypothesis = hypotheses.find((h) => h.field_name === "id");
|
||||
expect(idHypothesis).toBeDefined();
|
||||
expect(idHypothesis!.evidence_count).toBe(2);
|
||||
expect(idHypothesis!.confidence).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("uses ProtocolCapture type", () => {
|
||||
it("validates a well-formed capture typed value", () => {
|
||||
const capture: ProtocolCapture = {
|
||||
family: "grpc",
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
expect(capture.family).toBe("grpc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("protocol capture schema validation", () => {
|
||||
it("validates a well-formed capture", () => {
|
||||
const capture = {
|
||||
family: "grpc" as const,
|
||||
messages: [],
|
||||
inferred_schema: [],
|
||||
has_truncated: false,
|
||||
credentials_detected: false,
|
||||
};
|
||||
const result = protocolCaptureSchema.safeParse(capture);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isCliOperationFailure,
|
||||
logCliCommand,
|
||||
} from "../../../src/cliLogging.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
|
||||
const originalExitCode = process.exitCode;
|
||||
|
||||
afterEach(() => {
|
||||
process.exitCode = originalExitCode;
|
||||
});
|
||||
|
||||
describe("CLI operation status", () => {
|
||||
it.each([
|
||||
["typed error", { error: "Analysis failed", category: "timeout" }],
|
||||
["unhealthy diagnostic", { healthy: false, checks: [] }],
|
||||
["failed status", { status: "failed" }],
|
||||
["confirmation requirement", { status: "needs_confirmation" }],
|
||||
["human remediation", { status: "needs_human" }],
|
||||
["unapplied plan", { status: "planned" }],
|
||||
])("classifies %s as failure", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["ready setup", { status: "ready" }],
|
||||
["complete uninstall", { status: "complete" }],
|
||||
["current version", { status: "current" }],
|
||||
["completed upgrade", { status: "upgraded" }],
|
||||
["healthy diagnostics", { healthy: true, checks: [] }],
|
||||
["bounded evidence", { evidence: [{ truncated: true }] }],
|
||||
])("keeps %s successful", (_label, value) => {
|
||||
expect(isCliOperationFailure(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("sets a nonzero process status without replacing structured output", async () => {
|
||||
const output = {
|
||||
error: "Analysis failed",
|
||||
category: "integrity_mismatch",
|
||||
message: "Artifact integrity check failed.",
|
||||
details: { logical_path: "main.js" },
|
||||
};
|
||||
|
||||
await expect(
|
||||
logCliCommand(silentLogger, "inventory-artifact", () =>
|
||||
Promise.resolve(output),
|
||||
),
|
||||
).resolves.toBe(output);
|
||||
expect(process.exitCode).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,456 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ClientRegistrationStatus } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("12.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("doctor", () => {
|
||||
it("returns exact recovery for every failed diagnostic", async () => {
|
||||
const result = await runDoctor(
|
||||
"/missing/app",
|
||||
host({
|
||||
nodeVersion: "20.0.0",
|
||||
macosVersion: () => Promise.resolve("11.7"),
|
||||
executable: () => Promise.resolve(false),
|
||||
validTarget: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
Object.fromEntries(
|
||||
result.checks.map(({ name, remediation }) => [name, remediation]),
|
||||
),
|
||||
).toEqual({
|
||||
node: "Install Node.js 22.19+ or 24.11+.",
|
||||
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
|
||||
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
target: "Supply a readable local app or program path.",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["11.7", undefined])(
|
||||
"rejects unsupported macOS version %s",
|
||||
async (version) => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ macosVersion: () => Promise.resolve(version) }),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("admits only the experimental Windows x64 host boundary", async () => {
|
||||
const windows = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
const arm = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "win32",
|
||||
architecture: "arm64",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(windows.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(arm.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: false,
|
||||
detail: "win32 arm64",
|
||||
});
|
||||
});
|
||||
it("detects a manual configured Hopper before Homebrew", async () => {
|
||||
let brewProbes = 0;
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: "/manual/Hopper",
|
||||
executable: (path) => Promise.resolve(path === "/manual/Hopper"),
|
||||
brewHopperPath: () => {
|
||||
brewProbes += 1;
|
||||
return Promise.resolve(undefined);
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe("/manual/Hopper");
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(brewProbes).toBe(0);
|
||||
});
|
||||
|
||||
it("reports optional BYO ilspycmd diagnostics only when configured", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/tools/ilspycmd",
|
||||
ilspyCmdVersion: (path) =>
|
||||
Promise.resolve(
|
||||
path === "/tools/ilspycmd" ? "ilspycmd: 9.1.0.7988" : undefined,
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
detail: "/tools/ilspycmd (ilspycmd: 9.1.0.7988)",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports configured ilspycmd drift without installing it", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredIlspyCmdPath: "/missing/ilspycmd",
|
||||
ilspyCmdVersion: () => Promise.resolve(undefined),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "ilspycmd",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "/missing/ilspycmd",
|
||||
remediation:
|
||||
"Unset REA_ILSPY_CMD_PATH or point it at a runnable ilspycmd executable.",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not fall back when the configured Hopper launcher is invalid", async () => {
|
||||
const configuredPath = "/invalid/custom/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ configuredHopperPath: configuredPath }),
|
||||
);
|
||||
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks.find(({ name }) => name === "hopper")).toEqual({
|
||||
name: "hopper",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: configuredPath,
|
||||
remediation:
|
||||
"Unset or update HOPPER_LAUNCHER_PATH to an executable Hopper launcher.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor installation identity", () => {
|
||||
it("distinguishes stale skills, path shadowing, and unobservable live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
installationPaths: () =>
|
||||
Promise.resolve(["/usr/local/bin/rea", "/home/user/bin/rea"]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: "10",
|
||||
toolCount: null,
|
||||
catalogDigest: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
installations: { state: "multiple" },
|
||||
skill: {
|
||||
installed_version: "10",
|
||||
state: "stale",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("reports a missing installed skill as unhealthy", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({ installedSkillIdentity: () => Promise.resolve(undefined) }),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.skill).toMatchObject({
|
||||
state: "missing",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
expect(result.checks).toContainEqual({
|
||||
name: "skill:identity",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: "Installed REA skill identity is missing.",
|
||||
remediation: "Run rea setup to update the installed REA skill.",
|
||||
});
|
||||
});
|
||||
it("reports stale client registration paths without claiming live state", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
clientRegistrations: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale",
|
||||
remediation:
|
||||
"Run rea setup to refresh this registration, then restart the client.",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity).toMatchObject({
|
||||
live_server: { state: "unknown" },
|
||||
registrations: [{ client: "codex", state: "stale" }],
|
||||
});
|
||||
expect(result.checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "registration:codex",
|
||||
classification: "config_drift",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor scoped readiness", () => {
|
||||
it("scopes effective readiness to selected clients without hiding drift", async () => {
|
||||
const registrations: readonly ClientRegistrationStatus[] = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["/current/rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
{
|
||||
client: "cursor",
|
||||
config_path: "/home/user/.cursor/mcp.json",
|
||||
command: ["/old/rea", "mcp"],
|
||||
state: "stale",
|
||||
remediation: "Run rea setup to refresh this registration.",
|
||||
},
|
||||
];
|
||||
const scoped = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["codex"] },
|
||||
);
|
||||
|
||||
expect(scoped).toMatchObject({
|
||||
healthy: true,
|
||||
environment_healthy: false,
|
||||
scope: { mode: "explicit", clients: ["codex"] },
|
||||
});
|
||||
expect(scoped.scope_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:codex", ok: true }),
|
||||
);
|
||||
expect(scoped.informational_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "registration:cursor", ok: false }),
|
||||
);
|
||||
|
||||
const staleSelected = await runDoctor(
|
||||
undefined,
|
||||
host({ clientRegistrations: () => Promise.resolve(registrations) }),
|
||||
{ clients: ["cursor"] },
|
||||
);
|
||||
expect(staleSelected.healthy).toBe(false);
|
||||
});
|
||||
|
||||
it("requires explicitly selected providers instead of any available provider", async () => {
|
||||
const ghidra = {
|
||||
id: "ghidra",
|
||||
configured: true,
|
||||
available: true,
|
||||
providerVersion: "12.1.2",
|
||||
registrationEnvironment: { GHIDRA_INSTALL_DIR: "/tools/ghidra" },
|
||||
checks: [
|
||||
{
|
||||
name: "configuration",
|
||||
ok: true,
|
||||
code: null,
|
||||
detail: "/tools/ghidra",
|
||||
remediation: null,
|
||||
classification: "config_drift" as const,
|
||||
},
|
||||
],
|
||||
};
|
||||
const noHopper = host({
|
||||
executable: () => Promise.resolve(false),
|
||||
providerInspections: () => Promise.resolve([ghidra]),
|
||||
});
|
||||
|
||||
const hopper = await runDoctor(undefined, noHopper, {
|
||||
providers: ["hopper"],
|
||||
});
|
||||
expect(hopper).toMatchObject({
|
||||
healthy: false,
|
||||
environment_healthy: true,
|
||||
});
|
||||
|
||||
const selectedGhidra = await runDoctor(undefined, noHopper, {
|
||||
providers: ["ghidra"],
|
||||
});
|
||||
expect(selectedGhidra.healthy).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor Linux and Hopper discovery", () => {
|
||||
it("accepts an officially supported Linux distribution", async () => {
|
||||
const path = "/home/user/.local/share/rea/hopper/bin/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
configuredHopperPath: path,
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
it("reports missing Linux demo-session dependencies", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: "Install Xvfb, xauth, Python 3, libX11, and libXtst.",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-demo-runtime"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("xauth"),
|
||||
});
|
||||
});
|
||||
it("explains how to recover from an unsupported configured launcher", async () => {
|
||||
const path = "/custom/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
configuredHopperPath: path,
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
supportedLinuxHopper: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "hopper-version")?.remediation,
|
||||
).toContain("Unset or update HOPPER_LAUNCHER_PATH");
|
||||
});
|
||||
it("detects a Homebrew cask installed outside /Applications", async () => {
|
||||
const path =
|
||||
"/opt/homebrew/Caskroom/hopper/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
brewHopperPath: () => Promise.resolve(path),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("detects a manually installed Hopper application", async () => {
|
||||
const path = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
executable: (candidate) => Promise.resolve(candidate === path),
|
||||
manualHopperPaths: () => Promise.resolve([path]),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBe(path);
|
||||
});
|
||||
|
||||
it("uses shared app target validation when a target is supplied", async () => {
|
||||
const result = await runDoctor(
|
||||
"/Applications/Notes.app",
|
||||
host({
|
||||
validTarget: (path) =>
|
||||
Promise.resolve(path === "/Applications/Notes.app"),
|
||||
}),
|
||||
);
|
||||
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a readable Hopper launcher without execute permission", async () => {
|
||||
const path = "/manual/Hopper";
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
configuredHopperPath: path,
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: () => Promise.resolve(false),
|
||||
}),
|
||||
);
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,93 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
|
||||
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve("12.0"),
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
executable: (path) => Promise.resolve(path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("doctor runtime executable diagnostics", () => {
|
||||
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
runtimeExecutables: () =>
|
||||
Promise.resolve({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/healthy/node",
|
||||
canonical_path: "/healthy/node",
|
||||
path_index: null,
|
||||
selection: "rea-launcher",
|
||||
version: "v24.18.0",
|
||||
healthy: true,
|
||||
failure: null,
|
||||
},
|
||||
{
|
||||
tool: "node",
|
||||
lexical_path: "/opt/homebrew/bin/node",
|
||||
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
|
||||
path_index: 2,
|
||||
selection: "path-shadowed",
|
||||
version: null,
|
||||
healthy: false,
|
||||
failure: {
|
||||
code: "runtime_dynamic_library_missing",
|
||||
exit_code: 134,
|
||||
signal: null,
|
||||
dependency:
|
||||
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
|
||||
stderr: "dyld: Library not loaded",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.identity?.runtime_executables).toMatchObject({
|
||||
launcher_node: "/healthy/node",
|
||||
candidates: [
|
||||
{ healthy: true, selection: "rea-launcher" },
|
||||
{
|
||||
healthy: false,
|
||||
failure: { code: "runtime_dynamic_library_missing" },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "node-toolchains"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.stringContaining("Do not create"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
import {
|
||||
copyFile,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
configureTomlClient,
|
||||
detectClients,
|
||||
} from "../../../src/application/Setup.js";
|
||||
import {
|
||||
runUninstall,
|
||||
systemUninstallHost,
|
||||
type UninstallFileSystem,
|
||||
} from "../../../src/application/Uninstall.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("client configuration filesystem lifecycle", () => {
|
||||
it("detects every supported client and skips absent clients", async () => {
|
||||
const home = await createTestTempDirectory("rea-detect-");
|
||||
roots.push(home);
|
||||
for (const marker of [
|
||||
".claude",
|
||||
"Library/Application Support/Claude",
|
||||
".codex",
|
||||
".cursor",
|
||||
".gemini",
|
||||
".codeium/windsurf",
|
||||
".devin",
|
||||
])
|
||||
await mkdir(join(home, marker), { recursive: true });
|
||||
const detected = await detectClients(home);
|
||||
expect(detected.map(({ name }) => name)).toEqual([
|
||||
"claude_code",
|
||||
"claude_desktop",
|
||||
"codex",
|
||||
"cursor",
|
||||
"gemini_cli",
|
||||
"windsurf",
|
||||
"devin",
|
||||
]);
|
||||
expect(
|
||||
detected.find(({ name }) => name === "claude_code")?.configPath,
|
||||
).toBe(join(home, ".claude.json"));
|
||||
expect(detected.find(({ name }) => name === "devin")?.format).toBe(
|
||||
"unsupported",
|
||||
);
|
||||
const emptyHome = await createTestTempDirectory("rea-empty-");
|
||||
roots.push(emptyHome);
|
||||
expect(await detectClients(emptyHome)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves unrelated Codex TOML and supports an installed command", async () => {
|
||||
const home = await createTestTempDirectory("rea-toml-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".codex/config.toml");
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(
|
||||
configPath,
|
||||
'model = "gpt-5"\n[mcp_servers.other]\ncommand = "other"\n',
|
||||
);
|
||||
expect(
|
||||
await configureTomlClient(
|
||||
{ name: "codex", configPath, format: "toml" },
|
||||
{
|
||||
HOPPER_LAUNCHER_PATH: "/Hopper Path",
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra",
|
||||
JAVA_HOME: "/opt/jdk-21",
|
||||
},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).toMatchObject({ status: "configured" });
|
||||
const configured = await readFile(configPath, "utf8");
|
||||
expect(configured).toContain('model = "gpt-5"');
|
||||
expect(configured).toContain("[mcp_servers.rea]");
|
||||
expect(configured).toContain('command = "rea"');
|
||||
expect(configured).toContain("startup_timeout_sec = 30");
|
||||
expect(configured).toContain('GHIDRA_INSTALL_DIR = "/opt/ghidra"');
|
||||
expect(configured).toContain('JAVA_HOME = "/opt/jdk-21"');
|
||||
expect(
|
||||
await configureTomlClient(
|
||||
{ name: "codex", configPath, format: "toml" },
|
||||
{
|
||||
HOPPER_LAUNCHER_PATH: "/Hopper Path",
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra",
|
||||
JAVA_HOME: "/opt/jdk-21",
|
||||
},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).toEqual({ status: "unchanged" });
|
||||
});
|
||||
|
||||
it("does not rewrite an equivalent Codex registration with reordered environment keys", async () => {
|
||||
const home = await createTestTempDirectory("rea-toml-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".codex/config.toml");
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(
|
||||
configPath,
|
||||
`[mcp_servers.rea]\ncommand = "rea"\nargs = ["mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.rea.env]\nJAVA_HOME = "/opt/jdk-21"\nHOPPER_LAUNCHER_PATH = "/Hopper Path"\nGHIDRA_INSTALL_DIR = "/opt/ghidra"\n`,
|
||||
);
|
||||
|
||||
expect(
|
||||
await configureTomlClient(
|
||||
{ name: "codex", configPath, format: "toml" },
|
||||
{
|
||||
HOPPER_LAUNCHER_PATH: "/Hopper Path",
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra",
|
||||
JAVA_HOME: "/opt/jdk-21",
|
||||
},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).toEqual({ status: "unchanged" });
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("updates a symlink target without replacing the TOML config symlink", async () => {
|
||||
const home = await createTestTempDirectory("rea-toml-symlink-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".codex/config.toml");
|
||||
const targetPath = join(home, "managed-config.toml");
|
||||
const original = 'model = "gpt-5"\n';
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(targetPath, original);
|
||||
await symlink(targetPath, configPath);
|
||||
|
||||
expect(
|
||||
await configureTomlClient(
|
||||
{ name: "codex", configPath, format: "toml" },
|
||||
undefined,
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).toMatchObject({ status: "configured" });
|
||||
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(await readFile(targetPath, "utf8")).toContain("[mcp_servers.rea]");
|
||||
});
|
||||
|
||||
it("fails before mutation when a TOML config symlink is dangling", async () => {
|
||||
const home = await createTestTempDirectory("rea-toml-symlink-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".codex/config.toml");
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await symlink(join(home, "missing-config.toml"), configPath);
|
||||
|
||||
expect(
|
||||
await configureTomlClient({ name: "codex", configPath, format: "toml" }),
|
||||
).toEqual({ status: "failed", reason: "path" });
|
||||
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("client configuration filesystem removal", () => {
|
||||
it("uninstalls only owned entries and refuses purge symlinks", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-");
|
||||
roots.push(home);
|
||||
const cursor = join(home, ".cursor/mcp.json");
|
||||
const skill = join(
|
||||
home,
|
||||
".agents/skills/reverse-engineer-anything/SKILL.md",
|
||||
);
|
||||
await mkdir(dirname(cursor), { recursive: true });
|
||||
await mkdir(dirname(skill), { recursive: true });
|
||||
await writeFile(
|
||||
cursor,
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
rea: { command: "/isolated prefix/bin/rea", args: ["mcp"] },
|
||||
other: { command: "other" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
await writeFile(skill, "managed");
|
||||
await mkdir(join(home, ".rea"), { recursive: true });
|
||||
await import("node:fs/promises").then(({ symlink }) =>
|
||||
symlink(home, join(home, ".rea/cache")),
|
||||
);
|
||||
const first = await runUninstall(true, systemUninstallHost(home));
|
||||
expect(first.status).toBe("complete");
|
||||
expect(JSON.parse(await readFile(cursor, "utf8"))).toEqual({
|
||||
mcpServers: { other: { command: "other" } },
|
||||
});
|
||||
await expect(readFile(skill, "utf8")).rejects.toThrow();
|
||||
expect(first.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "cache",
|
||||
status: "retained",
|
||||
detail:
|
||||
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
|
||||
}),
|
||||
);
|
||||
expect((await runUninstall(true, systemUninstallHost(home))).status).toBe(
|
||||
"complete",
|
||||
);
|
||||
});
|
||||
|
||||
it("removes an owned entry through a symlink without replacing it", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-symlink-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".cursor/mcp.json");
|
||||
const targetPath = join(home, "managed-mcp.json");
|
||||
const original = JSON.stringify({
|
||||
mcpServers: {
|
||||
rea: { command: "rea", args: ["mcp"] },
|
||||
other: { command: "other" },
|
||||
},
|
||||
});
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(targetPath, original);
|
||||
await symlink(targetPath, configPath);
|
||||
|
||||
expect((await runUninstall(false, systemUninstallHost(home))).status).toBe(
|
||||
"complete",
|
||||
);
|
||||
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
|
||||
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(JSON.parse(await readFile(targetPath, "utf8"))).toEqual({
|
||||
mcpServers: { other: { command: "other" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails before mutation when an uninstall config symlink is dangling", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-symlink-");
|
||||
roots.push(home);
|
||||
const configPath = join(home, ".cursor/mcp.json");
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await symlink(join(home, "missing-mcp.json"), configPath);
|
||||
|
||||
const result = await runUninstall(false, systemUninstallHost(home));
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual({
|
||||
name: "cursor",
|
||||
status: "failed",
|
||||
detail:
|
||||
"Configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun uninstall.",
|
||||
});
|
||||
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
|
||||
await expect(
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("fails closed on malformed client configuration", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-bad-");
|
||||
roots.push(home);
|
||||
const config = join(home, ".cursor/mcp.json");
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(config, "not-json");
|
||||
const result = await runUninstall(false, systemUninstallHost(home));
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "cursor",
|
||||
status: "failed",
|
||||
detail:
|
||||
"Configuration is not valid JSON and was not changed. Repair it, then rerun uninstall.",
|
||||
}),
|
||||
);
|
||||
expect(await readFile(config, "utf8")).toBe("not-json");
|
||||
});
|
||||
});
|
||||
|
||||
describe("client configuration filesystem failure reporting", () => {
|
||||
it.each([
|
||||
[
|
||||
"read",
|
||||
"Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
],
|
||||
[
|
||||
"backup",
|
||||
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
|
||||
],
|
||||
[
|
||||
"update",
|
||||
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
|
||||
],
|
||||
[
|
||||
"restore",
|
||||
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
|
||||
],
|
||||
] as const)(
|
||||
"reports an actionable client %s failure",
|
||||
async (failure, detail) => {
|
||||
const { home, config } = await uninstallFixture();
|
||||
let writes = 0;
|
||||
const fileSystem: UninstallFileSystem = {
|
||||
...testFileSystem,
|
||||
readText: (path) =>
|
||||
failure === "read" && path === config
|
||||
? Promise.reject(new Error("SECRET read failure"))
|
||||
: readFile(path, "utf8"),
|
||||
copy: (source, destination) =>
|
||||
failure === "backup"
|
||||
? Promise.reject(new Error("SECRET backup failure"))
|
||||
: copyFile(source, destination),
|
||||
writeText: async (path, contents) => {
|
||||
writes += 1;
|
||||
if ((failure === "update" && writes === 1) || failure === "restore")
|
||||
throw new Error("SECRET write failure");
|
||||
await writeFile(path, contents);
|
||||
},
|
||||
};
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, fileSystem),
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({ name: "cursor", status: "failed", detail }),
|
||||
);
|
||||
expect(JSON.stringify(result)).not.toContain("SECRET");
|
||||
},
|
||||
);
|
||||
|
||||
it("reports a managed-path removal failure", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-remove-");
|
||||
roots.push(home);
|
||||
const skillRoot = join(home, ".agents/skills/reverse-engineer-anything");
|
||||
await mkdir(skillRoot, { recursive: true });
|
||||
const result = await runUninstall(
|
||||
false,
|
||||
systemUninstallHost(home, {
|
||||
...testFileSystem,
|
||||
remove: () => Promise.reject(new Error("SECRET removal failure")),
|
||||
}),
|
||||
);
|
||||
expect(result.items).toContainEqual({
|
||||
name: "skill",
|
||||
status: "failed",
|
||||
detail:
|
||||
"This item could not be removed. Check file permissions, then rerun uninstall.",
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("SECRET");
|
||||
});
|
||||
});
|
||||
|
||||
const testFileSystem: UninstallFileSystem = {
|
||||
readText: (path) => readFile(path, "utf8"),
|
||||
copy: (source, destination) => copyFile(source, destination),
|
||||
writeText: (path, contents) => writeFile(path, contents),
|
||||
stat: (path) => lstat(path),
|
||||
realpath: (path) => realpath(path),
|
||||
remove: (path) => rm(path, { recursive: true }),
|
||||
};
|
||||
|
||||
const uninstallFixture = async (): Promise<{
|
||||
readonly home: string;
|
||||
readonly config: string;
|
||||
}> => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-failure-");
|
||||
roots.push(home);
|
||||
const config = join(home, ".cursor/mcp.json");
|
||||
await mkdir(dirname(config), { recursive: true });
|
||||
await writeFile(
|
||||
config,
|
||||
JSON.stringify({ mcpServers: { rea: { command: "rea", args: ["mcp"] } } }),
|
||||
);
|
||||
return { home, config };
|
||||
};
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
|
||||
describe("configuration parsing integration", () => {
|
||||
it("returns defaults when no environment variables are set", () => {
|
||||
const result = parseConfig({});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe(
|
||||
process.platform === "linux"
|
||||
? "/opt/hopper/bin/Hopper"
|
||||
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
);
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([]);
|
||||
expect(result.value.analysisProvider).toBe("auto");
|
||||
});
|
||||
|
||||
it("parses a complete target-bound configuration", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/usr/bin/true",
|
||||
HOPPER_TARGET_KIND: "executable",
|
||||
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
|
||||
REA_ANALYSIS_PROVIDER: "hopper",
|
||||
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/tmp/releases"]',
|
||||
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
|
||||
expect(result.value.hopperTargetKind).toBe("executable");
|
||||
expect(result.value.analysisProvider).toBe("hopper");
|
||||
expect(result.value.hopperLoaderArgs).toEqual([
|
||||
"-l",
|
||||
"Mach-O",
|
||||
"--aarch64",
|
||||
]);
|
||||
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
|
||||
expect(result.value.investigationInputRoots).toEqual(["/tmp/releases"]);
|
||||
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
|
||||
"/tmp/analysis",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects target kind values outside the enum", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_KIND: "archive",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("Invalid REA environment");
|
||||
});
|
||||
|
||||
it("rejects invalid JSON in loader arguments", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: "not json",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("valid JSON");
|
||||
});
|
||||
|
||||
it("rejects non-array types in loader arguments JSON", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: '"just a string"',
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("unreachable");
|
||||
expect(result.error.message).toContain("array of strings");
|
||||
});
|
||||
|
||||
it("allows overriding the launcher path while keeping other defaults", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LAUNCHER_PATH: "/custom/hopper",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
|
||||
expect(result.value.hopperTargetPath).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses database target kind correctly", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_TARGET_PATH: "/path/to/file.hop",
|
||||
HOPPER_TARGET_KIND: "database",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error("unreachable");
|
||||
expect(result.value.hopperTargetKind).toBe("database");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { chmod, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { writeAnalysisSnapshot } from "../../../src/application/AnalysisSnapshotFiles.js";
|
||||
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
|
||||
import type { AnalysisSnapshot } from "../../../src/domain/analysisSnapshot.js";
|
||||
import {
|
||||
snapshotBinding,
|
||||
snapshotTarget,
|
||||
} from "../../../src/domain/analysisSnapshot.js";
|
||||
import { parseBinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
} from "../../../src/application/InvestigationProviders.js";
|
||||
import { HOPPER_PROVIDER_IDENTITY } from "../../../src/hopper/HopperProvider.js";
|
||||
import { resolveHopperAnalysisProfile } from "../../../src/hopper/HopperAnalysisProfile.js";
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("direct analysis snapshot filesystem permissions", () => {
|
||||
it("forwards the CLI provider selector ahead of the environment preference", async () => {
|
||||
const directory = await createTestTempDirectory("rea-direct-provider-");
|
||||
const targetPath = join(directory, "fixture.hop");
|
||||
await writeFile(targetPath, "fixture");
|
||||
vi.stubEnv("HOPPER_LAUNCHER_PATH", process.execPath);
|
||||
vi.stubEnv("REA_ANALYSIS_PROVIDER", "environment-provider");
|
||||
|
||||
await expect(
|
||||
runDirectAnalysis(
|
||||
targetPath,
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
providerId: "request-provider",
|
||||
},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
error: "Analysis failed",
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "unknown_provider",
|
||||
requested_provider_id: "request-provider",
|
||||
candidate_ids: ["ghidra", "hopper"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("replays a cache hit with snapshot read authority only", async () => {
|
||||
const directory = await createTestTempDirectory("rea-direct-snapshot-");
|
||||
const snapshotPath = join(directory, "analysis.json");
|
||||
const launcherPath = join(directory, "hopper-launcher");
|
||||
await writeFile(launcherPath, "fixture Hopper launcher");
|
||||
await chmod(launcherPath, 0o755);
|
||||
const target = await parseBinaryTarget(process.execPath);
|
||||
if (!target.ok) throw target.error;
|
||||
const resolved = await resolveHopperAnalysisProfile(target.value, {
|
||||
launcherPath,
|
||||
loaderArgsOverride: [],
|
||||
provider: HOPPER_PROVIDER_IDENTITY,
|
||||
});
|
||||
if (!resolved.ok || resolved.value.profile === null)
|
||||
throw new Error("fixture Hopper profile did not resolve");
|
||||
const profile = resolved.value.profile;
|
||||
const workflowProfile = workflowAnalysisProfile(profile);
|
||||
const evidence = createEvidence(target.value, REA_WORKFLOW_PROVIDER, {
|
||||
operation: "binary_overview",
|
||||
parameters: {},
|
||||
result: { cached: true },
|
||||
analysisProfile: workflowProfile,
|
||||
});
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
snapshot_version: 2,
|
||||
target: snapshotTarget(target.value),
|
||||
binding: snapshotBinding(profile),
|
||||
entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
};
|
||||
const policy = {
|
||||
roots: [directory],
|
||||
maxBytes: 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024,
|
||||
maxNodes: 10_000,
|
||||
};
|
||||
expect(
|
||||
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
|
||||
).toBe(true);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
directory,
|
||||
["snapshot_read", "snapshot_write"],
|
||||
["snapshot_read"],
|
||||
);
|
||||
vi.stubEnv("REA_ANALYSIS_SNAPSHOT_ROOTS_JSON", JSON.stringify([directory]));
|
||||
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
|
||||
|
||||
await expect(
|
||||
runDirectAnalysis(
|
||||
process.execPath,
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
snapshotPath,
|
||||
permissionAuthority: authority,
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(evidence);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -15,29 +14,13 @@ import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationP
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { managedRuntimeCorrelationResultSchema } from "../../../src/domain/managedRuntimeCorrelation.js";
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
|
||||
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
} from "../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed runtime correlation planning", () => {
|
||||
it("fails closed while the managed runtime authority is disabled", async () => {
|
||||
@@ -157,7 +140,7 @@ describe("managed runtime correlation planning", () => {
|
||||
await writeFile(artifactPath, bytes);
|
||||
await writeFile(executablePath, "#!/bin/sh\n");
|
||||
const fixture = inspect(bytes, artifactPath, {
|
||||
...memberLimits,
|
||||
...MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
maxMethodInstructions: 1,
|
||||
});
|
||||
const authority = await authorityFor(directory, executablePath, true);
|
||||
@@ -247,18 +230,9 @@ const inputFor = (
|
||||
const inspect = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
limits: typeof memberLimits = memberLimits,
|
||||
limits: typeof MANAGED_MEMBER_FIXTURE_LIMITS = MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
) => {
|
||||
const target: BinaryTarget = {
|
||||
path,
|
||||
sha256: hash(bytes),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
};
|
||||
const target = managedPeFixtureTarget(bytes, path);
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
const method = result.methods.items[0];
|
||||
if (method === undefined) throw new Error("fixture has no method");
|
||||
@@ -274,6 +248,3 @@ const inspect = (
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
canonicalizePermissionCeilings,
|
||||
canonicalizePermissionRequest,
|
||||
createPermissionAuthority,
|
||||
type PermissionAuthority,
|
||||
} from "../../../src/application/PermissionAuthority.js";
|
||||
import {
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
type PermissionGrant,
|
||||
type PermissionScope,
|
||||
} from "../../../src/domain/permissionPolicy.js";
|
||||
|
||||
describe("permission authority filesystem boundaries", () => {
|
||||
it("distinguishes an elicitable grant from administrator reconfiguration", async () => {
|
||||
const sandbox = await createTestTempDirectory(
|
||||
"rea-permission-remediation-",
|
||||
);
|
||||
const allowedRoot = join(sandbox, "allowed");
|
||||
const outsideRoot = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(allowedRoot), mkdir(outsideRoot)]);
|
||||
const authority = await createPermissionAuthority([
|
||||
evidenceScope(allowedRoot),
|
||||
]);
|
||||
expect(authority.ok).toBe(true);
|
||||
if (!authority.ok) return;
|
||||
|
||||
const inside = await authority.value.authorize(
|
||||
{
|
||||
...evidenceScope(allowedRoot),
|
||||
operation_identity: "read:inside-ceiling",
|
||||
},
|
||||
"read",
|
||||
{ remediation: "elicit" },
|
||||
);
|
||||
expect(inside).toMatchObject({
|
||||
ok: false,
|
||||
error: { remediation: "elicit" },
|
||||
});
|
||||
|
||||
const outside = await authority.value.createConnectionAuthority().authorize(
|
||||
{
|
||||
...evidenceScope(outsideRoot),
|
||||
operation_identity: "read:outside-ceiling",
|
||||
},
|
||||
"read",
|
||||
{ remediation: "elicit" },
|
||||
);
|
||||
expect(outside).toMatchObject({
|
||||
ok: false,
|
||||
error: { remediation: "restart" },
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts canonical aliases but rejects a symlink escape", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-");
|
||||
const root = join(sandbox, "root");
|
||||
const outside = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(root), mkdir(outside)]);
|
||||
await writeFile(join(root, "inside"), "inside");
|
||||
await writeFile(join(outside, "secret"), "secret");
|
||||
await symlink(root, join(sandbox, "root-alias"));
|
||||
await symlink(join(outside, "secret"), join(root, "escape"));
|
||||
const ceiling = await canonicalizePermissionCeilings([
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(sandbox, "root-alias")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
},
|
||||
]);
|
||||
expect(ceiling.ok).toBe(true);
|
||||
if (!ceiling.ok) return;
|
||||
const policy = createPermissionPolicy(ceiling.value, [
|
||||
{
|
||||
...ceiling.value[0]!,
|
||||
grant_id: "administrator:evidence-read",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
]);
|
||||
const inside = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(root, "inside")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:inside",
|
||||
},
|
||||
"read",
|
||||
);
|
||||
const escaped = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(root, "escape")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:escape",
|
||||
},
|
||||
"read",
|
||||
);
|
||||
expect(inside.ok).toBe(true);
|
||||
expect(escaped.ok).toBe(true);
|
||||
if (!inside.ok || !escaped.ok) return;
|
||||
expect(evaluatePermission(policy, inside.value)).toMatchObject({
|
||||
allowed: true,
|
||||
});
|
||||
expect(evaluatePermission(policy, escaped.value)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
});
|
||||
});
|
||||
|
||||
it("canonicalizes a new write through its existing parent", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-write-");
|
||||
const result = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_write",
|
||||
roots: [join(sandbox, "new.json")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "write:new.json",
|
||||
},
|
||||
"write",
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
if (result.ok)
|
||||
expect(result.value.roots).toEqual([join(sandbox, "new.json")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission authority policy and connection lifecycle", () => {
|
||||
it("commits a configured policy only after every grant validates", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-reload-");
|
||||
const oldRoot = join(sandbox, "old");
|
||||
const newRoot = join(sandbox, "new");
|
||||
const outsideRoot = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(oldRoot), mkdir(newRoot), mkdir(outsideRoot)]);
|
||||
const oldScope = evidenceScope(oldRoot);
|
||||
const newScope = evidenceScope(newRoot);
|
||||
const authority = await createPermissionAuthority(
|
||||
[oldScope],
|
||||
[administratorGrant(oldScope)],
|
||||
);
|
||||
expect(authority.ok).toBe(true);
|
||||
if (!authority.ok) return;
|
||||
|
||||
const reloaded = await authority.value.replaceConfiguredPolicy({
|
||||
ceilings: [newScope],
|
||||
administratorGrants: [administratorGrant(newScope)],
|
||||
projectGrants: [
|
||||
{
|
||||
...evidenceScope(outsideRoot),
|
||||
grant_id: "project:outside-ceiling",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(reloaded.ok).toBe(false);
|
||||
expect(await canRead(authority.value, oldRoot)).toBe(true);
|
||||
expect(await canRead(authority.value, newRoot)).toBe(false);
|
||||
|
||||
expect(
|
||||
await authority.value.replaceConfiguredPolicy({
|
||||
ceilings: [newScope],
|
||||
administratorGrants: [administratorGrant(newScope)],
|
||||
projectGrants: [],
|
||||
}),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await canRead(authority.value, oldRoot)).toBe(false);
|
||||
expect(await canRead(authority.value, newRoot)).toBe(true);
|
||||
});
|
||||
|
||||
it("isolates transient grants and consumption between live connections", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-session-");
|
||||
const scope = evidenceScope(sandbox);
|
||||
const configured = await createPermissionAuthority([scope]);
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) return;
|
||||
const connectionA = configured.value.createConnectionAuthority();
|
||||
const connectionB = configured.value.createConnectionAuthority();
|
||||
const request = {
|
||||
...scope,
|
||||
operation_identity: "read:connection-owned",
|
||||
};
|
||||
|
||||
expect(
|
||||
connectionA.grant({
|
||||
...request,
|
||||
grant_id: "session:a",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await connectionA.authorize(request, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(await connectionB.authorize(request, "read")).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
|
||||
connectionB.clearSessionGrants();
|
||||
expect(await connectionA.authorize(request, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
|
||||
connectionA.clearSessionGrants();
|
||||
const onceRequest = {
|
||||
...request,
|
||||
operation_identity: "read:once-on-a",
|
||||
};
|
||||
expect(
|
||||
connectionA.grant({
|
||||
...onceRequest,
|
||||
grant_id: "once:a",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
connectionB.grant({
|
||||
...onceRequest,
|
||||
grant_id: "once:a",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
const concurrent = await Promise.all([
|
||||
connectionA.authorize(onceRequest, "read"),
|
||||
connectionA.authorize(onceRequest, "read"),
|
||||
]);
|
||||
expect(concurrent.filter(({ ok }) => ok)).toHaveLength(1);
|
||||
expect(await connectionB.authorize(onceRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission authority policy reload", () => {
|
||||
it("applies configured policy reloads to existing connections", async () => {
|
||||
const sandbox = await createTestTempDirectory(
|
||||
"rea-permission-live-reload-",
|
||||
);
|
||||
const allowedRoot = join(sandbox, "allowed");
|
||||
const replacementRoot = join(sandbox, "replacement");
|
||||
await Promise.all([mkdir(allowedRoot), mkdir(replacementRoot)]);
|
||||
const configured = await createPermissionAuthority([
|
||||
evidenceScope(allowedRoot),
|
||||
]);
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) return;
|
||||
const connection = configured.value.createConnectionAuthority();
|
||||
expect(
|
||||
connection.grant({
|
||||
...evidenceScope(allowedRoot),
|
||||
grant_id: "session:before-reload",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await canRead(connection, allowedRoot)).toBe(true);
|
||||
|
||||
const collisionRequest = {
|
||||
...evidenceScope(allowedRoot),
|
||||
operation_identity: "read:reload-collision",
|
||||
};
|
||||
expect(
|
||||
connection.grant({
|
||||
...collisionRequest,
|
||||
grant_id: "shared-id",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(
|
||||
await configured.value.replaceAdministratorGrants([
|
||||
{
|
||||
...evidenceScope(allowedRoot),
|
||||
grant_id: "shared-id",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
]),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
await configured.value.reload([evidenceScope(replacementRoot)]),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await canRead(connection, allowedRoot)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const evidenceScope = (root: string): PermissionScope => ({
|
||||
capability: "evidence_read",
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
});
|
||||
|
||||
const administratorGrant = (scope: PermissionScope): PermissionGrant => ({
|
||||
...scope,
|
||||
grant_id: "administrator:evidence_read",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
|
||||
const canRead = async (
|
||||
authority: PermissionAuthority,
|
||||
root: string,
|
||||
): Promise<boolean> =>
|
||||
(
|
||||
await authority.explain(
|
||||
{
|
||||
...evidenceScope(root),
|
||||
operation_identity: `read:${root}`,
|
||||
},
|
||||
"read",
|
||||
)
|
||||
).ok;
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDerivedOperation } from "../../../src/server/runDerivedOperation.js";
|
||||
|
||||
const context = (
|
||||
controller: AbortController,
|
||||
notifications: unknown[] = [],
|
||||
) => ({
|
||||
mcpReq: {
|
||||
signal: controller.signal,
|
||||
_meta: { progressToken: "derived-test" },
|
||||
notify: (notification: unknown) => {
|
||||
notifications.push(notification);
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
describe("derived MCP operation boundary", () => {
|
||||
it("cancels before computation and never evaluates the operation", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
let computed = false;
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
computed = true;
|
||||
return "impossible";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(computed).toBe(false);
|
||||
});
|
||||
|
||||
it("lets cancellation win immediately before result publication", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = await runDerivedOperation(
|
||||
context(controller),
|
||||
"compare",
|
||||
() => {
|
||||
controller.abort();
|
||||
return "must-not-publish";
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("emits bounded monotonic progress with one terminal state", async () => {
|
||||
const controller = new AbortController();
|
||||
const notifications: Array<{
|
||||
params?: { progress?: number; total?: number };
|
||||
}> = [];
|
||||
const result = await runDerivedOperation(
|
||||
context(controller, notifications),
|
||||
"compare",
|
||||
() => "complete",
|
||||
);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: "complete" });
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
|
||||
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("projects synchronous computation failures into a typed result", async () => {
|
||||
const result = await runDerivedOperation(
|
||||
context(new AbortController()),
|
||||
"compare_artifacts",
|
||||
() => {
|
||||
throw new TypeError("malformed comparison evidence");
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
operation: "compare_artifacts",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../../src/domain/electronActiveObservation.fixture.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraReferenceEdge,
|
||||
} from "../../fixtures/ghidraFunction.js";
|
||||
} from "../../../src/domain/hopperValues.fixture.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../src/contracts/mana
|
||||
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
|
||||
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
|
||||
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
it("opens a managed PE and executes the managed static provider through MCP", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-mcp-");
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
containsProcess,
|
||||
getDescendants,
|
||||
maxTreeDepth,
|
||||
reconstructProcessTree,
|
||||
type ProcessTreeEvent,
|
||||
type ProcessEventType,
|
||||
type ProcessNode,
|
||||
type ProcessTreeReconstruction,
|
||||
} from "../../../src/domain/eventProcessTree.js";
|
||||
|
||||
describe("event-backed process tree reconstruction", () => {
|
||||
it("reconstructs a simple process tree", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 3,
|
||||
at_ms: 30,
|
||||
type: "exit",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.processes).toHaveLength(2);
|
||||
expect(result.events_consumed).toBe(4);
|
||||
expect(result.events_unmatched).toBe(0);
|
||||
expect(result.short_lived_descendants).toBe(2);
|
||||
});
|
||||
|
||||
it("detects short-lived descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: "/short",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 11,
|
||||
type: "exit",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "short",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.short_lived_descendants).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree transitions", () => {
|
||||
it("detects re-exec", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "re_exec",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/newroot",
|
||||
arguments: ["--new"],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_re_exec).toBe(true);
|
||||
const root = result.processes.find((p) => p.pid === 1)!;
|
||||
expect(root.is_re_exec).toBe(true);
|
||||
expect(root.executable).toBe("/newroot");
|
||||
});
|
||||
|
||||
it("detects reparenting", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/child",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "reparent",
|
||||
pid: 2,
|
||||
ppid: 0,
|
||||
process_name: "child",
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: 1,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.has_reparenting).toBe(true);
|
||||
const child = result.processes.find((p) => p.pid === 2)!;
|
||||
expect(child.is_reparented).toBe(true);
|
||||
expect(child.previous_ppid).toBe(1);
|
||||
expect(child.ppid).toBe(0);
|
||||
});
|
||||
|
||||
it("reports unmatched events for unknown exits", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "exit",
|
||||
pid: 999,
|
||||
ppid: null,
|
||||
process_name: null,
|
||||
executable: null,
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: 1,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(result.events_unmatched).toBe(1);
|
||||
expect(result.processes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree queries", () => {
|
||||
it("gets descendants", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child1",
|
||||
executable: "/c1",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "grandchild",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
const descendants = getDescendants(result.processes, 1);
|
||||
expect(descendants).toHaveLength(2);
|
||||
expect(descendants).toContain(2);
|
||||
expect(descendants).toContain(3);
|
||||
});
|
||||
|
||||
it("checks process containment", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(containsProcess(result.processes, 1)).toBe(true);
|
||||
expect(containsProcess(result.processes, 999)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-backed process tree depth and types", () => {
|
||||
it("computes max tree depth", () => {
|
||||
const events: ProcessTreeEvent[] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
type: "spawn",
|
||||
pid: 1,
|
||||
ppid: 0,
|
||||
process_name: "root",
|
||||
executable: "/root",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
type: "spawn",
|
||||
pid: 2,
|
||||
ppid: 1,
|
||||
process_name: "child",
|
||||
executable: "/c",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
{
|
||||
sequence: 2,
|
||||
at_ms: 20,
|
||||
type: "spawn",
|
||||
pid: 3,
|
||||
ppid: 2,
|
||||
process_name: "gc",
|
||||
executable: "/gc",
|
||||
arguments: [],
|
||||
previous_pid: null,
|
||||
previous_ppid: null,
|
||||
exit_code: null,
|
||||
signal: null,
|
||||
tid: null,
|
||||
},
|
||||
];
|
||||
const result = reconstructProcessTree(events, 1);
|
||||
expect(maxTreeDepth(result.processes, 1)).toBe(2);
|
||||
});
|
||||
|
||||
it("uses exported types", () => {
|
||||
const node: ProcessNode = {
|
||||
pid: 1,
|
||||
ppid: null,
|
||||
process_name: "test",
|
||||
executable: "/test",
|
||||
arguments: [],
|
||||
children: [],
|
||||
spawn_time_ms: 0,
|
||||
exit_time_ms: null,
|
||||
exit_code: null,
|
||||
is_re_exec: false,
|
||||
is_reparented: false,
|
||||
previous_ppid: null,
|
||||
};
|
||||
expect(node.pid).toBe(1);
|
||||
const recon: ProcessTreeReconstruction = {
|
||||
root_pid: 1,
|
||||
processes: [node],
|
||||
events_consumed: 1,
|
||||
events_unmatched: 0,
|
||||
short_lived_descendants: 0,
|
||||
has_re_exec: false,
|
||||
has_reparenting: false,
|
||||
};
|
||||
expect(recon.root_pid).toBe(1);
|
||||
});
|
||||
|
||||
it("uses ProcessEventType", () => {
|
||||
const t: ProcessEventType = "spawn";
|
||||
expect(t).toBe("spawn");
|
||||
});
|
||||
});
|
||||
@@ -1,197 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "../../fixtures/processCapture.js";
|
||||
|
||||
it("classifies missing observations as unknown and one-sided evidence as added", () => {
|
||||
const base = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const added = compareProcessCaptures(base, {
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
columns: 3,
|
||||
rows: 1,
|
||||
cursor_x: 3,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["new"],
|
||||
serialized_state: "new",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(added.terminal).toBe("added");
|
||||
expect(added.status).toBe("changed");
|
||||
const unknown = compareProcessCaptures(
|
||||
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
|
||||
base,
|
||||
);
|
||||
expect(unknown.process).toBe("unknown");
|
||||
expect(unknown.shim).toBe("unchanged");
|
||||
expect(unknown.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("treats equivalent normalization records as equal regardless of member order", () => {
|
||||
const capture = emptyCapture();
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
normalization: {
|
||||
patterns: [],
|
||||
time_bucket_ms: 10,
|
||||
ports: true,
|
||||
pids: true,
|
||||
paths: true,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
first_divergence: { status: "none" },
|
||||
});
|
||||
});
|
||||
|
||||
it("compares raw terminal chunks even when rendered states agree", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "bar" }],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "foo\rbar" }],
|
||||
});
|
||||
expect(comparison.terminal).toBe("changed");
|
||||
expect(comparison.first_divergence).toMatchObject({
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps filesystem evidence unknown when stable snapshots match", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [
|
||||
{ scope: "filesystem" as const, reason: "watcher unavailable" },
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, capture);
|
||||
expect(comparison.filesystem).toBe("unknown");
|
||||
expect(comparison.status).toBe("unknown");
|
||||
|
||||
const complete = { ...capture, residual_unknowns: [] };
|
||||
const transient = compareProcessCaptures(complete, {
|
||||
...complete,
|
||||
filesystem_checkpoints: [
|
||||
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
|
||||
{
|
||||
name: "during_run",
|
||||
at_ms: 10,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
{
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(transient.filesystem).toBe("changed");
|
||||
expect(transient.status).toBe("changed");
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import { processCaptureIssues } from "../../fixtures/processCapture.js";
|
||||
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
|
||||
|
||||
type EventSource = "process" | "filesystem" | "http" | "websocket" | "shim";
|
||||
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "../../../src/application/FilesystemSnapshot.js";
|
||||
import {
|
||||
buildCaptureResult,
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "../../../src/application/ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "../../../src/application/ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "../../../src/application/ProcessNormalization.js";
|
||||
import {
|
||||
isInitializedPtyRoot,
|
||||
readLinuxChildren,
|
||||
} from "../../../src/application/ProcessSampling.js";
|
||||
import { TerminalRenderer } from "../../../src/application/TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import { emptyProcessCapture as emptyCapture } from "../../fixtures/processCapture.js";
|
||||
|
||||
const base = {
|
||||
approved: true as const,
|
||||
executable: "/bin/sh",
|
||||
working_directory: "/tmp",
|
||||
};
|
||||
|
||||
it("returns detached terminal and filesystem checkpoint observations", async () => {
|
||||
const observed: string[] = [];
|
||||
const renderer = new TerminalRenderer({
|
||||
columns: 40,
|
||||
rows: 12,
|
||||
scrollback: 100,
|
||||
maxFrames: 10,
|
||||
maxBytes: 10_000,
|
||||
normalize: (value) => value,
|
||||
recordEvent: (collection, index) =>
|
||||
observed.push(`${collection}:${String(index)}`),
|
||||
});
|
||||
renderer.write("A", 20);
|
||||
renderer.resize(40, 12, 10);
|
||||
const frames = await renderer.frames();
|
||||
expect(frames.map(({ at_ms }) => at_ms)).toEqual([20, 10]);
|
||||
expect(observed).toEqual(["rendered_frames:0", "rendered_frames:1"]);
|
||||
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
|
||||
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
|
||||
await renderer.dispose();
|
||||
|
||||
const scenario = parseProcessScenario(base);
|
||||
const checkpoints = new ProcessCheckpoints(
|
||||
scenario,
|
||||
Date.now(),
|
||||
{ files: [], truncated: false },
|
||||
{ signal: undefined },
|
||||
);
|
||||
const first = await checkpoints.finish({ files: [], truncated: false });
|
||||
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
|
||||
const second = await checkpoints.finish({ files: [], truncated: false });
|
||||
expect(second[0]?.name).toBe("before");
|
||||
await checkpoints.dispose();
|
||||
});
|
||||
|
||||
it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
const capture = emptyCapture();
|
||||
const renderedFrames: ProcessCapture["rendered_frames"] = [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 20,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["first"],
|
||||
serialized_state: "first",
|
||||
},
|
||||
{
|
||||
sequence: 1,
|
||||
at_ms: 10,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["second"],
|
||||
serialized_state: "second",
|
||||
},
|
||||
];
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
replay: {
|
||||
httpUrl: "http://127.0.0.1",
|
||||
websocketUrl: "ws://127.0.0.1/ws",
|
||||
events: [],
|
||||
transitions: [],
|
||||
truncated: false,
|
||||
close: () => Promise.resolve(),
|
||||
},
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario(base),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames,
|
||||
interactions: [],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
shimEvents: [],
|
||||
settlement: {
|
||||
state: capture.settlement.state,
|
||||
elapsed_ms: capture.settlement.elapsed_ms,
|
||||
},
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
{
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
const samples = normalizeProcessSamples(
|
||||
[
|
||||
{
|
||||
at_ms: 0,
|
||||
pid: 101,
|
||||
parent_pid: 0,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "root 101",
|
||||
},
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 202,
|
||||
parent_pid: 101,
|
||||
process_group_id: 101,
|
||||
session_id: 101,
|
||||
command: "child 202 peer=101 unrelated 1202",
|
||||
},
|
||||
],
|
||||
parseProcessScenario(base),
|
||||
101,
|
||||
);
|
||||
|
||||
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
|
||||
});
|
||||
|
||||
it("collects and deduplicates children from every Linux thread", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
expect(
|
||||
await readLinuxChildren(100, signal, {
|
||||
taskIds: () => Promise.resolve([100, 101, 102]),
|
||||
children: (_pid, taskId) =>
|
||||
Promise.resolve(
|
||||
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
|
||||
),
|
||||
}),
|
||||
).toEqual([201, 202, 203]);
|
||||
});
|
||||
|
||||
it("admits PTY samples only after stable session and token setup", () => {
|
||||
const initialized = {
|
||||
pid: 100,
|
||||
parent_pid: 10,
|
||||
process_group_id: 100,
|
||||
session_id: 100,
|
||||
startTime: "200",
|
||||
};
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, process_group_id: 10, session_id: 10 },
|
||||
observedRunId: undefined,
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, startTime: "201" },
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: initialized,
|
||||
observedRunId: "run-token",
|
||||
after: initialized,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isInitializedPtyRoot({
|
||||
rootPid: 100,
|
||||
expectedRunId: "run-token",
|
||||
before: { ...initialized, session_id: null },
|
||||
observedRunId: "run-token",
|
||||
after: { ...initialized, session_id: null },
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
|
||||
const baseCapture = emptyCapture();
|
||||
const interaction = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [
|
||||
{ scope: "interaction", reason: "Interaction capture was partial." },
|
||||
],
|
||||
});
|
||||
const shim = parseProcessCapture({
|
||||
...baseCapture,
|
||||
residual_unknowns: [{ scope: "shim", reason: "Shim capture was partial." }],
|
||||
});
|
||||
|
||||
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unknown",
|
||||
shim: "unchanged",
|
||||
});
|
||||
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
|
||||
status: "unknown",
|
||||
terminal: "unchanged",
|
||||
interaction: "unchanged",
|
||||
shim: "unknown",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels filesystem snapshots before traversing declared roots", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_roots: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
});
|
||||
|
||||
it("parses bounded scenarios and rejects unordered events", () => {
|
||||
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [
|
||||
{ type: "input", at_ms: 2, data: "a" },
|
||||
{ type: "input", at_ms: 1, data: "b" },
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/unsafe" },
|
||||
}),
|
||||
).toThrow(/reserved/);
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 31_000, data: "late" }],
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
|
||||
it("requires explicit operator approval for host network access", () => {
|
||||
expect(
|
||||
authorizeProcessScenario(parseProcessScenario(base), {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "none",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "host network access is not approved by operator policy",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses paths and environment outside operator policy", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
...base,
|
||||
environment: { TOKEN: "secret" },
|
||||
});
|
||||
expect(
|
||||
authorizeProcessScenario(scenario, {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "scenario requests an environment variable not allowed by policy",
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
parseProcessScenario,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import { processCaptureIssues } from "../../fixtures/processCapture.js";
|
||||
import { processCaptureIssues } from "../../../src/domain/processCapture.fixture.js";
|
||||
|
||||
function createInteractiveScenario(root: string, script: string) {
|
||||
return parseProcessScenario({
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { digestProcessCommitment } from "../../../src/domain/processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyProcessCapture as emptyCapture,
|
||||
} from "../../fixtures/processCapture.js";
|
||||
|
||||
it("detects changes in normalized process sample metadata", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 10,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: false,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
const changed = {
|
||||
...capture,
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 20,
|
||||
pid: 1,
|
||||
parent_pid: 2,
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
command: "worker",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const comparison = compareProcessCaptures(capture, changed);
|
||||
expect(comparison.process).toBe("changed");
|
||||
expect(comparison.status).toBe("changed");
|
||||
});
|
||||
|
||||
it("compares replay state transitions as protocol evidence", () => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "anonymous",
|
||||
states: [
|
||||
{ name: "anonymous" },
|
||||
{ name: "authenticated", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "login",
|
||||
from: "anonymous",
|
||||
to: "authenticated",
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
};
|
||||
const empty = emptyCapture();
|
||||
const baseline = {
|
||||
...empty,
|
||||
manifest: {
|
||||
...empty.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
};
|
||||
const transitioned = {
|
||||
...baseline,
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
transition_id: "login",
|
||||
state_before: "anonymous",
|
||||
state_after: "authenticated",
|
||||
sensitive_aliases: ["token"],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(compareProcessCaptures(baseline, transitioned)).toMatchObject({
|
||||
status: "changed",
|
||||
protocol: "added",
|
||||
});
|
||||
});
|
||||
@@ -1,283 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
parseProcessCapture,
|
||||
processCaptureSchema,
|
||||
type ProcessCaptureEventJournalEntry,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import {
|
||||
compareUnverifiedProcessCaptures as compareProcessCaptures,
|
||||
emptyUnverifiedProcessCapture as emptyCapture,
|
||||
processCaptureIssues,
|
||||
} from "../../fixtures/processCapture.js";
|
||||
|
||||
it("never considers truncated captures equivalent", () => {
|
||||
const capture = {
|
||||
schema_version: 4 as const,
|
||||
manifest: emptyCapture().manifest,
|
||||
settlement: emptyCapture().settlement,
|
||||
normalization: {
|
||||
paths: true,
|
||||
pids: true,
|
||||
ports: true,
|
||||
time_bucket_ms: 10,
|
||||
patterns: [],
|
||||
},
|
||||
frames: [],
|
||||
rendered_frames: [],
|
||||
interaction_events: [],
|
||||
exit: { code: 0, signal: null, reason: "exited" as const },
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
|
||||
shim_events: [],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
reactive_run: null,
|
||||
files_before: [],
|
||||
files_after: [],
|
||||
filesystem_effects: [],
|
||||
truncated: true,
|
||||
limitations: [],
|
||||
residual_unknowns: [],
|
||||
cleanup: {
|
||||
owned_process_group: "verified" as const,
|
||||
temporary_root: "removed" as const,
|
||||
},
|
||||
};
|
||||
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
|
||||
});
|
||||
|
||||
it("rejects altered v4 commitments and accepts canonical key reordering", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(parseProcessCapture(capture)).toEqual(capture);
|
||||
expect(digestProcessCommitment({ second: 2, first: 1 })).toBe(
|
||||
digestProcessCommitment({ first: 1, second: 2 }),
|
||||
);
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
normalization_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("normalization_sha256");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
executable_sha256: "f".repeat(64),
|
||||
},
|
||||
}),
|
||||
).toThrow("executable_sha256");
|
||||
});
|
||||
|
||||
it("rejects settlement and cleanup combinations that cannot occur", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "quiesced",
|
||||
elapsed_ms: 0,
|
||||
cleanup_outcome: "cleaned",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
expect(() =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
settlement: {
|
||||
state: "alive_at_deadline",
|
||||
elapsed_ms: 1,
|
||||
cleanup_outcome: "not_required",
|
||||
},
|
||||
}),
|
||||
).toThrow("cleanup_outcome");
|
||||
});
|
||||
|
||||
it("accepts old captures without a journal and validates complete journals", () => {
|
||||
const journal = createProcessCaptureJournal();
|
||||
const observed: ProcessCaptureEventJournalEntry[] = [];
|
||||
const unsubscribe = journal.subscribe((entry) => observed.push(entry));
|
||||
journal.recordEvent("lifecycle", 0);
|
||||
const settlementEntry = journal.record("lifecycle", 1);
|
||||
unsubscribe();
|
||||
journal.recordEvent("frames", 0);
|
||||
expect(journal.entries).toEqual([
|
||||
{ capture_order: 0, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 2, collection: "frames", index: 0 },
|
||||
]);
|
||||
expect(observed).toEqual(journal.entries.slice(0, 2));
|
||||
expect(settlementEntry).toEqual(journal.entries[1]);
|
||||
|
||||
const nestedJournal = createProcessCaptureJournal();
|
||||
const notifications: string[] = [];
|
||||
nestedJournal.subscribe((entry) => {
|
||||
notifications.push(`a:${String(entry.capture_order)}`);
|
||||
if (entry.capture_order === 0) nestedJournal.record("frames", 1);
|
||||
});
|
||||
nestedJournal.subscribe((entry) =>
|
||||
notifications.push(`b:${String(entry.capture_order)}`),
|
||||
);
|
||||
nestedJournal.record("frames", 0);
|
||||
expect(notifications).toEqual(["a:0", "b:0", "a:1", "b:1"]);
|
||||
|
||||
const capture = emptyCapture();
|
||||
const { event_journal: _eventJournal, ...oldCapture } = capture;
|
||||
expect(parseProcessCapture(oldCapture).event_journal).toEqual([]);
|
||||
|
||||
const eventJournal = [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
] as const;
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: eventJournal }),
|
||||
).toEqual([]);
|
||||
|
||||
for (const [candidate, message] of [
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 1 ? { ...entry, capture_order: 2 } : entry,
|
||||
),
|
||||
"contiguous",
|
||||
],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3
|
||||
? { ...entry, collection: "lifecycle" as const, index: 1 }
|
||||
: entry,
|
||||
),
|
||||
"unique",
|
||||
],
|
||||
[eventJournal.slice(0, 3), "every captured observation"],
|
||||
[
|
||||
eventJournal.map((entry, index) =>
|
||||
index === 3 ? { ...entry, index: 2 } : entry,
|
||||
),
|
||||
"outside",
|
||||
],
|
||||
] as const) {
|
||||
expect(
|
||||
processCaptureIssues({ ...capture, event_journal: candidate }),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining(message),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["machine limit", 1, 5, 10],
|
||||
["transition use limit", 5, 1, 10],
|
||||
["state visit limit", 5, 5, 1],
|
||||
])(
|
||||
"rejects replay journals that exceed the declared %s",
|
||||
(_name, maxTransitions, maxUses, maxVisits) => {
|
||||
const replayPlan = {
|
||||
machine: {
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: maxVisits },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "again",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "again",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "again" }],
|
||||
max_uses: maxUses,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "complete",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/ws",
|
||||
body: "finish",
|
||||
},
|
||||
actions: [{ type: "websocket_send", data: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: maxTransitions,
|
||||
},
|
||||
};
|
||||
const capture = emptyCapture();
|
||||
const candidate: UnverifiedProcessCapture = {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
replay_plan: replayPlan,
|
||||
replay_plan_sha256: digestProcessCommitment(replayPlan),
|
||||
},
|
||||
replay_transitions: [0, 1].map((sequence) => ({
|
||||
sequence,
|
||||
at_ms: sequence,
|
||||
transition_id: "again",
|
||||
state_before: "active",
|
||||
state_after: "active",
|
||||
sensitive_aliases: [],
|
||||
})),
|
||||
};
|
||||
|
||||
expect(processCaptureIssues(candidate)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
message: expect.stringContaining("limit"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("tells agents and users to recapture unsupported v3 evidence", () => {
|
||||
const legacy = { ...emptyCapture(), schema_version: 3 };
|
||||
expect(() => parseProcessCapture(legacy)).toThrow(
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
);
|
||||
const parsed = processCaptureSchema.safeParse(legacy);
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected legacy capture rejection");
|
||||
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
});
|
||||
|
||||
it("requires compatible contracts and enforces capture age through a clock seam", () => {
|
||||
const capture = emptyCapture();
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, {
|
||||
...capture,
|
||||
manifest: {
|
||||
...capture.manifest,
|
||||
comparison_contract: { changed: true },
|
||||
comparison_contract_sha256: digestProcessCommitment({
|
||||
changed: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
).toThrow("incompatible comparison contracts");
|
||||
expect(() =>
|
||||
compareProcessCaptures(capture, capture, {
|
||||
maxCaptureAgeMs: 1,
|
||||
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
|
||||
}),
|
||||
).toThrow("max_capture_age_ms");
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import {
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
import {
|
||||
createProcessObservation,
|
||||
projectProcessObservation,
|
||||
} from "../../../src/domain/processObservation.js";
|
||||
|
||||
const emptyCapture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
|
||||
const capture: UnverifiedProcessCapture = {
|
||||
...emptyCapture,
|
||||
frames: [{ sequence: 0, at_ms: 1, data: "Ready" }],
|
||||
rendered_frames: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
columns: 80,
|
||||
rows: 24,
|
||||
cursor_x: 0,
|
||||
cursor_y: 0,
|
||||
active_buffer: "normal",
|
||||
lines: ["Ready"],
|
||||
serialized_state: "Ready",
|
||||
},
|
||||
],
|
||||
interaction_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 2,
|
||||
dispatched_at_ms: 3,
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
],
|
||||
process_samples: [
|
||||
{
|
||||
at_ms: 4,
|
||||
pid: 2,
|
||||
parent_pid: 1,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
},
|
||||
],
|
||||
shim_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 5,
|
||||
command: "helper",
|
||||
route_index: 0,
|
||||
arguments: [],
|
||||
working_directory: "/fixture",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
protocol_events: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 6,
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: "/done",
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
replay_transitions: [
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 7,
|
||||
transition_id: "done",
|
||||
state_before: "open",
|
||||
state_after: "closed",
|
||||
sensitive_aliases: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("process observation vocabulary", () => {
|
||||
it("projects every capture collection without timestamp sorting", () => {
|
||||
const locations = [
|
||||
{ collection: "frames", index: 0, capture_order: 4 },
|
||||
{ collection: "rendered_frames", index: 0, capture_order: 3 },
|
||||
{ collection: "interaction_events", index: 0, capture_order: 2 },
|
||||
{ collection: "lifecycle", index: 0, capture_order: 8 },
|
||||
{ collection: "lifecycle", index: 1, capture_order: 9 },
|
||||
{ collection: "process_samples", index: 0, capture_order: 1 },
|
||||
{ collection: "filesystem_checkpoints", index: 0, capture_order: 0 },
|
||||
{ collection: "shim_events", index: 0, capture_order: 5 },
|
||||
{ collection: "protocol_events", index: 0, capture_order: 6 },
|
||||
{ collection: "replay_transitions", index: 0, capture_order: 7 },
|
||||
] as const;
|
||||
const observations = locations.map((location) =>
|
||||
projectProcessObservation(capture, location),
|
||||
);
|
||||
|
||||
expect(observations.map((value) => value?.source)).toEqual([
|
||||
"terminal_raw",
|
||||
"terminal_rendered",
|
||||
"interaction",
|
||||
"lifecycle",
|
||||
"lifecycle",
|
||||
"process",
|
||||
"filesystem",
|
||||
"shim",
|
||||
"http",
|
||||
"replay_transition",
|
||||
]);
|
||||
expect(observations.map((value) => value?.capture_order)).toEqual(
|
||||
locations.map(({ capture_order }) => capture_order),
|
||||
);
|
||||
expect(observations[5]).toMatchObject({
|
||||
event_id: "obs.process_samples.0",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 4,
|
||||
subject_id: "process:2",
|
||||
});
|
||||
expect(observations[7]).toMatchObject({
|
||||
event_id: "obs.shim_events.0",
|
||||
subject_id: "shim:helper:route:0",
|
||||
});
|
||||
expect(observations[3]?.captured_at_ms).toBeNull();
|
||||
expect(observations[4]?.captured_at_ms).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the same constructor for live and post-hoc observations", () => {
|
||||
const location = {
|
||||
collection: "frames" as const,
|
||||
index: 0,
|
||||
capture_order: 4,
|
||||
};
|
||||
const projected = projectProcessObservation(capture, location);
|
||||
const live = createProcessObservation({
|
||||
source: "terminal_raw",
|
||||
source_sequence: 0,
|
||||
captured_at_ms: 1,
|
||||
subject_id: null,
|
||||
location,
|
||||
payload: capture.frames[0],
|
||||
});
|
||||
expect(live).toEqual(projected);
|
||||
});
|
||||
|
||||
it("returns no observation for a missing raw record", () => {
|
||||
expect(
|
||||
projectProcessObservation(capture, {
|
||||
collection: "frames",
|
||||
index: 1,
|
||||
capture_order: 10,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
parseProcessEnvironment,
|
||||
selectCapturedProcessGroupIds,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
import { matchesOwnedProcessCommand } from "../../../src/process/ProcessCommandIdentity.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("excludes sampled groups whose leader was outside the captured tree", () => {
|
||||
expect(
|
||||
selectCapturedProcessGroupIds(100, [
|
||||
{ pid: 100, process_group_id: 42 },
|
||||
{ pid: 100, process_group_id: 100 },
|
||||
{ pid: 101, process_group_id: 42 },
|
||||
{ pid: 102, process_group_id: 102 },
|
||||
{ pid: 103, process_group_id: 102 },
|
||||
]),
|
||||
).toEqual([100, 102]);
|
||||
});
|
||||
it("drops nameless Linux environment entries", () => {
|
||||
expect(
|
||||
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
|
||||
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
|
||||
});
|
||||
it("matches macOS executable names after process-table normalization", () => {
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "darwin"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/python/bin/python3",
|
||||
"darwin",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand(
|
||||
"node /tmp/fake-launcher.mjs",
|
||||
"/opt/node/bin/node",
|
||||
"linux",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
matchesOwnedProcessCommand("(node)", "/opt/node/bin/node", "linux"),
|
||||
).toBe(false);
|
||||
});
|
||||
it("signals only a group whose every member carries the run token", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("validates and signals rooted descendant groups once, root first", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100 },
|
||||
{ pid: 110, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
{ pid: 103, parentPid: 102, processGroupId: 102 },
|
||||
].map((process) => ({
|
||||
...process,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
}));
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
[102, "SIGKILL"],
|
||||
]);
|
||||
});
|
||||
it("leaves an unrelated Hopper process group outside the rooted tree untouched", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "rea-hopper" },
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101, command: "owned-child" },
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command:
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/Hopper Disassembler",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{ cleaned: true, signaled: true },
|
||||
);
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[101, "SIGKILL"],
|
||||
]);
|
||||
expect(environment.mock.calls.some(([pid]) => pid === 900)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,212 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
verifyNoTokenOwnedProcesses,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("signals token-owned groups that were reparented outside the launcher tree", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-helper",
|
||||
},
|
||||
{
|
||||
pid: 901,
|
||||
parentPid: 900,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-worker",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(
|
||||
{ ...ownership, sweepTokenOwnedProcesses: true },
|
||||
adapter,
|
||||
),
|
||||
).resolves.toEqual({ cleaned: true, signaled: true });
|
||||
expect(signalGroup.mock.calls.map(([groupId]) => groupId)).toEqual([
|
||||
100, 900,
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails closed when a token-owned process remains after cleanup", async () => {
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
state: "S",
|
||||
command: "detached-helper",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
|
||||
await expect(
|
||||
verifyNoTokenOwnedProcesses("run-token", adapter),
|
||||
).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason: "token-owned process remained after cleanup",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("fails before signaling when any descendant-group member is unowned", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
{
|
||||
pid: 104,
|
||||
parentPid: 101,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-helper",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 104 ? "other-run" : "run-token",
|
||||
}),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 104, reason: "run-token-mismatch" }],
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails before signaling when a descendant group leader is not rooted", async () => {
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 105,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "descendant",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 999,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "unrelated-group-leader",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: false,
|
||||
reason:
|
||||
"descendant process-group leader identity could not be verified",
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("records sorted launcher and descendant lineage after token checks", async () => {
|
||||
const { adapter } = host({
|
||||
102: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 100 },
|
||||
{ pid: 102, parentPid: 100, processGroupId: 100 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,72 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
describe("owned process-group cleanup discovery", () => {
|
||||
it("walks the PPID tree across process-group boundaries", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 103 ? "unrelated-run" : "run-token",
|
||||
}),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 103,
|
||||
parentPid: 999,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "unrelated-same-group",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
parentPid: 101,
|
||||
processGroupId: 102,
|
||||
state: "S",
|
||||
command: "grandchild-session",
|
||||
},
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-group",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "verified",
|
||||
observedAt: expect.any(String),
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 101 },
|
||||
{ pid: 102, parentPid: 101, processGroupId: 102 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
});
|
||||
});
|
||||
@@ -1,165 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessLineage,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("fails closed when a descendant in another process group lacks the token", async () => {
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 101,
|
||||
state: "S",
|
||||
command: "child-session",
|
||||
},
|
||||
]),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 100 ? "run-token" : "other-run",
|
||||
}),
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("does not publish lineage when any member fails ownership checks", async () => {
|
||||
const { adapter } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "other-run" },
|
||||
});
|
||||
await expect(
|
||||
observeOwnedProcessLineage(ownership, adapter),
|
||||
).resolves.toEqual({
|
||||
status: "unavailable",
|
||||
observedAt: expect.any(String),
|
||||
runId: "run-token",
|
||||
launcherPid: 100,
|
||||
processGroupId: 100,
|
||||
reason: "process lineage contains an unowned or PID-reused process",
|
||||
});
|
||||
});
|
||||
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
101: { REA_PROCESS_RUN_ID: "different-run" },
|
||||
});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [{ pid: 101, reason: "run-token-mismatch" }],
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("checks every member and aggregates ownership read failures", async () => {
|
||||
const environment = vi.fn((pid: number) => {
|
||||
if (pid === 100)
|
||||
return Promise.reject(new Error("transient procfs read"));
|
||||
return Promise.resolve(
|
||||
pid === 101
|
||||
? { REA_PROCESS_RUN_ID: "different-run" }
|
||||
: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
);
|
||||
});
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
[100, 101, 102].map((pid) => ({
|
||||
pid,
|
||||
parentPid: pid === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures: [
|
||||
{ pid: 100, reason: "environment-unreadable" },
|
||||
{ pid: 101, reason: "run-token-mismatch" },
|
||||
],
|
||||
});
|
||||
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("accepts a member that exits during ownership revalidation", async () => {
|
||||
const liveLauncher = {
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
};
|
||||
const listProcesses = vi
|
||||
.fn<ProcessOwnershipHost["listProcesses"]>()
|
||||
.mockResolvedValueOnce([liveLauncher])
|
||||
.mockResolvedValue([]);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses,
|
||||
environment: () =>
|
||||
Promise.reject(new Error("process exited before environment read")),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
|
||||
{
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
},
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,134 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
observeOwnedProcessGroup,
|
||||
type ProcessOwnershipHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
const ownership = {
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
};
|
||||
const host = (
|
||||
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
|
||||
): {
|
||||
readonly adapter: ProcessOwnershipHost;
|
||||
readonly signalGroup: ReturnType<typeof vi.fn>;
|
||||
} => {
|
||||
const signalGroup = vi.fn();
|
||||
return {
|
||||
adapter: {
|
||||
listProcesses: () =>
|
||||
Promise.resolve(
|
||||
Object.keys(environments).map((pid) => ({
|
||||
pid: Number(pid),
|
||||
parentPid: Number(pid) === 100 ? 1 : 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
})),
|
||||
),
|
||||
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
|
||||
signalGroup,
|
||||
},
|
||||
signalGroup,
|
||||
};
|
||||
};
|
||||
describe("owned process-group cleanup validation", () => {
|
||||
it("ignores exited zombie members during live ownership checks", async () => {
|
||||
const environment = vi.fn((pid: number) =>
|
||||
Promise.resolve(pid === 101 ? {} : { REA_PROCESS_RUN_ID: "run-token" }),
|
||||
);
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "fixture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "Z",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup,
|
||||
};
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
expect(environment.mock.calls).toEqual([[100], [100]]);
|
||||
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
|
||||
});
|
||||
it("observes a zombie-only group as settled", async () => {
|
||||
const environment = vi.fn(() => Promise.resolve({}));
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "Z+",
|
||||
command: "[node] <defunct>",
|
||||
},
|
||||
]),
|
||||
environment,
|
||||
signalGroup: vi.fn(),
|
||||
};
|
||||
expect(await observeOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
state: "empty",
|
||||
});
|
||||
expect(environment).not.toHaveBeenCalled();
|
||||
});
|
||||
it("is idempotent when the owned group has already exited", async () => {
|
||||
const { adapter } = host({});
|
||||
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("fails closed when the launcher command identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
expectedCommand: "/owned/hopper",
|
||||
expectedParentPid: 1,
|
||||
},
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"owned launcher command identity did not match (observed=fixture; expected=/owned/hopper)",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails closed when the launcher parent identity changes", async () => {
|
||||
const { adapter, signalGroup } = host({
|
||||
100: { REA_PROCESS_RUN_ID: "run-token" },
|
||||
});
|
||||
expect(
|
||||
await cleanupOwnedProcessGroup(
|
||||
{ ...ownership, expectedCommand: "fixture", expectedParentPid: 999 },
|
||||
adapter,
|
||||
),
|
||||
).toEqual({
|
||||
cleaned: false,
|
||||
reason: "owned launcher parent identity did not match",
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
cleanupWindowsProcessTree,
|
||||
type WindowsProcessTreeHost,
|
||||
} from "../../../src/process/ProcessOwnership.js";
|
||||
describe("Windows P0 process-tree cleanup", () => {
|
||||
it("reports whether taskkill signaled or found an exited tree", async () => {
|
||||
const terminated: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("terminated"),
|
||||
};
|
||||
const missing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.resolve("missing"),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(42, terminated)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, missing)).resolves.toEqual({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
});
|
||||
});
|
||||
it("keeps invalid identity and termination failures explicit", async () => {
|
||||
const failing: WindowsProcessTreeHost = {
|
||||
terminateTree: () => Promise.reject(new Error("taskkill failed")),
|
||||
};
|
||||
await expect(cleanupWindowsProcessTree(0, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason: "Windows process-tree PID is invalid",
|
||||
});
|
||||
await expect(cleanupWindowsProcessTree(42, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { getEventListeners } from "node:events";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { access, mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
@@ -394,12 +393,6 @@ describe("GhidraClient cleanup and diagnostics", () => {
|
||||
expect(exited(process_)).toBe(true);
|
||||
if (process_ === undefined)
|
||||
throw new Error("Fixture process was not captured");
|
||||
expect(getEventListeners(process_, "exit")).toHaveLength(0);
|
||||
expect(getEventListeners(process_, "close")).toHaveLength(0);
|
||||
expect(getEventListeners(process_, "error")).toHaveLength(0);
|
||||
expect(process_.stdout).not.toBeNull();
|
||||
if (process_.stdout !== null)
|
||||
expect(getEventListeners(process_.stdout, "data")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("retains actionable runtime coordinates after successful cleanup", async () => {
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
runDoctor,
|
||||
type DoctorHost,
|
||||
} from "../../../../src/application/Doctor.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
type GhidraInstallationHost,
|
||||
type GhidraInstallationInspection,
|
||||
} from "../../../../src/ghidra/GhidraInstallation.js";
|
||||
import { projectGhidraDoctorInspection } from "../../../../src/ghidra/GhidraDoctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../../src/identity.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
const installationHost = (
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationHost => ({
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const inspection = (
|
||||
options: {
|
||||
readonly installDir?: string;
|
||||
readonly architecture?: NodeJS.Architecture;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
} = { installDir: INSTALL },
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationInspection =>
|
||||
inspectGhidraInstallation(
|
||||
{
|
||||
platform: options.platform ?? "linux",
|
||||
architecture: options.architecture ?? "x64",
|
||||
...(options.installDir === undefined
|
||||
? {}
|
||||
: { installDir: options.installDir }),
|
||||
},
|
||||
installationHost(overrides),
|
||||
);
|
||||
|
||||
const doctorHost = (
|
||||
ghidra: GhidraInstallationInspection,
|
||||
hopperAvailable = false,
|
||||
): DoctorHost => ({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
nodeVersion: "24.18.0",
|
||||
macosVersion: () => Promise.resolve(undefined),
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
}),
|
||||
validTarget: () => Promise.resolve(true),
|
||||
executable: (path) =>
|
||||
Promise.resolve(hopperAvailable && path.includes("Hopper")),
|
||||
supportedLinuxHopper: () => Promise.resolve(true),
|
||||
linuxDemoRuntimeCheck: () =>
|
||||
Promise.resolve({
|
||||
name: "hopper-demo-runtime",
|
||||
ok: true,
|
||||
classification: "healthy",
|
||||
}),
|
||||
brewHopperPath: () => Promise.resolve(undefined),
|
||||
manualHopperPaths: () => Promise.resolve([]),
|
||||
providerInspections: () =>
|
||||
Promise.resolve([projectGhidraDoctorInspection(ghidra)]),
|
||||
installedSkillIdentity: () =>
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
}),
|
||||
});
|
||||
|
||||
describe("Ghidra doctor integration", () => {
|
||||
it("accepts a valid BYO Ghidra engine when Hopper is absent", async () => {
|
||||
const result = await runDoctor(undefined, doctorHost(inspection()));
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.hopperPath).toBeUndefined();
|
||||
expect(result.providerInspections?.[0]).toMatchObject({
|
||||
id: "ghidra",
|
||||
available: true,
|
||||
providerVersion: "12.1.2",
|
||||
registrationEnvironment: {
|
||||
GHIDRA_INSTALL_DIR: INSTALL,
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "ghidra-java"),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
detail: expect.stringContaining("21.0.11"),
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the experimental Windows x64 Ghidra provider boundary", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.2_PUBLIC",
|
||||
platform: "win32",
|
||||
});
|
||||
const result = await runDoctor(undefined, {
|
||||
...doctorHost(ghidra),
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
});
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"bad installation",
|
||||
inspection({ installDir: INSTALL }, { readText: () => undefined }),
|
||||
"ghidra-installation",
|
||||
],
|
||||
[
|
||||
"wrong version",
|
||||
inspection(
|
||||
{ installDir: INSTALL },
|
||||
{ readText: () => "application.version=11.4\n" },
|
||||
),
|
||||
"ghidra-version",
|
||||
],
|
||||
[
|
||||
"missing analyzeHeadless",
|
||||
inspection({ installDir: INSTALL }, { executable: () => false }),
|
||||
"ghidra-headless",
|
||||
],
|
||||
[
|
||||
"wrong Java",
|
||||
inspection(
|
||||
{ installDir: INSTALL },
|
||||
{
|
||||
probeJava: () => ({
|
||||
version: "17.0.12",
|
||||
major: 17,
|
||||
home: "/usr/lib/jvm/jdk-17",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
},
|
||||
),
|
||||
"ghidra-java",
|
||||
],
|
||||
[
|
||||
"unsupported architecture",
|
||||
inspection({ installDir: INSTALL, architecture: "arm64" }),
|
||||
"ghidra-architecture",
|
||||
],
|
||||
] as const)("distinguishes %s", async (_label, ghidra, checkName) => {
|
||||
const result = await runDoctor(undefined, doctorHost(ghidra, true));
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.checks.find(({ name }) => name === checkName)).toMatchObject({
|
||||
ok: false,
|
||||
remediation: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("treats unconfigured Ghidra as optional when Hopper is healthy", async () => {
|
||||
const result = await runDoctor(undefined, doctorHost(inspection({}), true));
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: false,
|
||||
classification: "missing_analysis_engine",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,302 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { JsonValue } from "../../../../src/domain/jsonValue.js";
|
||||
import {
|
||||
GHIDRA_FUNCTION_OPERATIONS,
|
||||
isGhidraFunctionOperation,
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
type GhidraFunctionOperation,
|
||||
} from "../../../../src/ghidra/GhidraFunctionValues.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraNativeApiBoundary,
|
||||
ghidraReferenceEdge,
|
||||
} from "../../../fixtures/ghidraFunction.js";
|
||||
|
||||
describe("Ghidra function-analysis boundary values", () => {
|
||||
it("defaults bounded inputs and rejects undeclared or implicit addresses", () => {
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, procedure: "main" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_references", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
direction: "outgoing",
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
max_instructions: 500,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("analyze_function", { procedure: "main" }),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
procedure: "main",
|
||||
include_assembly: false,
|
||||
limit: 100,
|
||||
max_pseudocode_chars: 20_000,
|
||||
max_instructions: 500,
|
||||
pseudocode_offset: 0,
|
||||
assembly_offset: 0,
|
||||
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("read_function_instructions", {
|
||||
procedure: "main",
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
},
|
||||
});
|
||||
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", {
|
||||
procedure: "main",
|
||||
extra: true,
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(9);
|
||||
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("read_function_instructions")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
|
||||
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra function-analysis result values", () => {
|
||||
it("parses provider-classified function facts and reference kinds", () => {
|
||||
expect(
|
||||
parseGhidraFunctionResult("read_function_instructions", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraFunctionResult("read_function_instructions", {
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
address: "0X401000",
|
||||
},
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_info", {
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [
|
||||
{
|
||||
description: "int local @ Stack[-0x4]:4",
|
||||
provenance: "ghidra-function-database",
|
||||
},
|
||||
],
|
||||
classification: ghidraFunctionClassification(),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_references", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
data: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionResult("analyze_function", ghidraFunctionDossier()),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
native_api: {
|
||||
available: true,
|
||||
provenance: "ghidra-high-function",
|
||||
return_type: {
|
||||
data_type: "int",
|
||||
confidence: "medium",
|
||||
},
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [{ address: "0x403000" }],
|
||||
mappings: [
|
||||
{
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
pseudocode: {
|
||||
classification: "decompiler-generated-non-source",
|
||||
compilable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraFunctionResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const malformedOutputs = (): Array<
|
||||
[string, GhidraFunctionOperation, JsonValue]
|
||||
> => {
|
||||
const dossier = ghidraFunctionDossier();
|
||||
if (typeof dossier !== "object" || dossier === null || Array.isArray(dossier))
|
||||
throw new TypeError("Ghidra dossier fixture is invalid");
|
||||
const edge = ghidraReferenceEdge();
|
||||
const nativeApi = ghidraNativeApiBoundary();
|
||||
const jumpTable = nativeApi.jump_tables[0];
|
||||
const mapping = jumpTable?.mappings[0];
|
||||
if (jumpTable === undefined || mapping === undefined)
|
||||
throw new TypeError("Ghidra native API fixture is invalid");
|
||||
return [
|
||||
["non-canonical address", "procedure_callers", ["401000"]],
|
||||
[
|
||||
"missing classification",
|
||||
"procedure_info",
|
||||
{
|
||||
name: "main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 1,
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"unavailable Ghidra reference kind",
|
||||
"procedure_references",
|
||||
{
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([
|
||||
{ ...edge, kind: { available: false, reason: "unknown" } },
|
||||
]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing native API boundary",
|
||||
"analyze_function",
|
||||
Object.fromEntries(
|
||||
Object.entries(dossier).filter(([key]) => key !== "native_api"),
|
||||
),
|
||||
],
|
||||
[
|
||||
"non-canonical native API target",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
native_api: {
|
||||
...nativeApi,
|
||||
jump_tables: [
|
||||
{
|
||||
...jumpTable,
|
||||
mappings: [
|
||||
{
|
||||
...mapping,
|
||||
target_address: "401020",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"Hopper local provenance",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: null,
|
||||
locals: [
|
||||
{
|
||||
description: "opaque",
|
||||
provenance: "hopper-public-python-api",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"inconsistent dossier bound",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
instruction_scan: { scanned: -1, truncated: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing uncertainty limitations",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
];
|
||||
};
|
||||
@@ -1,223 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ghidraJavaEnvironment,
|
||||
inspectGhidraInstallation,
|
||||
SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
SUPPORTED_GHIDRA_VERSION,
|
||||
type GhidraInstallationHost,
|
||||
type GhidraJavaObservation,
|
||||
} from "../../../../src/ghidra/GhidraInstallation.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra";
|
||||
const PROPERTIES = `${INSTALL}/Ghidra/application.properties`;
|
||||
const HEADLESS = `${INSTALL}/support/analyzeHeadless`;
|
||||
const WINDOWS_INSTALL = "C:\\tools\\ghidra_12.1.2_PUBLIC";
|
||||
const WINDOWS_PROPERTIES = `${WINDOWS_INSTALL}\\Ghidra\\application.properties`;
|
||||
const WINDOWS_HEADLESS = `${WINDOWS_INSTALL}\\support\\analyzeHeadless.bat`;
|
||||
const JAVA: GhidraJavaObservation = {
|
||||
version: "21.0.11",
|
||||
major: SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
};
|
||||
|
||||
const host = (
|
||||
overrides: Partial<GhidraInstallationHost> = {},
|
||||
): GhidraInstallationHost => ({
|
||||
readText: (path) =>
|
||||
path === PROPERTIES
|
||||
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
|
||||
: undefined,
|
||||
executable: (path) => path === HEADLESS,
|
||||
probeJava: () => JAVA,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("Ghidra installation inspection", () => {
|
||||
it("clears inherited JVM option injection before probing Java", () => {
|
||||
expect(
|
||||
ghidraJavaEnvironment(
|
||||
"/opt/jdk-21",
|
||||
{
|
||||
PATH: "/usr/bin",
|
||||
_JAVA_OPTIONS: "-Xmx99G",
|
||||
JAVA_TOOL_OPTIONS: "-javaagent:/tmp/agent.jar",
|
||||
JDK_JAVA_OPTIONS: "-XX:MaxRAMPercentage=99",
|
||||
GHIDRA_JAVA_OPTIONS: "-Duser.home=/tmp/unapproved",
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toMatchObject({
|
||||
PATH: "/opt/jdk-21/bin:/usr/bin",
|
||||
JAVA_HOME: "/opt/jdk-21",
|
||||
_JAVA_OPTIONS: "",
|
||||
JAVA_TOOL_OPTIONS: "",
|
||||
JDK_JAVA_OPTIONS: "",
|
||||
GHIDRA_JAVA_OPTIONS: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts only the exact Linux x64 Ghidra and JDK commitment", () => {
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
host(),
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "available",
|
||||
providerVersion: SUPPORTED_GHIDRA_VERSION,
|
||||
analyzeHeadlessPath: HEADLESS,
|
||||
javaVersion: "21.0.11",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the exact Windows x64 batch launcher and JDK commitment", () => {
|
||||
const windowsHost: GhidraInstallationHost = {
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
readText: (path) =>
|
||||
path === WINDOWS_PROPERTIES
|
||||
? `application.version=${SUPPORTED_GHIDRA_VERSION}\n`
|
||||
: undefined,
|
||||
executable: (path) => path === WINDOWS_HEADLESS,
|
||||
probeJava: (command, environment) => {
|
||||
expect(command).toBe("C:\\Java\\jdk-21\\bin\\java.exe");
|
||||
expect(environment.PATH).toMatch(/^C:\\Java\\jdk-21\\bin;/u);
|
||||
return {
|
||||
...JAVA,
|
||||
home: "C:\\Java\\jdk-21",
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{
|
||||
installDir: WINDOWS_INSTALL,
|
||||
javaHome: "C:\\Java\\jdk-21",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
},
|
||||
windowsHost,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "available",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
analyzeHeadlessPath: WINDOWS_HEADLESS,
|
||||
javaCommand: "C:\\Java\\jdk-21\\bin\\java.exe",
|
||||
providerVersion: SUPPORTED_GHIDRA_VERSION,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra installation rejection diagnostics", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "missing configuration",
|
||||
options: { platform: "linux" as const, architecture: "x64" as const },
|
||||
override: {},
|
||||
failed: "configuration",
|
||||
code: "not_configured",
|
||||
},
|
||||
{
|
||||
name: "unsupported platform",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "darwin" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: {},
|
||||
failed: "platform",
|
||||
code: "unsupported_host",
|
||||
},
|
||||
{
|
||||
name: "unsupported architecture",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "arm64" as const,
|
||||
},
|
||||
override: {},
|
||||
failed: "architecture",
|
||||
code: "unsupported_host",
|
||||
},
|
||||
{
|
||||
name: "bad installation root",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { readText: () => undefined },
|
||||
failed: "installation",
|
||||
code: "executable_missing",
|
||||
},
|
||||
{
|
||||
name: "wrong Ghidra version",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { readText: () => "application.version=11.4\n" },
|
||||
failed: "version",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
{
|
||||
name: "missing analyzeHeadless",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { executable: () => false },
|
||||
failed: "headless",
|
||||
code: "executable_missing",
|
||||
},
|
||||
{
|
||||
name: "missing Java",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => undefined },
|
||||
failed: "java",
|
||||
code: "runtime_missing",
|
||||
},
|
||||
{
|
||||
name: "wrong Java",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => ({ ...JAVA, major: 17, version: "17" }) },
|
||||
failed: "java",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
{
|
||||
name: "JRE instead of JDK",
|
||||
options: {
|
||||
installDir: INSTALL,
|
||||
platform: "linux" as const,
|
||||
architecture: "x64" as const,
|
||||
},
|
||||
override: { probeJava: () => ({ ...JAVA, runtime: "jre" as const }) },
|
||||
failed: "java",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
])("distinguishes $name", ({ options, override, failed, code }) => {
|
||||
const result = inspectGhidraInstallation(options, host(override));
|
||||
expect(result.status).toBe("unavailable");
|
||||
expect(
|
||||
result.checks.find(({ status }) => status === "failed"),
|
||||
).toMatchObject({
|
||||
name: failed,
|
||||
code,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,232 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
GHIDRA_INVENTORY_OPERATIONS,
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
type GhidraInventoryOperation,
|
||||
} from "../../../../src/ghidra/GhidraInventoryValues.js";
|
||||
import type { JsonValue } from "../../../../src/domain/jsonValue.js";
|
||||
|
||||
describe("Ghidra inventory boundary values", () => {
|
||||
it("defaults bounded provider inputs without accepting undeclared fields", () => {
|
||||
expect(parseGhidraInventoryInput("list_procedures", {})).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, offset: 0, limit: 100 },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("search_strings", { pattern: "needle" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("list_documents", { extra: true }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(parseGhidraInventoryInput("address_name", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("procedure_address", {
|
||||
procedure: "x".repeat(4097),
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_INVENTORY_OPERATIONS).toHaveLength(10);
|
||||
expect(isGhidraInventoryOperation("list_names")).toBe(true);
|
||||
expect(isGhidraInventoryOperation("goto_address")).toBe(false);
|
||||
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses primary, dynamic, and external symbol facts", () => {
|
||||
const items = [
|
||||
{
|
||||
address: "EXTERNAL:0x1",
|
||||
value: "libc::puts",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: true,
|
||||
type: "function",
|
||||
source: "imported",
|
||||
},
|
||||
},
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "LAB_00401000",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: true,
|
||||
external: false,
|
||||
type: "label",
|
||||
source: "default",
|
||||
},
|
||||
},
|
||||
] satisfies readonly JsonValue[];
|
||||
expect(parseGhidraInventoryResult("list_names", page(items))).toEqual({
|
||||
ok: true,
|
||||
value: page(items),
|
||||
});
|
||||
});
|
||||
|
||||
it("parses thunk, string-layout, and memory-permission observations", () => {
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "0x401020",
|
||||
value: "puts",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: true,
|
||||
thunk_target: "EXTERNAL:0x1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_strings",
|
||||
page([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "fixture",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "missing",
|
||||
byte_length: 7,
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult("list_segments", [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x402000",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraInventoryResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function malformedOutputs(): Array<
|
||||
[string, GhidraInventoryOperation, JsonValue]
|
||||
> {
|
||||
return [
|
||||
[
|
||||
"non-canonical address",
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "00401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
[
|
||||
"missing external metadata",
|
||||
"list_names",
|
||||
page([{ address: "0x401000", value: "main", value_truncated: false }]),
|
||||
],
|
||||
[
|
||||
"contradictory continuation",
|
||||
"search_strings",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: false,
|
||||
next_offset: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
"non-advancing continuation",
|
||||
"list_procedures",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: true,
|
||||
next_offset: 0,
|
||||
},
|
||||
],
|
||||
[
|
||||
"items beyond exact total",
|
||||
"list_procedures",
|
||||
{ ...page([procedureItem()]), total: 0 },
|
||||
],
|
||||
["provider limit", "search_procedures", { ...page([]), limit: 101 }],
|
||||
["multiple programs", "list_documents", ["first", "second"]],
|
||||
];
|
||||
}
|
||||
|
||||
function procedureItem(): JsonValue {
|
||||
return {
|
||||
address: "0x401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function page(items: readonly JsonValue[]) {
|
||||
return {
|
||||
items: [...items],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../../src/config.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
} from "../../../../src/ghidra/GhidraProvider.js";
|
||||
import type { GhidraInstallationHost } from "../../../../src/ghidra/GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../../../../src/ghidra/GhidraSessionValues.js";
|
||||
import { err, ok } from "../../../../src/domain/result.js";
|
||||
import { GhidraSessionError } from "../../../../src/ghidra/GhidraSessionError.js";
|
||||
import { silentLogger } from "../../../../src/logger.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
const installationHost = (): GhidraInstallationHost => ({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
});
|
||||
|
||||
const provider = (
|
||||
host = installationHost(),
|
||||
clientFactory?: GhidraProviderClientFactory,
|
||||
): GhidraProvider => {
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
|
||||
if (!config.ok) throw config.error;
|
||||
return new GhidraProvider(config.value, silentLogger, host, clientFactory);
|
||||
};
|
||||
|
||||
describe("Ghidra provider", () => {
|
||||
it("discovers the exact installation once without launching Ghidra", () => {
|
||||
let probeCount = 0;
|
||||
const host: GhidraInstallationHost = {
|
||||
...installationHost(),
|
||||
probeJava: () => {
|
||||
probeCount += 1;
|
||||
return {
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
};
|
||||
},
|
||||
};
|
||||
const ghidra = provider(host);
|
||||
|
||||
expect(ghidra.identity()).toEqual(GHIDRA_PROVIDER_IDENTITY);
|
||||
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(19);
|
||||
expect(Object.isFrozen(ghidra.capabilities())).toBe(true);
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
pagination: "offset",
|
||||
effects: expect.objectContaining({
|
||||
mutatesArtifact: false,
|
||||
mayShowUi: false,
|
||||
mayWriteFilesystem: true,
|
||||
}),
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
operation: "analyze_function",
|
||||
pagination: "offset",
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 35_000,
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"unresolved targetless flows remain unknown",
|
||||
),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "available",
|
||||
diagnostics: {
|
||||
install_dir: INSTALL,
|
||||
provider_version: "12.1.2",
|
||||
java_version: "21.0.11",
|
||||
},
|
||||
});
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({ status: "available" });
|
||||
expect(probeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("separates target kind, format, and concrete architecture", () => {
|
||||
const ghidra = provider();
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
||||
).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
path: "/tmp/fixture.asar",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
path: "/tmp/fixture.js",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "artifact",
|
||||
format: "javascript",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra platform support", () => {
|
||||
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
|
||||
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
||||
const nativeApplication = peTarget("x86_64");
|
||||
|
||||
expect(ghidra.inspectTargetSupport(nativeApplication)).toMatchObject({
|
||||
status: "supported",
|
||||
diagnostics: {
|
||||
host_platform: "win32",
|
||||
executable_role: "application",
|
||||
managed: false,
|
||||
},
|
||||
});
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "unavailable",
|
||||
code: "unsupported_host",
|
||||
reason: expect.stringContaining("native authority is unavailable"),
|
||||
diagnostics: {
|
||||
windows_security: {
|
||||
job_object_process_ownership: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
private_runtime_dacl: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
reparse_safe_path_admission: expect.objectContaining({
|
||||
available: false,
|
||||
proof: "not-proven",
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("bounded taskkill cleanup"),
|
||||
expect.stringContaining("private DACL enforcement"),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({
|
||||
...nativeApplication,
|
||||
executableRole: "shared-library",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_role_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport({ ...nativeApplication, managed: true }),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "managed_target_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
});
|
||||
expect(
|
||||
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "architecture_unsupported",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra client projection", () => {
|
||||
it("commits exact provider, isolation, and resource semantics", async () => {
|
||||
const toolCalls: Array<{
|
||||
readonly operation: string;
|
||||
readonly input: unknown;
|
||||
readonly options: unknown;
|
||||
}> = [];
|
||||
let startCount = 0;
|
||||
const factoryOptions: unknown[] = [];
|
||||
const callTool: ReturnType<GhidraProviderClientFactory>["callTool"] = (
|
||||
operation,
|
||||
input,
|
||||
options,
|
||||
) => {
|
||||
toolCalls.push({ operation, input, options });
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
);
|
||||
};
|
||||
const clientFactory: GhidraProviderClientFactory = (options) => {
|
||||
factoryOptions.push(options);
|
||||
return {
|
||||
start: () => {
|
||||
startCount += 1;
|
||||
return Promise.resolve(ok(sessionInfo()));
|
||||
},
|
||||
callTool,
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
};
|
||||
const ghidra = provider(installationHost(), clientFactory);
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
|
||||
expect(resolved.ok).toBe(true);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
expect(resolved.value.profile).toMatchObject({
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
|
||||
provider_profile_schema_version: 1,
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
analyzer_preset: "ghidra-default",
|
||||
analysis_timeout_seconds: 300,
|
||||
max_cpu: 2,
|
||||
max_heap: "2G",
|
||||
},
|
||||
});
|
||||
expect(resolved.value.compatibility).toEqual({
|
||||
languageId: "auto",
|
||||
compilerSpecId: "auto",
|
||||
});
|
||||
|
||||
const result = await ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile, {
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
})
|
||||
.execute("list_procedures", {});
|
||||
expect(factoryOptions).toEqual([
|
||||
expect.objectContaining({
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
}),
|
||||
]);
|
||||
expect(toolCalls).toEqual([
|
||||
{
|
||||
operation: "list_procedures",
|
||||
input: { document: null, offset: 0, limit: 100 },
|
||||
options: {},
|
||||
},
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
provider: {
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: "12.1.2",
|
||||
},
|
||||
analysisProfile: resolved.value.profile,
|
||||
result: {
|
||||
items: [{ address: "0x1000", value: "fixture_main" }],
|
||||
total: 1,
|
||||
},
|
||||
rawResult: {
|
||||
items: [{ procedure: { external: false, thunk: false } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(startCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra result projection", () => {
|
||||
it("rejects malformed inventory output before Evidence creation", async () => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () => Promise.resolve(ok({ items: "not-a-page" })),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid_request", "AnalysisInputError"],
|
||||
["not_found", "AnalysisInputError"],
|
||||
["ambiguous", "AnalysisInputError"],
|
||||
["method_unavailable", "AnalysisCapabilityUnavailableError"],
|
||||
] as const)(
|
||||
"projects remote %s without losing its typed meaning",
|
||||
async (code, tag) => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"Fixture remote failure",
|
||||
{ remote_code: code },
|
||||
{ remoteCode: code },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(
|
||||
executableTarget("elf", "x86_64"),
|
||||
resolved.value.profile,
|
||||
)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({ ok: false, error: { _tag: tag } });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["decompile_timeout", "AnalysisTimeoutError", 30_000],
|
||||
["decompile_cancelled", "AnalysisCancelledError", undefined],
|
||||
] as const)(
|
||||
"projects remote %s as a provider-neutral interruption",
|
||||
async (code, tag, timeoutMs) => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"Fixture decompiler interruption",
|
||||
{ remote_code: code },
|
||||
{ remoteCode: code },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
const result = await ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("procedure_pseudo_code", { procedure: "main" });
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: tag,
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("returns cancellation before profile work", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
provider().resolveAnalysisProfile(executableTarget("elf", "x86_64"), {
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const sessionInfo = () => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 6 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: "a".repeat(64),
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
read_only: true as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
sha256: "a".repeat(64),
|
||||
},
|
||||
});
|
||||
|
||||
const executableTarget = (
|
||||
format: "mach-o" | "elf" | "pe",
|
||||
architecture: NonNullable<BinaryTarget["architecture"]>,
|
||||
): BinaryTarget =>
|
||||
format === "pe"
|
||||
? peTarget(architecture)
|
||||
: {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
|
||||
const peTarget = (
|
||||
architecture: NonNullable<BinaryTarget["architecture"]>,
|
||||
): Extract<BinaryTarget, { format: "pe" }> => ({
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { getEventListeners } from "node:events";
|
||||
import { access } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -286,12 +285,6 @@ describe("HopperClient cleanup", () => {
|
||||
if (child === undefined)
|
||||
throw new Error("Fixture process was not captured");
|
||||
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
|
||||
expect(getEventListeners(child, "exit")).toHaveLength(0);
|
||||
expect(getEventListeners(child, "close")).toHaveLength(0);
|
||||
expect(getEventListeners(child, "error")).toHaveLength(0);
|
||||
expect(child.stderr).not.toBeNull();
|
||||
if (child.stderr === null) throw new Error("Fixture stderr is unavailable");
|
||||
expect(getEventListeners(child.stderr, "data")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
const stopUnrelatedFixture = async (child: ChildProcess): Promise<void> => {
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseDocuments,
|
||||
parseAddressedPage,
|
||||
parseListCount,
|
||||
parseNames,
|
||||
parseProcedures,
|
||||
parseRelatedAddresses,
|
||||
parseSegments,
|
||||
} from "../../../../src/domain/hopperValues.js";
|
||||
|
||||
describe("Hopper boundary values", () => {
|
||||
it("parses Hopper's address-keyed name and string maps", () => {
|
||||
expect(parseNames({ "0x1000": "_main" })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1000", name: "_main" }],
|
||||
});
|
||||
expect(
|
||||
parseListCount({ "0x1000": "hello", "0x2000": "world" }, "strings"),
|
||||
).toEqual({ ok: true, value: 2 });
|
||||
});
|
||||
|
||||
it("parses direct and wrapped protocol shapes", () => {
|
||||
expect(parseProcedures({ procedures: { "0x1": "main" } })).toEqual({
|
||||
ok: true,
|
||||
value: [{ address: "0x1", name: "main" }],
|
||||
});
|
||||
expect(parseNames({ names: [{ address: "0x2", name: "label" }] }).ok).toBe(
|
||||
true,
|
||||
);
|
||||
expect(parseRelatedAddresses({ callers: ["0x3"] }, "callers")).toEqual({
|
||||
ok: true,
|
||||
value: ["0x3"],
|
||||
});
|
||||
expect(
|
||||
parseSegments([
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
]),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: [
|
||||
{
|
||||
name: "__TEXT",
|
||||
start: "0x1",
|
||||
end: "0x2",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(parseDocuments(["fixture"])).toEqual({
|
||||
ok: true,
|
||||
value: ["fixture"],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: true,
|
||||
},
|
||||
{
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: 100,
|
||||
has_more: false,
|
||||
},
|
||||
])("rejects contradictory page continuation metadata", (page) => {
|
||||
const result = parseAddressedPage(page);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["procedures", () => parseProcedures(["not-a-map"])],
|
||||
["names", () => parseNames([{ address: 1, name: "bad" }])],
|
||||
["relations", () => parseRelatedAddresses([1], "callees")],
|
||||
["segments", () => parseSegments([{ name: 1 }])],
|
||||
["documents", () => parseDocuments([1])],
|
||||
])(
|
||||
"rejects malformed %s instead of manufacturing empty output",
|
||||
(_label, parse) => {
|
||||
const result = parse();
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,245 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installLinuxHopper,
|
||||
linuxHopperInstallDisclosure,
|
||||
linuxPackageManagerCommands,
|
||||
linuxSharedLibrariesAvailable,
|
||||
parseLinuxDistribution,
|
||||
type LinuxDistribution,
|
||||
type LinuxHopperDownload,
|
||||
type LinuxHopperInstallHost,
|
||||
type LinuxHopperLauncherStatus,
|
||||
type LinuxPackageFamily,
|
||||
} from "../../../../src/application/LinuxHopper.js";
|
||||
|
||||
class RecordingLinuxHost implements LinuxHopperInstallHost {
|
||||
distributionValue: LinuxDistribution | undefined = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
archive = new Uint8Array([1, 2, 3]);
|
||||
archiveOk = true;
|
||||
installSucceeds = true;
|
||||
launcherStatusValue: LinuxHopperLauncherStatus = "ready";
|
||||
downloads: string[] = [];
|
||||
installed: Array<{ family: LinuxPackageFamily; archive: string }> = [];
|
||||
cleaned: string[] = [];
|
||||
|
||||
distribution = (): Promise<LinuxDistribution | undefined> =>
|
||||
Promise.resolve(this.distributionValue);
|
||||
download = (url: string): Promise<LinuxHopperDownload> => {
|
||||
this.downloads.push(url);
|
||||
return Promise.resolve({ ok: this.archiveOk, bytes: this.archive });
|
||||
};
|
||||
createTemporaryDirectory = (): Promise<string> =>
|
||||
Promise.resolve("/tmp/rea test");
|
||||
writeArchive = (): Promise<void> => Promise.resolve();
|
||||
installPackage = (
|
||||
family: LinuxPackageFamily,
|
||||
archive: string,
|
||||
): Promise<boolean> => {
|
||||
this.installed.push({ family, archive });
|
||||
return Promise.resolve(this.installSucceeds);
|
||||
};
|
||||
launcherStatus = (): Promise<LinuxHopperLauncherStatus> =>
|
||||
Promise.resolve(this.launcherStatusValue);
|
||||
cleanup = (path: string): Promise<void> => {
|
||||
this.cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
};
|
||||
}
|
||||
|
||||
describe("Linux Hopper host classification", () => {
|
||||
it.each([
|
||||
['ID=ubuntu\nVERSION_ID="24.04"\n', "deb"],
|
||||
["ID=fedora\nVERSION_ID=41\n", "rpm"],
|
||||
["ID=arch\n", "arch"],
|
||||
] as const)("accepts an official Hopper distribution", (document, family) => {
|
||||
expect(parseLinuxDistribution(document)).toMatchObject({
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("detects unresolved or loader-reported shared libraries", () => {
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"libQt6Network.so.6 => not found\nlibc.so.6 => /lib/libc.so.6",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"error while loading shared libraries: libQt6Gui.so.6",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
linuxSharedLibrariesAvailable(
|
||||
"libQt6Network.so.6 => /usr/lib/libQt6Network.so.6",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'ID=ubuntu\nVERSION_ID="22.04"\n',
|
||||
"ID=fedora\nVERSION_ID=40\n",
|
||||
'ID=debian\nVERSION_ID="13"\nID_LIKE=debian\n',
|
||||
])("rejects unsupported vendor/version combinations", (document) => {
|
||||
expect(parseLinuxDistribution(document).supported).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Linux Hopper installation", () => {
|
||||
it("discloses the exact download, integrity evidence, and privileged command", () => {
|
||||
expect(linuxHopperInstallDisclosure("deb", false)).toEqual({
|
||||
downloadUrl:
|
||||
"https://www.hopperapp.com:443/downloader/public/Hopper-6.4.2-Linux-demo.deb",
|
||||
expectedBytes: 35_755_772,
|
||||
expectedSha1: "e4f79dff602648a8ff4a88b773875b6bfac0dc65",
|
||||
commands: [
|
||||
"pkexec apt-get install -y <verified-hopper.deb> xvfb xauth python3 libx11-6 libxtst6",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deb", "apt-get"],
|
||||
["rpm", "dnf"],
|
||||
["arch", "pacman"],
|
||||
] as const)("selects the %s native package manager", (family, executable) => {
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
executable,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", false),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
executable: "pkexec",
|
||||
args: expect.arrayContaining([executable, "/tmp/Hopper package"]),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deb", ["xvfb", "xauth", "python3", "libx11-6", "libxtst6"]],
|
||||
[
|
||||
"rpm",
|
||||
[
|
||||
"xorg-x11-server-Xvfb",
|
||||
"xorg-x11-xauth",
|
||||
"python3",
|
||||
"libX11",
|
||||
"libXtst",
|
||||
],
|
||||
],
|
||||
["arch", ["xorg-server-xvfb", "xorg-xauth", "python", "libx11", "libxtst"]],
|
||||
] as const)(
|
||||
"installs the %s demo-session dependencies",
|
||||
(family, packages) => {
|
||||
expect(
|
||||
linuxPackageManagerCommands(family, "/tmp/Hopper package", true),
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
args: expect.arrayContaining([...packages]),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["deb", "rpm", "arch"] as const)(
|
||||
"downloads, verifies, installs, reads back, and cleans a %s package",
|
||||
async (family) => {
|
||||
const host = new RecordingLinuxHost();
|
||||
host.distributionValue = {
|
||||
id: family,
|
||||
packageFamily: family,
|
||||
supported: true,
|
||||
};
|
||||
const result = await installFixture(host);
|
||||
expect(result).toEqual({
|
||||
status: "installed",
|
||||
launcherPath: "/opt/hopper/bin/Hopper",
|
||||
});
|
||||
expect(host.installed).toEqual([
|
||||
{ family, archive: `/tmp/rea test/hopper.${family}` },
|
||||
]);
|
||||
expect(host.cleaned).toEqual(["/tmp/rea test"]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["unsupported host", "unsupported_host"],
|
||||
["package request failure", "download"],
|
||||
["checksum mismatch", "integrity"],
|
||||
["package manager failure", "authorization_or_package_manager"],
|
||||
["missing launcher", "launcher_missing"],
|
||||
["missing runtime", "runtime_dependencies"],
|
||||
["unsupported build", "unsupported_hopper_build"],
|
||||
] as const)("classifies %s", async (scenario, reason) => {
|
||||
const host = new RecordingLinuxHost();
|
||||
if (scenario === "unsupported host")
|
||||
host.distributionValue = {
|
||||
id: "debian",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
if (scenario === "package request failure") host.archiveOk = false;
|
||||
if (scenario === "checksum mismatch") host.archive = new Uint8Array([9]);
|
||||
if (scenario === "package manager failure") host.installSucceeds = false;
|
||||
if (scenario === "missing launcher") host.launcherStatusValue = "missing";
|
||||
if (scenario === "missing runtime")
|
||||
host.launcherStatusValue = "runtime_dependencies";
|
||||
if (scenario === "unsupported build")
|
||||
host.launcherStatusValue = "unsupported_hopper_build";
|
||||
expect(await installFixture(host)).toEqual({
|
||||
status: "failed",
|
||||
reason,
|
||||
});
|
||||
if (host.installed.length > 0)
|
||||
expect(host.cleaned).toEqual(["/tmp/rea test"]);
|
||||
});
|
||||
|
||||
it("cancels before network or mutation", async () => {
|
||||
const host = new RecordingLinuxHost();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect(
|
||||
await installLinuxHopper(host, { signal: controller.signal }),
|
||||
).toEqual({
|
||||
status: "failed",
|
||||
reason: "cancelled",
|
||||
});
|
||||
expect(host.downloads).toEqual([]);
|
||||
expect(host.installed).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
function releasesFor(
|
||||
bytes: Uint8Array,
|
||||
): Record<
|
||||
LinuxPackageFamily,
|
||||
{ filename: string; file_length: string; file_hash: string }
|
||||
> {
|
||||
const release = (extension: string) => ({
|
||||
filename: `https://www.hopperapp.com:443/downloader/public/Hopper.${extension}`,
|
||||
file_length: String(bytes.byteLength),
|
||||
file_hash: createHash("sha1").update(bytes).digest("hex"),
|
||||
});
|
||||
return {
|
||||
deb: release("deb"),
|
||||
rpm: release("rpm"),
|
||||
arch: release("pkg.tar.xz"),
|
||||
};
|
||||
}
|
||||
|
||||
const installFixture = (host: RecordingLinuxHost) =>
|
||||
installLinuxHopper(host, {
|
||||
releases: releasesFor(new Uint8Array([1, 2, 3])),
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installMacHopper,
|
||||
macHopperInstallDisclosure,
|
||||
type MacHopperInstallHost,
|
||||
} from "../../../../src/application/MacHopper.js";
|
||||
|
||||
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||
archiveOk = true;
|
||||
valid = true;
|
||||
existing = false;
|
||||
mountSucceeds = true;
|
||||
copySucceeds = true;
|
||||
launcherSucceeds = true;
|
||||
badHash = false;
|
||||
unmounts = 0;
|
||||
cleanups = 0;
|
||||
opens = 0;
|
||||
replaces = false;
|
||||
|
||||
download = (url: string) =>
|
||||
Promise.resolve(
|
||||
url.includes("files-api")
|
||||
? {
|
||||
ok: true,
|
||||
bytes: new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
"OS X": {
|
||||
filename:
|
||||
"https://www.hopperapp.com:443/downloader/public/Hopper-demo.dmg",
|
||||
file_length: String(this.archive.byteLength),
|
||||
file_hash: this.badHash
|
||||
? "0".repeat(40)
|
||||
: createHash("sha1").update(this.archive).digest("hex"),
|
||||
},
|
||||
}),
|
||||
),
|
||||
}
|
||||
: { ok: this.archiveOk, bytes: this.archive },
|
||||
);
|
||||
createTemporaryDirectory = () => Promise.resolve("/tmp/rea-hopper-test");
|
||||
createMountDirectory = () => Promise.resolve();
|
||||
writePackage = () => Promise.resolve();
|
||||
mount = () => Promise.resolve(this.mountSucceeds);
|
||||
unmount = () => {
|
||||
this.unmounts += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||
validBundle = () => Promise.resolve(this.valid);
|
||||
destinationExists = () => Promise.resolve(this.existing);
|
||||
installBundle = (
|
||||
_source: string,
|
||||
_destination: string,
|
||||
_stage: string,
|
||||
replaceExisting: boolean,
|
||||
) => {
|
||||
this.replaces = replaceExisting;
|
||||
return Promise.resolve(this.copySucceeds);
|
||||
};
|
||||
launcherReady = () => Promise.resolve(this.launcherSucceeds);
|
||||
openApplication = () => {
|
||||
this.opens += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
cleanup = () => {
|
||||
this.cleanups += 1;
|
||||
return Promise.resolve();
|
||||
};
|
||||
destination = () => "/home/user/Applications/Hopper Disassembler.app";
|
||||
}
|
||||
|
||||
describe("macOS Hopper installation", () => {
|
||||
it("discloses network and command boundaries before installation", () => {
|
||||
expect(macHopperInstallDisclosure).toMatchObject({
|
||||
networkOrigins: [
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true",
|
||||
"https://www.hopperapp.com:443/downloader/public/",
|
||||
],
|
||||
});
|
||||
expect(macHopperInstallDisclosure.commands).toContain(
|
||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||
);
|
||||
});
|
||||
|
||||
it("installs, verifies, opens, and cleans the official package", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "installed",
|
||||
launcherPath:
|
||||
"/home/user/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
});
|
||||
expect(host.opens).toBe(1);
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects an integrity mismatch before mounting", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.badHash = true;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "integrity",
|
||||
});
|
||||
expect(host.unmounts).toBe(0);
|
||||
expect(host.cleanups).toBe(0);
|
||||
});
|
||||
|
||||
it("refuses to overwrite an existing application", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.existing = true;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "destination_exists",
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces the managed application when explicitly requested", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.existing = true;
|
||||
|
||||
await expect(
|
||||
installMacHopper({ replaceExisting: true }, host),
|
||||
).resolves.toMatchObject({ status: "installed" });
|
||||
expect(host.replaces).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans and detaches after bundle validation fails", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.valid = false;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "bundle",
|
||||
});
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,350 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectManagedApplicationGraphEvidence } from "../../../../src/application/ManagedApplicationGraphService.js";
|
||||
import { traceApplicationFeatureEvidence } from "../../../../src/application/JavaScriptApplicationWorkflowService.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../../../src/application/InvestigationProviders.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import {
|
||||
createEvidence,
|
||||
parseEvidence,
|
||||
} from "../../../../src/domain/evidence.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { managedApplicationGraphResultSchema } from "../../../../src/domain/managedApplicationGraph.js";
|
||||
import { inspectManagedArtifactBytes } from "../../../../src/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "../../../../src/dotnet/ManagedNativeBoundaryInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const artifactLimits = {
|
||||
referenceOffset: 0,
|
||||
referenceLimit: 100,
|
||||
resourceOffset: 0,
|
||||
resourceLimit: 100,
|
||||
attributeOffset: 0,
|
||||
attributeLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
const boundaryLimits = {
|
||||
moduleRefOffset: 0,
|
||||
moduleRefLimit: 100,
|
||||
importOffset: 0,
|
||||
importLimit: 100,
|
||||
implementationOffset: 0,
|
||||
implementationLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
describe("managed application graph projection", () => {
|
||||
it("projects managed metadata and native declarations into authenticated graph Evidence", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
pinvoke: {
|
||||
moduleName: "user32.dll",
|
||||
importName: "MessageBoxW",
|
||||
mappingFlags: 0x0345,
|
||||
},
|
||||
});
|
||||
const binary = target(bytes);
|
||||
const managedArtifact = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
binary,
|
||||
artifactLimits,
|
||||
);
|
||||
const members = inspectManagedMembersBytes(bytes, binary, memberLimits);
|
||||
const boundaries = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
binary,
|
||||
boundaryLimits,
|
||||
);
|
||||
const artifactEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_artifact",
|
||||
parameters: {},
|
||||
result: managedArtifact,
|
||||
rawResult: null,
|
||||
limitations: managedArtifact.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: members,
|
||||
rawResult: null,
|
||||
limitations: members.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
const boundaryEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_native_boundaries",
|
||||
parameters: {},
|
||||
result: boundaries,
|
||||
rawResult: null,
|
||||
limitations: boundaries.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
|
||||
const evidence = projectManagedApplicationGraphEvidence({
|
||||
managed_artifact: artifactEvidence,
|
||||
managed_members: memberEvidence,
|
||||
managed_native_boundaries: boundaryEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
evidence.ok,
|
||||
evidence.ok
|
||||
? undefined
|
||||
: `${JSON.stringify(evidence.error)} cause=${String(evidence.error.cause)}`,
|
||||
).toBe(true);
|
||||
if (!evidence.ok) throw new Error("projection failed");
|
||||
const parsed = parseEvidence(evidence.value);
|
||||
expect(parsed).toMatchObject({
|
||||
operation: "project_managed_application_graph",
|
||||
predicate_type: "rea.managed-application-graph/v1",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
evidence_links: [
|
||||
artifactEvidence.evidence_id,
|
||||
memberEvidence.evidence_id,
|
||||
boundaryEvidence.evidence_id,
|
||||
],
|
||||
});
|
||||
const result = managedApplicationGraphResultSchema.parse(
|
||||
parsed.normalized_result,
|
||||
);
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
expect(result.summary).toMatchObject({
|
||||
assemblies: 1,
|
||||
modules: 1,
|
||||
types: 1,
|
||||
methods: 1,
|
||||
fields: 1,
|
||||
pinvoke_imports: 1,
|
||||
});
|
||||
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"artifact",
|
||||
"managed-assembly",
|
||||
"managed-module",
|
||||
"managed-type",
|
||||
"managed-method",
|
||||
"managed-field",
|
||||
"managed-pinvoke-import",
|
||||
]),
|
||||
);
|
||||
const method = graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "managed-method" &&
|
||||
observations[0]?.label === "Fixture.Program.Main",
|
||||
);
|
||||
expect(method).toBeDefined();
|
||||
expect(
|
||||
graph.edges.some(
|
||||
({ source_node_id, relation, target_node_id }) =>
|
||||
source_node_id === method?.node_id &&
|
||||
relation === "imports" &&
|
||||
graph.nodes.find(({ node_id: id }) => id === target_node_id)?.kind ===
|
||||
"managed-pinvoke-import",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) =>
|
||||
observations.map(({ evidence }) => evidence.authority),
|
||||
),
|
||||
).toContain("managed-static-analysis");
|
||||
|
||||
const trace = traceApplicationFeatureEvidence({
|
||||
application: parsed,
|
||||
native_observations: [],
|
||||
seed: {
|
||||
kind: "string",
|
||||
value: "MessageBoxW",
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
},
|
||||
direction: "incoming",
|
||||
limits: {
|
||||
max_seed_matches: 5,
|
||||
max_depth: 4,
|
||||
max_nodes: 50,
|
||||
max_edges: 100,
|
||||
max_paths: 10,
|
||||
},
|
||||
});
|
||||
expect(trace.ok).toBe(true);
|
||||
if (!trace.ok) throw new Error("trace failed");
|
||||
expect(trace.value.normalized_result).toMatchObject({
|
||||
source_evidence_id: parsed.evidence_id,
|
||||
summary: { matched_seeds: 1 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed application graph coverage", () => {
|
||||
it("preserves source-page omissions in graph and per-fact coverage", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const binary = target(bytes);
|
||||
const members = inspectManagedMembersBytes(bytes, binary, memberLimits);
|
||||
const partialMembers = {
|
||||
...members,
|
||||
methods: {
|
||||
...members.methods,
|
||||
total: 2,
|
||||
returned: 1,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: partialMembers,
|
||||
rawResult: null,
|
||||
limitations: partialMembers.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
|
||||
const evidence = projectManagedApplicationGraphEvidence({
|
||||
managed_members: memberEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
evidence.ok,
|
||||
evidence.ok
|
||||
? undefined
|
||||
: `${JSON.stringify(evidence.error)} cause=${String(evidence.error.cause)}`,
|
||||
).toBe(true);
|
||||
if (!evidence.ok) throw new Error("projection failed");
|
||||
const result = managedApplicationGraphResultSchema.parse(
|
||||
parseEvidence(evidence.value).normalized_result,
|
||||
);
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
omitted_types: 0,
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 0,
|
||||
});
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
const method = graph.nodes.find(({ kind }) => kind === "managed-method");
|
||||
expect(method?.observations[0]?.evidence.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ target_node_id }) => target_node_id === method?.node_id,
|
||||
)?.evidence.coverage,
|
||||
).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
|
||||
const parserPartialMembers = {
|
||||
...partialMembers,
|
||||
coverage: {
|
||||
state: "partial" as const,
|
||||
issues: [
|
||||
{
|
||||
code: "limit-exceeded" as const,
|
||||
scope: "method.0x06000001.body.instructions",
|
||||
offset: 0x0a00,
|
||||
detail: "instruction limit reached",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const parserPartialEvidence = createEvidence(
|
||||
binary,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: parserPartialMembers,
|
||||
rawResult: null,
|
||||
limitations: parserPartialMembers.limitations,
|
||||
},
|
||||
);
|
||||
const parserPartialProjection = projectManagedApplicationGraphEvidence({
|
||||
managed_members: parserPartialEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parserPartialProjection.ok).toBe(true);
|
||||
if (!parserPartialProjection.ok)
|
||||
throw new Error("partial projection failed");
|
||||
const parserPartialResult = managedApplicationGraphResultSchema.parse(
|
||||
parseEvidence(parserPartialProjection.value).normalized_result,
|
||||
);
|
||||
expect(parserPartialResult.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omitted_methods: 1,
|
||||
});
|
||||
expect(parserPartialResult.graph.coverage).toEqual({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture/ManagedInterop.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
describe("managed CIL decoding", () => {
|
||||
it("reads fat method header size from the full flags-and-size word", () => {
|
||||
const il = Buffer.from([
|
||||
0x21, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x22, 0x00,
|
||||
0x00, 0x80, 0x3f, 0x26, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
|
||||
0x3f, 0x26, 0xfe, 0x06, 0x01, 0x00, 0x00, 0x06, 0x26, 0x2a,
|
||||
]);
|
||||
const header = Buffer.alloc(12);
|
||||
header.writeUInt16LE(0x3013, 0);
|
||||
header.writeUInt16LE(8, 2);
|
||||
header.writeUInt32LE(il.length, 4);
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([header, il]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
memberLimits,
|
||||
);
|
||||
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "present",
|
||||
header_format: "fat",
|
||||
il_size: il.length,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
opcode_counts: {
|
||||
"ldc.i8": 1,
|
||||
pop: 4,
|
||||
"ldc.r4": 1,
|
||||
"ldc.r8": 1,
|
||||
ldftn: 1,
|
||||
ret: 1,
|
||||
},
|
||||
issue: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not normalize reserved CIL opcodes as operand-free instructions", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([0x0a, 0x24, 0x2a]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
memberLimits,
|
||||
);
|
||||
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "malformed",
|
||||
il_size: 2,
|
||||
normalized_il_sha256: null,
|
||||
decoded_instruction_count: 0,
|
||||
issue: "Unsupported CIL opcode 0x24 at IL offset 0",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the documented decoded-CIL v1 golden vector stable", () => {
|
||||
const il = Buffer.from([0x00, 0x2a]);
|
||||
const tinyBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([0x0a, ...il]),
|
||||
});
|
||||
const fatHeader = Buffer.alloc(12);
|
||||
fatHeader.writeUInt16LE(0x3013, 0);
|
||||
fatHeader.writeUInt16LE(32, 2);
|
||||
fatHeader.writeUInt32LE(il.length, 4);
|
||||
fatHeader.writeUInt32LE(0x1100_0001, 8);
|
||||
const fatBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.concat([fatHeader, il]),
|
||||
});
|
||||
const tiny = inspectManagedMembersBytes(
|
||||
tinyBytes,
|
||||
target(tinyBytes),
|
||||
memberLimits,
|
||||
);
|
||||
const fat = inspectManagedMembersBytes(
|
||||
fatBytes,
|
||||
target(fatBytes),
|
||||
memberLimits,
|
||||
);
|
||||
|
||||
expect(tiny.methods.items[0]?.body).toMatchObject({
|
||||
status: "present",
|
||||
header_format: "tiny",
|
||||
max_stack: 8,
|
||||
init_locals: false,
|
||||
local_var_sig_token: null,
|
||||
il_size: 2,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
normalized_il_sha256:
|
||||
"5e5fad7741cb44bca3a4f045546b7449990da343f612f5f34c0ca30e9eee0636",
|
||||
opcode_counts: { nop: 1, ret: 1 },
|
||||
exception_regions: [],
|
||||
});
|
||||
expect(fat.methods.items[0]?.body).toMatchObject({
|
||||
header_format: "fat",
|
||||
max_stack: 32,
|
||||
init_locals: true,
|
||||
local_var_sig_token: "0x11000001",
|
||||
il_sha256: tiny.methods.items[0]?.body.il_sha256,
|
||||
normalized_il_sha256: tiny.methods.items[0]?.body.normalized_il_sha256,
|
||||
});
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
describe("managed CIL limits", () => {
|
||||
it("marks instruction-limited CIL as partial without assigning normalized identity", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const result = inspectManagedMembersBytes(bytes, target(bytes), {
|
||||
...memberLimits,
|
||||
maxMethodInstructions: 1,
|
||||
});
|
||||
const il = bytes.subarray(0x0a01, 0x0a0d);
|
||||
|
||||
expect(result.metadata.status).toBe("complete");
|
||||
expect(result.methods.items[0]?.body).toMatchObject({
|
||||
status: "partial",
|
||||
il_size: 12,
|
||||
il_sha256: createHash("sha256").update(il).digest("hex"),
|
||||
normalized_il_sha256: null,
|
||||
instruction_count: 1,
|
||||
decoded_instruction_count: 1,
|
||||
truncated_instructions: 1,
|
||||
issue:
|
||||
"Instruction decode reached max_method_instructions 1 before the end of the method body",
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
state: "partial",
|
||||
issues: [
|
||||
{
|
||||
code: "limit-exceeded",
|
||||
scope: "method.0x06000001.body.instructions",
|
||||
offset: 0x0a00,
|
||||
detail:
|
||||
"Instruction decode reached max_method_instructions 1 before the end of the method body",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.limitations.join(" ")).toContain(
|
||||
"has no normalized CIL identity",
|
||||
);
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedArtifactBytes } from "../../../../src/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "../../../../src/dotnet/ManagedNativeBoundaryInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const limits = {
|
||||
referenceOffset: 0,
|
||||
referenceLimit: 100,
|
||||
resourceOffset: 0,
|
||||
resourceLimit: 100,
|
||||
attributeOffset: 0,
|
||||
attributeLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
const nativeBoundaryLimits = {
|
||||
moduleRefOffset: 0,
|
||||
moduleRefLimit: 100,
|
||||
importOffset: 0,
|
||||
importLimit: 100,
|
||||
implementationOffset: 0,
|
||||
implementationLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
describe("managed artifact inventory", () => {
|
||||
it("inventories module, assembly, framework, references, and resources without loading CLR code", () => {
|
||||
const resource = Buffer.from("source-owned resource");
|
||||
const bytes = buildManagedPeFixture({ resourceData: resource });
|
||||
const result = inspectManagedArtifactBytes(bytes, target(bytes), limits);
|
||||
|
||||
expect(result.classification).toMatchObject({
|
||||
status: "managed",
|
||||
runtime_family: "modern-dotnet",
|
||||
implementation: "cil",
|
||||
managed_architecture: "anycpu",
|
||||
});
|
||||
expect(result.pe.cli).toMatchObject({
|
||||
flag_names: ["il-only"],
|
||||
entry_point: { kind: "metadata-token", value: "0x06000001" },
|
||||
});
|
||||
expect(result.module).toMatchObject({
|
||||
name: "Fixture.dll",
|
||||
mvid: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
token: "0x00000001",
|
||||
});
|
||||
expect(result.assembly).toMatchObject({
|
||||
name: "Fixture.Managed",
|
||||
version: "1.2.3.4",
|
||||
token: "0x20000001",
|
||||
});
|
||||
expect(result.target_frameworks).toEqual([".NETCoreApp,Version=v8.0"]);
|
||||
expect(result.references).toMatchObject({
|
||||
total: 1,
|
||||
returned: 1,
|
||||
complete: true,
|
||||
items: [expect.objectContaining({ name: "System.Runtime" })],
|
||||
});
|
||||
expect(result.resources.items).toEqual([
|
||||
expect.objectContaining({
|
||||
name: "Fixture.resources",
|
||||
embedded: true,
|
||||
visibility: "private",
|
||||
data_length: resource.length,
|
||||
data_sha256: createHash("sha256").update(resource).digest("hex"),
|
||||
}),
|
||||
]);
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
});
|
||||
|
||||
it("keeps classification evidence complete when caller pages visible references", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
references: ["System.Runtime", "UnityEngine.CoreModule"],
|
||||
});
|
||||
const result = inspectManagedArtifactBytes(bytes, target(bytes), {
|
||||
...limits,
|
||||
referenceLimit: 1,
|
||||
});
|
||||
|
||||
expect(result.classification.runtime_family).toBe("unity-mono");
|
||||
expect(result.references).toMatchObject({
|
||||
total: 2,
|
||||
returned: 1,
|
||||
complete: false,
|
||||
});
|
||||
expect(result.coverage.state).toBe("partial");
|
||||
expect(result.coverage.issues).toEqual([]);
|
||||
});
|
||||
|
||||
it("accepts CLI metadata GUIDs without RFC UUID version or variant bits", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
mvid: Buffer.from("3aebc60edc4a544b1f458b4ed40b33b1", "hex"),
|
||||
});
|
||||
const result = inspectManagedArtifactBytes(bytes, target(bytes), limits);
|
||||
const members = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
memberLimits,
|
||||
);
|
||||
const boundaries = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
nativeBoundaryLimits,
|
||||
);
|
||||
|
||||
expect(result.module?.mvid).toBe("0ec6eb3a-4adc-4b54-1f45-8b4ed40b33b1");
|
||||
expect(result.classification.status).toBe("managed");
|
||||
expect(members.identity_scope.requires_mvid).toBe(result.module?.mvid);
|
||||
expect(boundaries.identity_scope.requires_mvid).toBe(result.module?.mvid);
|
||||
});
|
||||
|
||||
it("decodes ECMA-335 pointer and byref element types without swapping them", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
fieldSignature: Buffer.from([0x06, 0x1d, 0x0f, 0x0f, 0x08]),
|
||||
methodSignature: Buffer.from([
|
||||
0x00, 0x02, 0x10, 0x08, 0x0f, 0x08, 0x10, 0x0e,
|
||||
]),
|
||||
});
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
memberLimits,
|
||||
);
|
||||
|
||||
expect(result.fields.items[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
field_type: "i4**[]",
|
||||
});
|
||||
expect(result.methods.items[0]?.signature).toMatchObject({
|
||||
parse_status: "decoded",
|
||||
return_type: "i4&",
|
||||
parameter_types: ["i4*", "string&"],
|
||||
});
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
describe("managed member inspection", () => {
|
||||
it("inspects metadata members, signatures, CIL hashes, call edges, and field anchors", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const result = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
memberLimits,
|
||||
);
|
||||
|
||||
expect(result.identity_scope).toEqual({
|
||||
token_identity: "build-local",
|
||||
requires_artifact_sha256: target(bytes).sha256,
|
||||
requires_mvid: "00112233-4455-6677-8899-aabbccddeeff",
|
||||
});
|
||||
expect(result.types.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x02000001",
|
||||
full_name: "Fixture.Program",
|
||||
field_list: { first_row: 1, last_row: 1, count: 1 },
|
||||
method_list: { first_row: 1, last_row: 1, count: 1 },
|
||||
}),
|
||||
]);
|
||||
expect(result.fields.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x04000001",
|
||||
declaring_type: "Fixture.Program",
|
||||
name: "counter",
|
||||
signature: expect.objectContaining({
|
||||
kind: "field",
|
||||
parse_status: "decoded",
|
||||
field_type: "i4",
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.methods.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
declaring_type: "Fixture.Program",
|
||||
name: "Main",
|
||||
rva: 0x2800,
|
||||
signature: expect.objectContaining({
|
||||
kind: "method",
|
||||
parse_status: "decoded",
|
||||
return_type: "void",
|
||||
parameter_types: [],
|
||||
}),
|
||||
body: expect.objectContaining({
|
||||
status: "present",
|
||||
header_format: "tiny",
|
||||
file_offset: 0x0a00,
|
||||
il_size: 12,
|
||||
instruction_count: 4,
|
||||
decoded_instruction_count: 4,
|
||||
truncated_instructions: 0,
|
||||
opcode_counts: { "ldarg.0": 1, ldfld: 1, call: 1, ret: 1 },
|
||||
anchors: [
|
||||
{
|
||||
il_offset: 1,
|
||||
opcode: "ldfld",
|
||||
operand_kind: "field",
|
||||
operand: "0x04000001",
|
||||
},
|
||||
{
|
||||
il_offset: 6,
|
||||
opcode: "call",
|
||||
operand_kind: "method",
|
||||
operand: "0x0a000001",
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.member_refs.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x0a000001",
|
||||
name: ".ctor",
|
||||
signature: expect.objectContaining({
|
||||
kind: "method",
|
||||
parse_status: "decoded",
|
||||
parameter_types: ["string"],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
expect(result.call_edges.items).toEqual([
|
||||
{
|
||||
caller_token: "0x06000001",
|
||||
caller: "Fixture.Program.Main",
|
||||
opcode: "call",
|
||||
target_token: "0x0a000001",
|
||||
target_kind: "member-ref",
|
||||
target_name: ".ctor",
|
||||
},
|
||||
]);
|
||||
expect(result.field_accesses.items).toEqual([
|
||||
{
|
||||
method_token: "0x06000001",
|
||||
method: "Fixture.Program.Main",
|
||||
opcode: "ldfld",
|
||||
field_token: "0x04000001",
|
||||
field_name: "counter",
|
||||
},
|
||||
]);
|
||||
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
@@ -1,156 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "../../../../src/dotnet/ManagedNativeBoundaryInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
buildNativePeFixture,
|
||||
} from "../../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
const nativeBoundaryLimits = {
|
||||
moduleRefOffset: 0,
|
||||
moduleRefLimit: 100,
|
||||
importOffset: 0,
|
||||
importLimit: 100,
|
||||
implementationOffset: 0,
|
||||
implementationLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
describe("managed native boundaries", () => {
|
||||
it("inspects managed/native PInvoke declarations without verifying native exports", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
pinvoke: {
|
||||
moduleName: "user32.dll",
|
||||
importName: "MessageBoxW",
|
||||
mappingFlags: 0x0345,
|
||||
},
|
||||
readyToRun: true,
|
||||
});
|
||||
const result = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
target(bytes),
|
||||
nativeBoundaryLimits,
|
||||
);
|
||||
|
||||
expect(result.cli_native).toMatchObject({
|
||||
il_only: true,
|
||||
ready_to_run_signature: true,
|
||||
managed_native_header_rva: 0x2700,
|
||||
managed_native_header_size: 4,
|
||||
});
|
||||
expect(result.module_refs.items).toEqual([
|
||||
{
|
||||
token: "0x1a000001",
|
||||
row_offset: expect.any(Number),
|
||||
name: "user32.dll",
|
||||
},
|
||||
]);
|
||||
expect(result.pinvoke_imports.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x1c000001",
|
||||
member_token: "0x06000001",
|
||||
member_kind: "method",
|
||||
member_name: "Main",
|
||||
import_name: "MessageBoxW",
|
||||
import_scope_token: "0x1a000001",
|
||||
import_scope_name: "user32.dll",
|
||||
no_mangle: true,
|
||||
char_set: "unicode",
|
||||
call_convention: "stdcall",
|
||||
supports_last_error: true,
|
||||
verification: "managed-declaration-only",
|
||||
}),
|
||||
]);
|
||||
expect(result.native_implementations.items).toEqual([
|
||||
expect.objectContaining({
|
||||
token: "0x06000001",
|
||||
name: "Main",
|
||||
pinvoke_declared: true,
|
||||
boundary_kind: "pinvoke",
|
||||
body_interpretation: "native-or-runtime",
|
||||
}),
|
||||
]);
|
||||
expect(result.summary).toMatchObject({
|
||||
module_ref_count: 1,
|
||||
pinvoke_import_count: 1,
|
||||
native_implementation_count: 1,
|
||||
ready_to_run: true,
|
||||
mixed_mode_or_native_header: true,
|
||||
});
|
||||
expect(result.limitations).toContain(
|
||||
"P/Invoke rows prove managed import declarations only; this inspection does not verify that a native library, export, thunk, or provider-qualified function exists.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps member evidence bounded and typed for pagination and unavailable metadata", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const paged = inspectManagedMembersBytes(bytes, target(bytes), {
|
||||
...memberLimits,
|
||||
methodLimit: 0 + 1,
|
||||
instructionAnchorLimit: 1,
|
||||
});
|
||||
expect(paged.methods).toMatchObject({
|
||||
total: 1,
|
||||
returned: 1,
|
||||
complete: true,
|
||||
});
|
||||
expect(paged.methods.items[0]?.body.anchors).toHaveLength(1);
|
||||
|
||||
const nativeBytes = buildNativePeFixture();
|
||||
const native = inspectManagedMembersBytes(
|
||||
nativeBytes,
|
||||
target(nativeBytes),
|
||||
memberLimits,
|
||||
);
|
||||
expect(native.metadata.status).toBe("absent");
|
||||
expect(native.coverage.state).toBe("unavailable");
|
||||
|
||||
const malformedBytes = buildManagedPeFixture({
|
||||
corruptMetadataSignature: true,
|
||||
});
|
||||
const malformed = inspectManagedMembersBytes(
|
||||
malformedBytes,
|
||||
target(malformedBytes),
|
||||
memberLimits,
|
||||
);
|
||||
expect(malformed.metadata.status).toBe("malformed");
|
||||
expect(malformed.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-metadata-root" }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
+3
-3
@@ -7,10 +7,10 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
|
||||
|
||||
import { runProviderAnalysis } from "../../../../src/application/DirectAnalysis.js";
|
||||
import { parseEvidence } from "../../../../src/domain/evidence.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed CLI evidence", () => {
|
||||
it("has the same evidence shape through direct CLI analysis plumbing", async () => {
|
||||
describe("managed direct-analysis path boundary", () => {
|
||||
it("returns provider evidence through the shared analysis service", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-cli-");
|
||||
const path = join(directory, "fixture.exe");
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
@@ -1,4 +1,3 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -7,292 +6,11 @@ import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { compareManagedMemberPaths } from "../../../../src/application/ManagedMemberComparisonService.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../../../src/application/InvestigationProviders.js";
|
||||
import { managedMemberComparisonResultSchema } from "../../../../src/domain/managedMemberComparison.js";
|
||||
import {
|
||||
compareManagedMembers,
|
||||
managedMemberComparisonResultSchema,
|
||||
} from "../../../../src/domain/managedMemberComparison.js";
|
||||
import { createEvidence } from "../../../../src/domain/evidence.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { buildManagedPeFixture } from "../../../fixtures/managedPe.js";
|
||||
|
||||
const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
const pathMemberLimits = {
|
||||
...memberLimits,
|
||||
maxFileBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
const comparisonLimits = {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
};
|
||||
|
||||
describe("managed member comparison", () => {
|
||||
it("remaps renamed methods by exact CIL/signature without using names", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
mvid: Buffer.from("00112233445566778899aabbccddeefe", "hex"),
|
||||
typeName: "A",
|
||||
typeNamespace: "X",
|
||||
methodName: "b",
|
||||
fieldName: "c",
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: left.result },
|
||||
{ evidenceId: right.evidence.evidence_id, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.algorithm.name_matching).toBe("not-used");
|
||||
expect(result.left.mvid).toBe("00112233-4455-6677-8899-aabbccddeeff");
|
||||
expect(result.right.mvid).toBe("33221100-5544-7766-8899-aabbccddeefe");
|
||||
expect(result.matching.exact_il_signature).toBe(1);
|
||||
expect(result.methods).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unchanged",
|
||||
left: expect.objectContaining({ token: "0x06000001", name: "Main" }),
|
||||
right: expect.objectContaining({ token: "0x06000001", name: "b" }),
|
||||
match: expect.objectContaining({
|
||||
status: "matched",
|
||||
basis: "exact-il-signature",
|
||||
confidence: "exact",
|
||||
}),
|
||||
dimensions: [],
|
||||
}),
|
||||
]);
|
||||
expect(result.limitations).toContain(
|
||||
"Names are reported as observations but are not used as a matching basis.",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses structural method shape when build-local token operands drift", () => {
|
||||
const leftBytes = buildManagedPeFixture();
|
||||
const rightBytes = buildManagedPeFixture({
|
||||
ilBody: Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, 0x0a,
|
||||
0x2a,
|
||||
]),
|
||||
});
|
||||
const left = inspect(leftBytes, "/tmp/left.dll");
|
||||
const right = inspect(rightBytes, "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: left.result },
|
||||
{ evidenceId: right.evidence.evidence_id, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(1);
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "changed",
|
||||
match: { status: "matched", basis: "structural-method-shape" },
|
||||
dimensions: ["cil"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects member states that disagree with their observed sides or match", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: left.result },
|
||||
{ evidenceId: right.evidence.evidence_id, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
const method = result.methods[0];
|
||||
expect(method).toBeDefined();
|
||||
if (method === undefined) return;
|
||||
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [{ ...method, status: "unchanged", right: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.safeParse({
|
||||
...result,
|
||||
methods: [
|
||||
{
|
||||
...method,
|
||||
match: {
|
||||
...method.match,
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
},
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not match identical instruction-limited method prefixes", () => {
|
||||
const limited = { ...memberLimits, maxMethodInstructions: 1 };
|
||||
const left = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/left-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const right = inspect(
|
||||
buildManagedPeFixture(),
|
||||
"/tmp/right-partial.dll",
|
||||
limited,
|
||||
);
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: left.result },
|
||||
{ evidenceId: right.evidence.evidence_id, result: right.result },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.exact_il_signature).toBe(0);
|
||||
expect(result.matching.structural_method_shape).toBe(0);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed member comparison uncertainty", () => {
|
||||
it("keeps unmatched members unknown when the opposite page is incomplete", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left-paged.dll");
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right-paged.dll");
|
||||
const leftPartial = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const rightPartial = {
|
||||
...right.result,
|
||||
methods: {
|
||||
...right.result.methods,
|
||||
items: [],
|
||||
returned: 0,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: leftPartial },
|
||||
{ evidenceId: right.evidence.evidence_id, result: rightPartial },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.summary).toMatchObject({
|
||||
added: 0,
|
||||
removed: 0,
|
||||
unknown: 2,
|
||||
});
|
||||
expect(result.methods[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: { token: "0x06000001" },
|
||||
right: null,
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.fields[0]).toMatchObject({
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: { token: "0x04000001" },
|
||||
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
|
||||
});
|
||||
expect(result.coverage).toEqual({
|
||||
status: "truncated",
|
||||
left_status: "partial",
|
||||
right_status: "partial",
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 1,
|
||||
omitted_candidates: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not guess ambiguous field signature matches", () => {
|
||||
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
|
||||
const leftField = left.result.fields.items[0];
|
||||
expect(leftField).toBeDefined();
|
||||
if (leftField === undefined) return;
|
||||
const duplicatedLeft = {
|
||||
...left.result,
|
||||
fields: {
|
||||
...left.result.fields,
|
||||
items: [
|
||||
leftField,
|
||||
{
|
||||
...leftField,
|
||||
token: "0x04000002",
|
||||
name: "other",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
|
||||
const rightField = right.result.fields.items[0];
|
||||
expect(rightField).toBeDefined();
|
||||
if (rightField === undefined) return;
|
||||
const duplicatedRight = {
|
||||
...right.result,
|
||||
fields: {
|
||||
...right.result.fields,
|
||||
items: [
|
||||
rightField,
|
||||
{
|
||||
...rightField,
|
||||
token: "0x04000002",
|
||||
name: "renamed",
|
||||
},
|
||||
],
|
||||
total: 2,
|
||||
returned: 2,
|
||||
},
|
||||
};
|
||||
const result = compareManagedMembers(
|
||||
{ evidenceId: left.evidence.evidence_id, result: duplicatedLeft },
|
||||
{ evidenceId: right.evidence.evidence_id, result: duplicatedRight },
|
||||
comparisonLimits,
|
||||
);
|
||||
|
||||
expect(result.matching.ambiguous).toBe(1);
|
||||
expect(result.fields).toEqual([
|
||||
expect.objectContaining({
|
||||
status: "unknown",
|
||||
match: expect.objectContaining({
|
||||
status: "ambiguous",
|
||||
basis: "field-signature",
|
||||
candidate_left_tokens: ["0x04000001", "0x04000002"],
|
||||
candidate_right_tokens: ["0x04000001", "0x04000002"],
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
buildManagedPeFixture,
|
||||
MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
|
||||
} from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed member comparison path workflow", () => {
|
||||
it("compares two local paths and returns derived Evidence", async () => {
|
||||
@@ -308,49 +26,24 @@ describe("managed member comparison path workflow", () => {
|
||||
const result = await compareManagedMemberPaths({
|
||||
leftPath,
|
||||
rightPath,
|
||||
memberLimits: pathMemberLimits,
|
||||
comparisonLimits,
|
||||
memberLimits: MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
|
||||
comparisonLimits: {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.operation).toBe("compare_managed_members");
|
||||
expect(result.value.confidence).toBe("inferred");
|
||||
expect(result.value.authority).toBe("analyst-inference");
|
||||
expect(result.value).toMatchObject({
|
||||
operation: "compare_managed_members",
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
});
|
||||
expect(
|
||||
managedMemberComparisonResultSchema.parse(result.value.normalized_result)
|
||||
.matching.exact_il_signature,
|
||||
).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
const inspect = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
limits: typeof memberLimits = memberLimits,
|
||||
) => {
|
||||
const target: BinaryTarget = {
|
||||
path,
|
||||
sha256: hash(bytes),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
};
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
return {
|
||||
result,
|
||||
evidence: createEvidence(target, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result,
|
||||
rawResult: null,
|
||||
limitations: result.limitations,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { importManagedReconstructionEvidence } from "../../../../src/application/ManagedReconstructionService.js";
|
||||
import { MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE } from "../../../../src/contracts/managedWorkflowExamples.js";
|
||||
import {
|
||||
importManagedReconstruction,
|
||||
managedReconstructionImportInputSchema,
|
||||
} from "../../../../src/domain/managedReconstruction.js";
|
||||
import { managedMemberInspectionSchema } from "../../../../src/domain/managedArtifact.js";
|
||||
import { createEvidence } from "../../../../src/domain/evidence.js";
|
||||
|
||||
const exampleInput = () =>
|
||||
managedReconstructionImportInputSchema.parse(
|
||||
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
|
||||
);
|
||||
|
||||
const exampleMethod = () => {
|
||||
const method = exampleInput().methods[0];
|
||||
if (method === undefined) throw new Error("missing example method");
|
||||
return method;
|
||||
};
|
||||
|
||||
describe("managed decompiler reconstruction import", () => {
|
||||
it("imports decompiler output as inference locked to static IL evidence", () => {
|
||||
const result = importManagedReconstruction(exampleInput());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
schema_version: 1,
|
||||
phase: "reconstruction-import",
|
||||
executed: false,
|
||||
static_observation: {
|
||||
artifact_sha256: "2".repeat(64),
|
||||
mvid: "11112222-3333-4444-9555-666677778888",
|
||||
},
|
||||
decompiler: {
|
||||
name: "ilspycmd",
|
||||
version: "9.1.0.7988",
|
||||
family: "ilspy",
|
||||
},
|
||||
summary: {
|
||||
imported_methods: 1,
|
||||
decompiled_csharp_methods: 1,
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
token: "0x06000001",
|
||||
signature_sha256: "3".repeat(64),
|
||||
normalized_il_sha256: "5".repeat(64),
|
||||
validation: {
|
||||
matched_static_member: true,
|
||||
exact_build_required: true,
|
||||
canonical_observation: false,
|
||||
confidence_floor: "inference",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.reconstruction_id).toMatch(/^mre_[a-f0-9]{64}$/u);
|
||||
expect(result.methods[0]?.reconstruction.text_sha256).toBe(
|
||||
createHash("sha256")
|
||||
.update("internal static void Main() { }")
|
||||
.digest("hex"),
|
||||
);
|
||||
expect(result.limitations.join(" ")).toContain(
|
||||
"metadata and IL observations remain canonical",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects reconstruction text hash drift", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...exampleInput(),
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
reconstruction: {
|
||||
...exampleMethod().reconstruction,
|
||||
text_sha256: "0".repeat(64),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/text hash mismatch/u);
|
||||
});
|
||||
|
||||
it("rejects stale method locks", () => {
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...exampleInput(),
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
normalized_il_sha256: "6".repeat(64),
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/does not match/u);
|
||||
});
|
||||
|
||||
it("rejects reconstruction locks for partial CIL without normalized identity", () => {
|
||||
const input = exampleInput();
|
||||
const observed = managedMemberInspectionSchema.parse(
|
||||
input.static_members.normalized_result,
|
||||
);
|
||||
const method = observed.methods.items[0];
|
||||
if (method === undefined) throw new Error("missing observed method");
|
||||
const partial = {
|
||||
...observed,
|
||||
methods: {
|
||||
...observed.methods,
|
||||
items: [
|
||||
{
|
||||
...method,
|
||||
body: {
|
||||
...method.body,
|
||||
status: "partial" as const,
|
||||
normalized_il_sha256: null,
|
||||
truncated_instructions: 1,
|
||||
issue: "instruction limit reached",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
coverage: { state: "partial" as const, issues: [] },
|
||||
};
|
||||
const partialEvidence = createEvidence(
|
||||
undefined,
|
||||
input.static_members.provider,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: partial,
|
||||
rawResult: null,
|
||||
limitations: partial.limitations,
|
||||
},
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
importManagedReconstruction({
|
||||
...input,
|
||||
static_members: partialEvidence,
|
||||
methods: [
|
||||
{
|
||||
...exampleMethod(),
|
||||
normalized_il_sha256: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow(/does not match/u);
|
||||
});
|
||||
|
||||
it("wraps imported reconstruction in Evidence v2", () => {
|
||||
const evidence = importManagedReconstructionEvidence(exampleInput());
|
||||
|
||||
expect(evidence.ok).toBe(true);
|
||||
if (!evidence.ok) return;
|
||||
expect(evidence.value).toMatchObject({
|
||||
operation: "import_managed_reconstruction",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
normalized_result: {
|
||||
phase: "reconstruction-import",
|
||||
methods: [
|
||||
{
|
||||
reconstruction: {
|
||||
kind: "decompiled-csharp",
|
||||
language: "csharp",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+2
-77
@@ -1,4 +1,3 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
@@ -7,79 +6,16 @@ import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisExecution } from "../../../../src/application/AnalysisProvider.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import {
|
||||
managedArtifactInspectionSchema,
|
||||
managedMemberInspectionSchema,
|
||||
managedNativeBoundaryInspectionSchema,
|
||||
} from "../../../../src/domain/managedArtifact.js";
|
||||
import { inspectManagedArtifactBytes } from "../../../../src/dotnet/ManagedArtifactInspector.js";
|
||||
import { ManagedStaticProvider } from "../../../../src/dotnet/ManagedStaticProvider.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
buildNativePeFixture,
|
||||
} from "../../../fixtures/managedPe.js";
|
||||
|
||||
const limits = {
|
||||
referenceOffset: 0,
|
||||
referenceLimit: 100,
|
||||
resourceOffset: 0,
|
||||
resourceLimit: 100,
|
||||
attributeOffset: 0,
|
||||
attributeLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
describe("managed artifact failures", () => {
|
||||
it("reports native PE, malformed metadata, and bounded metadata failures as typed results", () => {
|
||||
const native = inspectManagedArtifactBytes(
|
||||
buildNativePeFixture(),
|
||||
target(buildNativePeFixture()),
|
||||
limits,
|
||||
);
|
||||
expect(native.classification.status).toBe("not-managed");
|
||||
expect(native.metadata.status).toBe("absent");
|
||||
expect(native.coverage.state).toBe("unavailable");
|
||||
|
||||
const malformedBytes = buildManagedPeFixture({
|
||||
corruptMetadataSignature: true,
|
||||
});
|
||||
const malformed = inspectManagedArtifactBytes(
|
||||
malformedBytes,
|
||||
target(malformedBytes),
|
||||
limits,
|
||||
);
|
||||
expect(malformed.classification.status).toBe("malformed");
|
||||
expect(malformed.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-metadata-root" }),
|
||||
]);
|
||||
|
||||
const unsupportedTableBytes = buildManagedPeFixture({
|
||||
metadataValidMaskExtra: 1n << 50n,
|
||||
});
|
||||
const unsupportedTable = inspectManagedArtifactBytes(
|
||||
unsupportedTableBytes,
|
||||
target(unsupportedTableBytes),
|
||||
limits,
|
||||
);
|
||||
expect(unsupportedTable.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid-tables" }),
|
||||
]);
|
||||
|
||||
const limited = inspectManagedArtifactBytes(
|
||||
buildManagedPeFixture(),
|
||||
target(buildManagedPeFixture()),
|
||||
{ ...limits, maxMetadataBytes: 256 },
|
||||
);
|
||||
expect(limited.metadata.status).toBe("partial");
|
||||
expect(limited.coverage.issues).toEqual([
|
||||
expect.objectContaining({ code: "limit-exceeded" }),
|
||||
]);
|
||||
});
|
||||
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed static provider path boundary", () => {
|
||||
it("executes as a read-only auxiliary provider with digest, cancellation, and format boundaries", async () => {
|
||||
const directory = await createTestTempDirectory("rea-managed-provider-");
|
||||
const bytes = buildManagedPeFixture();
|
||||
@@ -161,17 +97,6 @@ describe("managed artifact failures", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
const target = (bytes: Buffer): BinaryTarget => ({
|
||||
path: "/fixture.exe",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "pe",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
|
||||
const asManagedResult = (execution: AnalysisExecution) =>
|
||||
managedArtifactInspectionSchema.parse(execution.result);
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countExecutableSections,
|
||||
getExportedFunctions,
|
||||
getImportedDlls,
|
||||
hasPdbInfo,
|
||||
parseDebugType,
|
||||
parseImageCharacteristics,
|
||||
parseMachineType,
|
||||
parseSectionCharacteristics,
|
||||
peManifestSchema,
|
||||
type PeManifest,
|
||||
type PeSection,
|
||||
type PeImport,
|
||||
type PeExport,
|
||||
type PeResource,
|
||||
type PeDebugEntry,
|
||||
type PeTlsCallback,
|
||||
} from "../../../../src/domain/peInspection.js";
|
||||
|
||||
const validManifest: PeManifest = {
|
||||
dos_magic: 0x5a4d,
|
||||
pe_signature: 0x00004550,
|
||||
machine: "x64",
|
||||
number_of_sections: 3,
|
||||
timestamp: 0x12345678,
|
||||
is_dll: false,
|
||||
is_executable: true,
|
||||
is_console: true,
|
||||
entry_point: 0x1000,
|
||||
image_base: 0x400000,
|
||||
section_alignment: 0x1000,
|
||||
subsystem_version: "10.0",
|
||||
sections: [
|
||||
{
|
||||
name: ".text",
|
||||
virtual_size: 0x1000,
|
||||
virtual_address: 0x1000,
|
||||
raw_size: 0x1000,
|
||||
raw_offset: 0x400,
|
||||
characteristics: {
|
||||
has_code: true,
|
||||
has_initialized_data: false,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".data",
|
||||
virtual_size: 0x500,
|
||||
virtual_address: 0x2000,
|
||||
raw_size: 0x500,
|
||||
raw_offset: 0x1400,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ".rdata",
|
||||
virtual_size: 0x200,
|
||||
virtual_address: 0x3000,
|
||||
raw_size: 0x200,
|
||||
raw_offset: 0x1900,
|
||||
characteristics: {
|
||||
has_code: false,
|
||||
has_initialized_data: true,
|
||||
has_uninitialized_data: false,
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
imports: [
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "CreateFileW",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "KERNEL32.DLL",
|
||||
function_name: "WriteFile",
|
||||
ordinal: null,
|
||||
is_delay_import: false,
|
||||
},
|
||||
{
|
||||
dll: "USER32.DLL",
|
||||
function_name: "MessageBoxW",
|
||||
ordinal: 100,
|
||||
is_delay_import: false,
|
||||
},
|
||||
],
|
||||
exports: [
|
||||
{ name: "DllMain", ordinal: 1, rva: 0x1000, forwarder: null },
|
||||
{ name: "MyFunction", ordinal: 2, rva: 0x1050, forwarder: null },
|
||||
],
|
||||
resources: [
|
||||
{ type: "RT_VERSION", name: "1", language: 0x0409, rva: 0x4000, size: 100 },
|
||||
],
|
||||
debug_entries: [
|
||||
{
|
||||
type: "CODEVIEW",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: "AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP",
|
||||
pdb_age: 1,
|
||||
pdb_path: "C:\\src\\app.pdb",
|
||||
},
|
||||
],
|
||||
tls_callbacks: [{ callback_rva: 0x6000, index: 0 }],
|
||||
relocations_count: 50,
|
||||
image_characteristics: ["Executable", "Console"],
|
||||
};
|
||||
|
||||
describe("PE/COFF static inspection", () => {
|
||||
it("parses machine types", () => {
|
||||
expect(parseMachineType(0x014c)).toBe("x86");
|
||||
expect(parseMachineType(0x8664)).toBe("x64");
|
||||
expect(parseMachineType(0x01c0)).toBe("arm");
|
||||
expect(parseMachineType(0xaa64)).toBe("arm64");
|
||||
expect(parseMachineType(0x0200)).toBe("ia64");
|
||||
expect(parseMachineType(0xffff)).toBe("unknown");
|
||||
});
|
||||
|
||||
it("parses section characteristics", () => {
|
||||
const CODE = 0x00000020;
|
||||
const READ = 0x40000000;
|
||||
const EXECUTE = 0x20000000;
|
||||
const result = parseSectionCharacteristics(CODE | READ | EXECUTE);
|
||||
expect(result.has_code).toBe(true);
|
||||
expect(result.readable).toBe(true);
|
||||
expect(result.executable).toBe(true);
|
||||
expect(result.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("parses image characteristics", () => {
|
||||
const DLL = 0x2000;
|
||||
const EXEC = 0x0002;
|
||||
const flags = parseImageCharacteristics(DLL | EXEC);
|
||||
expect(flags).toContain("DLL");
|
||||
expect(flags).toContain("Executable");
|
||||
});
|
||||
|
||||
it("parses debug types", () => {
|
||||
expect(parseDebugType(2)).toBe("CODEVIEW");
|
||||
expect(parseDebugType(1)).toBe("COFF");
|
||||
expect(parseDebugType(99)).toBe("UNKNOWN");
|
||||
});
|
||||
|
||||
it("validates a well-formed manifest", () => {
|
||||
const result = peManifestSchema.safeParse(validManifest);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects PDB info", () => {
|
||||
expect(hasPdbInfo(validManifest)).toBe(true);
|
||||
const withoutPdb: PeManifest = {
|
||||
...validManifest,
|
||||
debug_entries: [
|
||||
{
|
||||
type: "COFF",
|
||||
rva: 0x5000,
|
||||
size: 100,
|
||||
pdb_guid: null,
|
||||
pdb_age: null,
|
||||
pdb_path: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(hasPdbInfo(withoutPdb)).toBe(false);
|
||||
});
|
||||
|
||||
it("gets imported DLLs", () => {
|
||||
const dlls = getImportedDlls(validManifest);
|
||||
expect(dlls).toHaveLength(2);
|
||||
expect(dlls).toContain("KERNEL32.DLL");
|
||||
expect(dlls).toContain("USER32.DLL");
|
||||
});
|
||||
|
||||
it("gets exported functions", () => {
|
||||
const exports = getExportedFunctions(validManifest);
|
||||
expect(exports).toHaveLength(2);
|
||||
expect(exports).toContain("DllMain");
|
||||
expect(exports).toContain("MyFunction");
|
||||
});
|
||||
|
||||
it("counts executable sections", () => {
|
||||
expect(countExecutableSections(validManifest)).toBe(1);
|
||||
});
|
||||
|
||||
it("uses all exported types", () => {
|
||||
const section: PeSection = validManifest.sections[0]!;
|
||||
expect(section.name).toBe(".text");
|
||||
const imp: PeImport = validManifest.imports[0]!;
|
||||
expect(imp.dll).toBe("KERNEL32.DLL");
|
||||
const exp: PeExport = validManifest.exports[0]!;
|
||||
expect(exp.name).toBe("DllMain");
|
||||
const res: PeResource = validManifest.resources[0]!;
|
||||
expect(res.type).toBe("RT_VERSION");
|
||||
const dbg: PeDebugEntry = validManifest.debug_entries[0]!;
|
||||
expect(dbg.type).toBe("CODEVIEW");
|
||||
const tls: PeTlsCallback = validManifest.tls_callbacks[0]!;
|
||||
expect(tls.index).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analyzeBytecodeArtifacts,
|
||||
bytecodeAnalysisSchema,
|
||||
classifyProvenance,
|
||||
detectArtifactFormat,
|
||||
detectBytecodeFamily,
|
||||
type BytecodeArtifact,
|
||||
type BytecodeSymbol,
|
||||
} from "../../../../src/domain/bytecodeProvider.js";
|
||||
|
||||
describe("bytecode provider", () => {
|
||||
it("detects JVM family from extensions", () => {
|
||||
expect(detectBytecodeFamily("App.class")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.jar")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("webapp.war")).toBe("jvm");
|
||||
expect(detectBytecodeFamily("app.ear")).toBe("jvm");
|
||||
});
|
||||
|
||||
it("detects Python family from extensions", () => {
|
||||
expect(detectBytecodeFamily("module.pyc")).toBe("python");
|
||||
expect(detectBytecodeFamily("module.pyo")).toBe("python");
|
||||
expect(detectBytecodeFamily("package.whl")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.pyz")).toBe("python");
|
||||
expect(detectBytecodeFamily("app.zipapp")).toBe("python");
|
||||
});
|
||||
|
||||
it("returns null for unknown extensions", () => {
|
||||
expect(detectBytecodeFamily("readme.txt")).toBeNull();
|
||||
expect(detectBytecodeFamily("script.js")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects artifact format from path", () => {
|
||||
expect(detectArtifactFormat("App.class")).toBe("class");
|
||||
expect(detectArtifactFormat("lib.jar")).toBe("jar");
|
||||
expect(detectArtifactFormat("web.war")).toBe("war");
|
||||
expect(detectArtifactFormat("mod.pyc")).toBe("pyc");
|
||||
expect(detectArtifactFormat("pkg.whl")).toBe("whl");
|
||||
expect(detectArtifactFormat("unknown.xyz")).toBeNull();
|
||||
});
|
||||
|
||||
it("classifies standard library provenance", () => {
|
||||
expect(classifyProvenance("/usr/lib/stdlib", "java.lang.String")).toBe(
|
||||
"standard_library",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/lib/python3.10/site-packages/numpy", "__init__"),
|
||||
).toBe("standard_library");
|
||||
});
|
||||
|
||||
it("classifies generated provenance", () => {
|
||||
expect(classifyProvenance("/build/generated/src", "GeneratedClass")).toBe(
|
||||
"generated",
|
||||
);
|
||||
expect(
|
||||
classifyProvenance("/__pycache__/module.cpython-310.pyc", "module"),
|
||||
).toBe("generated");
|
||||
});
|
||||
|
||||
it("classifies vendored provenance", () => {
|
||||
expect(classifyProvenance("/vendor/libs/lib.jar", "VendorLib")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
expect(classifyProvenance("/third_party/pkg/module.pyc", "module")).toBe(
|
||||
"vendored",
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies application provenance", () => {
|
||||
expect(classifyProvenance("/src/main/App.java", "com.example.App")).toBe(
|
||||
"application",
|
||||
);
|
||||
expect(classifyProvenance("/src/app.py", "main")).toBe("application");
|
||||
});
|
||||
|
||||
it("analyzes bytecode artifacts and computes summary", () => {
|
||||
const artifacts: BytecodeArtifact[] = [
|
||||
{
|
||||
path: "src/App.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 1000,
|
||||
digest: "a".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "com.example.App",
|
||||
raw_location: "0x1000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "application",
|
||||
is_public: true,
|
||||
},
|
||||
{
|
||||
name: "java.lang.String",
|
||||
raw_location: "0x2000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "standard_library",
|
||||
is_public: true,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: false,
|
||||
is_vendored: false,
|
||||
},
|
||||
{
|
||||
path: "lib/generated/Generated.class",
|
||||
family: "jvm",
|
||||
format: "class",
|
||||
size: 500,
|
||||
digest: "b".repeat(64),
|
||||
symbols: [
|
||||
{
|
||||
name: "GeneratedClass",
|
||||
raw_location: "0x3000",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "generated",
|
||||
is_public: false,
|
||||
},
|
||||
],
|
||||
is_standard_library: false,
|
||||
is_generated: true,
|
||||
is_vendored: false,
|
||||
},
|
||||
];
|
||||
const result = analyzeBytecodeArtifacts(artifacts, "jvm");
|
||||
expect(result.family).toBe("jvm");
|
||||
expect(result.total_symbols).toBe(3);
|
||||
expect(result.application_symbols).toBe(1);
|
||||
expect(result.standard_library_symbols).toBe(1);
|
||||
expect(result.generated_symbols).toBe(1);
|
||||
expect(result.vendored_symbols).toBe(0);
|
||||
|
||||
// Validate schema
|
||||
const parsed = bytecodeAnalysisSchema.safeParse(result);
|
||||
expect(parsed.success).toBe(true);
|
||||
});
|
||||
|
||||
it("uses BytecodeSymbol type", () => {
|
||||
const sym: BytecodeSymbol = {
|
||||
name: "com.example.Test",
|
||||
raw_location: "0x100",
|
||||
kind: "class",
|
||||
bytecode_version: 52,
|
||||
provenance: "application",
|
||||
is_public: true,
|
||||
};
|
||||
expect(sym.provenance).toBe("application");
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectNativeApiInspection } from "../../../../src/application/NativeApiInspection.js";
|
||||
import { functionDossierSchema } from "../../../../src/domain/hopperValues.js";
|
||||
import { nativeApiBoundarySchema } from "../../../../src/domain/nativeApiBoundary.js";
|
||||
import { ghidraFunctionDossier } from "../../../fixtures/ghidraFunction.js";
|
||||
|
||||
describe("native API inspection", () => {
|
||||
it("projects structured boundary evidence through inspectable substeps", () => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
|
||||
expect(projectNativeApiInspection(dossier)).toMatchObject({
|
||||
schema_version: 1,
|
||||
procedure: { address: "0x401000", name: "fixture_main" },
|
||||
boundary: {
|
||||
available: true,
|
||||
return_type: { data_type: "int", confidence: "medium" },
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: "0x401010",
|
||||
data_sources: [{ address: "0x403000" }],
|
||||
mappings: [
|
||||
{
|
||||
target_address: "0x401020",
|
||||
data_addresses: ["0x403000"],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
substeps: [
|
||||
{ operation: "analyze_function", status: "completed" },
|
||||
{ operation: "project_native_api_boundary", status: "completed" },
|
||||
{ operation: "preserve_residual_unknowns", status: "completed" },
|
||||
],
|
||||
unsupported_branches: [],
|
||||
residual_unknowns: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves unsupported provider branches as residual unknowns", () => {
|
||||
const value = ghidraFunctionDossier();
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
throw new TypeError("Ghidra dossier fixture is invalid");
|
||||
const dossier = functionDossierSchema.parse(
|
||||
Object.fromEntries(
|
||||
Object.entries(value).filter(([key]) => key !== "native_api"),
|
||||
),
|
||||
);
|
||||
|
||||
expect(projectNativeApiInspection(dossier)).toMatchObject({
|
||||
boundary: { available: false },
|
||||
unsupported_branches: [
|
||||
"structured-boundary-types",
|
||||
"jump-table-data-mapping",
|
||||
],
|
||||
residual_unknowns: [
|
||||
expect.stringContaining("boundary types"),
|
||||
expect.stringContaining("jump table"),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects boundary types placed in the wrong ABI role", () => {
|
||||
const boundary = functionDossierSchema.parse(
|
||||
ghidraFunctionDossier(),
|
||||
).native_api;
|
||||
if (boundary === null || boundary.available !== true)
|
||||
throw new TypeError("Ghidra native API fixture is unavailable");
|
||||
|
||||
expect(
|
||||
nativeApiBoundarySchema.safeParse({
|
||||
...boundary,
|
||||
return_type: { ...boundary.return_type, role: "parameter" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
nativeApiBoundarySchema.safeParse({
|
||||
...boundary,
|
||||
parameters: [
|
||||
{
|
||||
...boundary.return_type,
|
||||
role: "return",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,129 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
countMethodsByType,
|
||||
isDbSaveComplete,
|
||||
isGetterSelector,
|
||||
isSetterSelector,
|
||||
objcSwiftMetadataSchema,
|
||||
propertyNameFromSelector,
|
||||
swiftDeclsByKind,
|
||||
type ObjcClass,
|
||||
type ObjcMethod,
|
||||
type ObjcProperty,
|
||||
type DbOperation,
|
||||
type ObjcSwiftMetadata,
|
||||
type ObjcProtocol,
|
||||
type ObjcPropertyAttribute,
|
||||
type SwiftDecl,
|
||||
type DbSaveResult,
|
||||
} from "../../../../src/domain/objcSwiftMetadata.js";
|
||||
|
||||
describe("ObjC/Swift metadata", () => {
|
||||
it("identifies getter selectors", () => {
|
||||
expect(isGetterSelector("name")).toBe(true);
|
||||
expect(isGetterSelector("setName:")).toBe(false);
|
||||
expect(isGetterSelector("set")).toBe(true);
|
||||
});
|
||||
|
||||
it("identifies setter selectors", () => {
|
||||
expect(isSetterSelector("setName:")).toBe(true);
|
||||
expect(isSetterSelector("name")).toBe(false);
|
||||
});
|
||||
|
||||
it("extracts property name from selector", () => {
|
||||
expect(propertyNameFromSelector("name")).toBe("name");
|
||||
expect(propertyNameFromSelector("setName:")).toBe("name");
|
||||
expect(propertyNameFromSelector("set")).toBe("set");
|
||||
});
|
||||
|
||||
it("counts methods by type", () => {
|
||||
const methods: ObjcMethod[] = [
|
||||
{
|
||||
selector: "init",
|
||||
method_type: "instance",
|
||||
address: 0x1000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
{
|
||||
selector: "alloc",
|
||||
method_type: "class",
|
||||
address: 0x2000,
|
||||
is_required: false,
|
||||
is_optional: false,
|
||||
},
|
||||
];
|
||||
const counts = countMethodsByType(methods);
|
||||
expect(counts.instance).toBe(1);
|
||||
expect(counts.class).toBe(1);
|
||||
expect(counts.ivar_getter).toBe(0);
|
||||
expect(counts.ivar_setter).toBe(0);
|
||||
});
|
||||
|
||||
it("filters Swift declarations by kind", () => {
|
||||
const decls: SwiftDecl[] = [
|
||||
{
|
||||
kind: "class",
|
||||
name: "Foo",
|
||||
module: null,
|
||||
access_level: "public",
|
||||
super_class: null,
|
||||
protocols: [],
|
||||
is_final: false,
|
||||
is_required: false,
|
||||
is_convenience_init: false,
|
||||
is_override: false,
|
||||
},
|
||||
];
|
||||
const classes = swiftDeclsByKind(decls, "class");
|
||||
expect(classes).toHaveLength(1);
|
||||
expect(classes[0]!.name).toBe("Foo");
|
||||
});
|
||||
|
||||
it("checks database save completeness", () => {
|
||||
const result: DbSaveResult = {
|
||||
operation: "save",
|
||||
succeeded: true,
|
||||
preserved_names: 10,
|
||||
preserved_comments: 5,
|
||||
preserved_bookmarks: 3,
|
||||
database_path: "/tmp/db.hop",
|
||||
error: null,
|
||||
};
|
||||
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
|
||||
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
|
||||
});
|
||||
|
||||
it("validates a well-formed metadata result", () => {
|
||||
const meta = {
|
||||
objc_classes: [] as ObjcClass[],
|
||||
objc_protocols: [] as ObjcProtocol[],
|
||||
swift_decls: [] as SwiftDecl[],
|
||||
db_save_result: null,
|
||||
};
|
||||
const result = objcSwiftMetadataSchema.safeParse(meta);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("uses all exported types", () => {
|
||||
const prop: ObjcProperty = {
|
||||
name: "title",
|
||||
type_encoding: 'T@"NSString"&,N,V_title',
|
||||
attributes: [] as ObjcPropertyAttribute[],
|
||||
is_readonly: false,
|
||||
getter: "title",
|
||||
setter: "setTitle:",
|
||||
};
|
||||
expect(prop.name).toBe("title");
|
||||
const op: DbOperation = "save";
|
||||
expect(op).toBe("save");
|
||||
const meta: ObjcSwiftMetadata = {
|
||||
objc_classes: [],
|
||||
objc_protocols: [],
|
||||
swift_decls: [],
|
||||
db_save_result: null,
|
||||
};
|
||||
expect(meta.objc_classes).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -1,461 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
replayMachineRunInputSchema,
|
||||
runReplayMachine,
|
||||
} from "../../../../src/domain/replayMachineRun.js";
|
||||
|
||||
const loginRun = () =>
|
||||
replayMachineRunInputSchema.parse({
|
||||
machine: {
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_json", path: ["token"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "target-secret" },
|
||||
body: "target-secret",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "token",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
limits: {
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
},
|
||||
events: [
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 1,
|
||||
method: "post",
|
||||
path: "/login",
|
||||
headers: {},
|
||||
body: '{"token":"target-secret"}',
|
||||
},
|
||||
{
|
||||
protocol: "http",
|
||||
connection: "not_applicable",
|
||||
at_ms: 2,
|
||||
method: "GET",
|
||||
path: "/api",
|
||||
headers: { Authorization: "target-secret" },
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const parseMachineRun = (machine: unknown, events: unknown[]) =>
|
||||
replayMachineRunInputSchema.parse({ machine, events });
|
||||
|
||||
const httpEvent = (path: string, atMs = 0) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: atMs,
|
||||
method: "GET",
|
||||
path,
|
||||
headers: {},
|
||||
body: "",
|
||||
});
|
||||
|
||||
describe("direct replay machine execution", () => {
|
||||
it("returns actions, aliases, terminal state, and exact limit use", () => {
|
||||
const result = runReplayMachine(loginRun());
|
||||
|
||||
expect(result).toMatchObject({
|
||||
schema_version: 1,
|
||||
initial_state: "login",
|
||||
final_state: "complete",
|
||||
terminal: true,
|
||||
decisions: [
|
||||
{ event_sequence: 0, outcome: "matched", transition_sequence: 0 },
|
||||
{ event_sequence: 1, outcome: "matched", transition_sequence: 1 },
|
||||
],
|
||||
transition_journal: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
captured_aliases: [{ name: "token", sensitive: true }],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
captured_aliases: [],
|
||||
},
|
||||
],
|
||||
transition_actions: [
|
||||
{
|
||||
transition_id: "capture_token",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 204,
|
||||
headers: { "x-token": "<secret:token>" },
|
||||
body: "<secret:token>",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
transition_id: "authorize",
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: {},
|
||||
body: "done",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
limits: {
|
||||
configured: {
|
||||
transitions: 2,
|
||||
connections: 2,
|
||||
messages: 4,
|
||||
bytes: 1_000,
|
||||
duration_ms: 100,
|
||||
},
|
||||
usage: {
|
||||
offered_events: 2,
|
||||
admitted_events: 2,
|
||||
transitions: 2,
|
||||
connections: 0,
|
||||
messages: 0,
|
||||
bytes: 25,
|
||||
last_at_ms: 2,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("target-secret");
|
||||
});
|
||||
|
||||
it("classifies unmatched and guard-failed events without aborting", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
events: [httpEvent("/missing"), input.events[0]!, httpEvent("/api", 2)],
|
||||
});
|
||||
|
||||
expect(result.decisions.map(({ outcome }) => outcome)).toEqual([
|
||||
"unmatched",
|
||||
"matched",
|
||||
"guard_failed",
|
||||
]);
|
||||
});
|
||||
|
||||
it("classifies exhausted transitions", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "retry_once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/retry" },
|
||||
actions: [{ type: "http_response", status: 200, body: "retry" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 200, body: "done" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
},
|
||||
[httpEvent("/retry"), httpEvent("/retry", 1)],
|
||||
);
|
||||
|
||||
expect(
|
||||
runReplayMachine(input).decisions.map(({ outcome }) => outcome),
|
||||
).toEqual(["matched", "transition_exhausted"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine protocol and limits", () => {
|
||||
it("classifies reconnects that arrive in the wrong state", () => {
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "connected",
|
||||
states: [
|
||||
{ name: "connected" },
|
||||
{ name: "reconnecting" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "disconnect",
|
||||
from: "connected",
|
||||
to: "reconnecting",
|
||||
trigger: {
|
||||
protocol: "websocket_message",
|
||||
path: "/socket",
|
||||
body: "disconnect",
|
||||
},
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "reconnect",
|
||||
from: "reconnecting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: [{ type: "websocket_send", data: "ready" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
},
|
||||
[
|
||||
{
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/socket",
|
||||
headers: {},
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
expect(runReplayMachine(input).decisions[0]?.outcome).toBe(
|
||||
"unexpected_reconnect",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects protocol-inconsistent events at the boundary", () => {
|
||||
const input = loginRun();
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [{ ...httpEvent("/login"), method: null }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: [
|
||||
{
|
||||
...httpEvent("/login"),
|
||||
headers: { Authorization: "first", authorization: "second" },
|
||||
},
|
||||
],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("reports limit refusals without committing rejected usage", () => {
|
||||
const input = loginRun();
|
||||
const result = runReplayMachine({
|
||||
...input,
|
||||
machine: {
|
||||
...input.machine,
|
||||
limits: { ...input.machine.limits, bytes: 1 },
|
||||
},
|
||||
events: [input.events[0]!],
|
||||
});
|
||||
|
||||
expect(result.decisions).toEqual([
|
||||
{
|
||||
event_sequence: 0,
|
||||
outcome: "limit_exhausted",
|
||||
transition_sequence: null,
|
||||
},
|
||||
]);
|
||||
expect(result.limits.usage).toMatchObject({
|
||||
offered_events: 1,
|
||||
admitted_events: 0,
|
||||
transitions: 0,
|
||||
bytes: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("direct replay machine output bounds", () => {
|
||||
it("records large repeated actions once instead of amplifying each match", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const input = parseMachineRun(
|
||||
{
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 11 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "repeat",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/repeat" },
|
||||
actions: [{ type: "http_response", status: 200, body: largeBody }],
|
||||
max_uses: 10,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [{ type: "http_response", status: 204, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 11,
|
||||
},
|
||||
Array.from({ length: 10 }, (_, index) => httpEvent("/repeat", index)),
|
||||
);
|
||||
|
||||
const result = runReplayMachine(input);
|
||||
expect(result.transition_journal).toHaveLength(10);
|
||||
expect(result.transition_actions).toHaveLength(1);
|
||||
expect(JSON.stringify(result).length).toBeLessThan(1_100_000);
|
||||
});
|
||||
|
||||
it("rejects aggregate action output above four MiB", () => {
|
||||
const largeBody = "x".repeat(1_000_000);
|
||||
const parsed = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "send",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "websocket_connect", path: "/socket" },
|
||||
actions: Array.from({ length: 5 }, () => ({
|
||||
type: "websocket_send",
|
||||
data: largeBody,
|
||||
})),
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (!parsed.success)
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds action-field and sensitive-redaction work structurally", () => {
|
||||
const input = loginRun();
|
||||
const excessiveCaptures = replayMachineRunInputSchema.safeParse({
|
||||
...input,
|
||||
events: Array.from({ length: 1_025 }, () => input.events[0]),
|
||||
});
|
||||
expect(excessiveCaptures.success).toBe(false);
|
||||
if (!excessiveCaptures.success)
|
||||
expect(excessiveCaptures.error.issues).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ path: ["events"] })]),
|
||||
);
|
||||
|
||||
const excessiveFields = replayMachineRunInputSchema.safeParse({
|
||||
machine: {
|
||||
initial_state: "waiting",
|
||||
states: [{ name: "waiting" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "respond",
|
||||
from: "waiting",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{
|
||||
type: "http_response",
|
||||
status: 200,
|
||||
headers: Object.fromEntries(
|
||||
Array.from({ length: 1_024 }, (_, index) => [
|
||||
`x-field-${String(index)}`,
|
||||
"",
|
||||
]),
|
||||
),
|
||||
body: "",
|
||||
},
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 1,
|
||||
},
|
||||
events: [],
|
||||
});
|
||||
expect(excessiveFields.success).toBe(false);
|
||||
if (!excessiveFields.success)
|
||||
expect(excessiveFields.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ path: ["machine", "transitions"] }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,333 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "../../../../src/domain/replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "../../../../src/domain/replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("captures secret values in memory and journals aliases only", () => {
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: {
|
||||
transition_id: "capture_token",
|
||||
sensitive_aliases: ["session_value"],
|
||||
},
|
||||
});
|
||||
const expectedRedaction = ["Bearer <", "secret", ":session_value>"].join("");
|
||||
expect(runtime.redact("Bearer test-auth-token")).toBe(expectedRedaction);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", { Authorization: "test-auth-token" }),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(JSON.stringify(runtime.timeline)).not.toContain("test-auth-token");
|
||||
expect(runtime.state).toBe("complete");
|
||||
});
|
||||
|
||||
it("classifies wrong-state, guard, capture, and exhaustion failures", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("GET", "/api")),
|
||||
).toMatchObject({ outcome: "invalid_state" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(event("POST", "/login", "{}")),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
const runtime = new ReplayMachineRuntime(machine);
|
||||
runtime.dispatch(
|
||||
event("POST", "/login", '{"session_value":"test-auth-token"}'),
|
||||
);
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("GET", "/api", "", {
|
||||
authorization: "test-token-placeholder",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
outcome: "guard_failed",
|
||||
});
|
||||
const bounded = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [{ name: "active" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "once",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "GET", path: "/once" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
|
||||
outcome: "transition_exhausted",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches bounded headers and bodies and distinguishes wrong-state reconnects", () => {
|
||||
const runtime = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
initial_state: "connected",
|
||||
states: [{ name: "connected" }, { name: "done", terminal: true }],
|
||||
transitions: [
|
||||
{
|
||||
id: "finish",
|
||||
from: "connected",
|
||||
to: "done",
|
||||
trigger: {
|
||||
protocol: "http",
|
||||
method: "POST",
|
||||
path: "/finish",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: '{"done":true}',
|
||||
},
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "initial_socket",
|
||||
from: "connected",
|
||||
to: "connected",
|
||||
trigger: { protocol: "websocket_connect", path: "/ws" },
|
||||
actions: [{ type: "disconnect" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
}),
|
||||
);
|
||||
expect(runtime.dispatch(event("POST", "/finish", "wrong"))).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "initial",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "transition_exhausted" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/finish", '{"done":true}', {
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch({
|
||||
protocol: "websocket_connect",
|
||||
connection: "reconnect",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "",
|
||||
}),
|
||||
).toMatchObject({ outcome: "unexpected_reconnect" });
|
||||
});
|
||||
|
||||
it("enforces state, connection, message, byte, and duration limits", () => {
|
||||
const limitedMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 1 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "loop",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "websocket_message", path: "/ws" },
|
||||
actions: [{ type: "websocket_send", data: "ack" }],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "ok" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
limits: { connections: 1, messages: 1, bytes: 100, duration_ms: 10 },
|
||||
});
|
||||
const stateLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
stateLimited.dispatch({
|
||||
protocol: "websocket_message",
|
||||
connection: "not_applicable",
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const messageLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
states: limitedMachine.states.map((state) =>
|
||||
state.name === "active" ? { ...state, max_visits: 3 } : state,
|
||||
),
|
||||
}),
|
||||
);
|
||||
const message = {
|
||||
protocol: "websocket_message" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
headers: {},
|
||||
body: "one",
|
||||
};
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "matched",
|
||||
});
|
||||
expect(messageLimited.dispatch(message)).toMatchObject({
|
||||
outcome: "limit_exhausted",
|
||||
});
|
||||
const durationLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
durationLimited.dispatch({ ...event("GET", "/done"), at_ms: 11 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
expect(
|
||||
new ReplayMachineRuntime(limitedMachine).dispatch({
|
||||
...event("GET", "/done"),
|
||||
at_ms: Number.NaN,
|
||||
}),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const monotonic = new ReplayMachineRuntime(limitedMachine);
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 5 }),
|
||||
).toMatchObject({ outcome: "unmatched" });
|
||||
expect(
|
||||
monotonic.dispatch({ ...event("GET", "/missing"), at_ms: 4 }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
const byteLimited = new ReplayMachineRuntime(
|
||||
replayMachineSchema.parse({
|
||||
...limitedMachine,
|
||||
limits: { ...limitedMachine.limits, bytes: 4 },
|
||||
}),
|
||||
);
|
||||
expect(byteLimited.dispatch(event("GET", "/missing", "12345"))).toMatchObject(
|
||||
{ outcome: "limit_exhausted" },
|
||||
);
|
||||
const connectionLimited = new ReplayMachineRuntime(limitedMachine);
|
||||
const connect = {
|
||||
protocol: "websocket_connect" as const,
|
||||
connection: "initial" as const,
|
||||
at_ms: 0,
|
||||
method: null,
|
||||
path: "/unknown",
|
||||
headers: {},
|
||||
body: "",
|
||||
};
|
||||
expect(connectionLimited.dispatch(connect)).toMatchObject({
|
||||
outcome: "unmatched",
|
||||
});
|
||||
expect(
|
||||
connectionLimited.dispatch({ ...connect, connection: "reconnect" }),
|
||||
).toMatchObject({ outcome: "limit_exhausted" });
|
||||
});
|
||||
@@ -1,308 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { replayMachineSchema } from "../../../../src/domain/replayMachine.js";
|
||||
import { ReplayMachineRuntime } from "../../../../src/domain/replayMachineRuntime.js";
|
||||
|
||||
const machine = replayMachineSchema.parse({
|
||||
initial_state: "login",
|
||||
states: [
|
||||
{ name: "login" },
|
||||
{ name: "api" },
|
||||
{ name: "complete", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_token",
|
||||
from: "login",
|
||||
to: "api",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "POST", path: "/login" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["session_value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "authorize_api",
|
||||
from: "api",
|
||||
to: "complete",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/api" },
|
||||
guards: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_header", name: "authorization" },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
const event = (
|
||||
method: string,
|
||||
path: string,
|
||||
body = "",
|
||||
headers: Readonly<Record<string, string>> = {},
|
||||
) => ({
|
||||
protocol: "http" as const,
|
||||
connection: "not_applicable" as const,
|
||||
at_ms: 0,
|
||||
method,
|
||||
path,
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
|
||||
it("compares captured JSON values canonically", () => {
|
||||
const objectMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_profile",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_profile",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "profile",
|
||||
value: { source: "request_json", path: ["profile"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(objectMachine);
|
||||
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/capture", '{"profile":{"name":"A","id":1}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
runtime.dispatch(
|
||||
event("POST", "/guard", '{"profile":{"id":1,"name":"A"}}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
});
|
||||
|
||||
it("does not traverse inherited properties in JSON capture paths", () => {
|
||||
const inheritedPathMachine = replayMachineSchema.parse({
|
||||
...machine,
|
||||
transitions: machine.transitions.map((transition, index) =>
|
||||
index === 0
|
||||
? {
|
||||
...transition,
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: {
|
||||
source: "request_json" as const,
|
||||
path: ["__proto__", "toString"],
|
||||
},
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
: transition,
|
||||
),
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(inheritedPathMachine).dispatch(
|
||||
event("POST", "/login", "{}"),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
});
|
||||
|
||||
it("rejects non-string sensitive captures and retains rotated values", () => {
|
||||
expect(
|
||||
new ReplayMachineRuntime(machine).dispatch(
|
||||
event("POST", "/login", '{"session_value":1234}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const rotatingMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 3 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "rotate",
|
||||
from: "active",
|
||||
to: "active",
|
||||
trigger: { protocol: "http", method: "POST", path: "/rotate" },
|
||||
captures: [
|
||||
{
|
||||
variable: "session_value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
sensitive: true,
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 2,
|
||||
},
|
||||
{
|
||||
id: "finish",
|
||||
from: "active",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "GET", path: "/done" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 3,
|
||||
});
|
||||
const rotating = new ReplayMachineRuntime(rotatingMachine);
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"alpha"}'));
|
||||
rotating.dispatch(event("POST", "/rotate", '{"value":"beta"}'));
|
||||
const alias = ["<", "secret", ":session_value>"].join("");
|
||||
|
||||
expect(rotating.redact("alpha beta")).toBe(`${alias} ${alias}`);
|
||||
});
|
||||
|
||||
it("falls back to a lower-priority transition after a preferred one is exhausted", () => {
|
||||
const fallbackMachine = replayMachineSchema.parse({
|
||||
initial_state: "active",
|
||||
states: [
|
||||
{ name: "active", max_visits: 2 },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "preferred",
|
||||
from: "active",
|
||||
to: "active",
|
||||
priority: 10,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "again" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "fallback",
|
||||
from: "active",
|
||||
to: "done",
|
||||
priority: 20,
|
||||
trigger: { protocol: "http", method: "GET", path: "/next" },
|
||||
actions: [
|
||||
{ type: "http_response", status: 200, headers: {}, body: "done" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
const runtime = new ReplayMachineRuntime(fallbackMachine);
|
||||
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "preferred" },
|
||||
});
|
||||
expect(runtime.dispatch(event("GET", "/next"))).toMatchObject({
|
||||
outcome: "matched",
|
||||
transition: { transition_id: "fallback" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-finite parsed JSON captures and guard values", () => {
|
||||
const jsonMachine = replayMachineSchema.parse({
|
||||
initial_state: "capture",
|
||||
states: [
|
||||
{ name: "capture" },
|
||||
{ name: "guard" },
|
||||
{ name: "done", terminal: true },
|
||||
],
|
||||
transitions: [
|
||||
{
|
||||
id: "capture_value",
|
||||
from: "capture",
|
||||
to: "guard",
|
||||
trigger: { protocol: "http", method: "POST", path: "/capture" },
|
||||
captures: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
{
|
||||
id: "guard_value",
|
||||
from: "guard",
|
||||
to: "done",
|
||||
trigger: { protocol: "http", method: "POST", path: "/guard" },
|
||||
guards: [
|
||||
{
|
||||
variable: "value",
|
||||
value: { source: "request_json", path: ["value"] },
|
||||
},
|
||||
],
|
||||
actions: [
|
||||
{ type: "http_response", status: 204, headers: {}, body: "" },
|
||||
],
|
||||
max_uses: 1,
|
||||
},
|
||||
],
|
||||
max_transitions: 2,
|
||||
});
|
||||
|
||||
expect(
|
||||
new ReplayMachineRuntime(jsonMachine).dispatch(
|
||||
event("POST", "/capture", '{"value":1e400}'),
|
||||
),
|
||||
).toMatchObject({ outcome: "invalid_capture" });
|
||||
|
||||
const guarded = new ReplayMachineRuntime(jsonMachine);
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/capture", '{"value":null}')),
|
||||
).toMatchObject({ outcome: "matched" });
|
||||
expect(
|
||||
guarded.dispatch(event("POST", "/guard", '{"value":1e400}')),
|
||||
).toMatchObject({ outcome: "guard_failed" });
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseReplayWorkerResponse } from "../../../../src/replay/ReplayWorkerProtocol.js";
|
||||
|
||||
const digest = "1".repeat(64);
|
||||
const cases = [{ case_id: "case-1", sha256: digest }];
|
||||
const outcome = {
|
||||
case_id: "case-1",
|
||||
outcome: "return" as const,
|
||||
value: { parsed: true },
|
||||
input_sha256: digest,
|
||||
output_sha256: null,
|
||||
truncated: false as const,
|
||||
};
|
||||
|
||||
describe("replay worker protocol", () => {
|
||||
it("accepts only the exact committed case sequence", () => {
|
||||
expect(
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [outcome] },
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toMatchObject({ left: [outcome] });
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [{ ...outcome, case_id: "forged" }] },
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow("case identity changed");
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, input_sha256: "2".repeat(64) }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow("case identity changed");
|
||||
});
|
||||
|
||||
it("requires the exact differential shape and strict outcomes", () => {
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{ schema_version: 1, left: [outcome] },
|
||||
cases,
|
||||
"differential",
|
||||
),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, unexpected: true }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseReplayWorkerResponse(
|
||||
{
|
||||
schema_version: 1,
|
||||
left: [{ ...outcome, outcome: "exception", value: undefined }],
|
||||
},
|
||||
cases,
|
||||
"single",
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user