Files
reverse-engineering-anything/tests/acceptance/dotnetBundleJourney.test.ts
morluto 8ed819573b fix(artifacts): route native images to static readers and name their architecture (#14189)
* fix(artifacts): route native images to static readers and name their architecture

inspect_artifact sent every PE, ELF and Mach-O root straight to
open_binary (PE first to inspect_managed_artifact, whatever its CLI
header) and left architecture null on every inventory node and on the
inspection subject, although the header parsers already know the CPU.

Inventory classification now returns the header's CPU family with the
format, from the same ELF, Mach-O and PE record parsers target admission
uses, so each thin image node (including universal slices and archive
members) names its architecture; an undecoded machine stays null, and a
universal container node names none. When the inventory root is the
open target's own bytes, its Evidence subject carries the architecture
target admission parsed, as it already carried the selection.

Native next probes now list the provider-free readers for the format
before open_binary: PE imports, exports, load config, resources,
hardening and release exposure; ELF dependencies, exports, hardening and
release exposure; Mach-O inspect_macho, inspect_signature, hardening and
release exposure. inspect_managed_artifact leads only when the PE
declares a CLI header, is omitted when it declares none, and stays a
conditional probe for directory members whose declaration is unknown.
The PE hypothesis that inventory cannot tell managed from native is kept
only for that unknown case.

Fixes #14157

* fix(artifacts): keep native readers for executables that carry a package

An executable whose contents inventory as an embedded package (Godot
PCK, PyInstaller, Node SEA, Deno, Bun or a .NET single-file bundle) is
also a native image. Previously inspection proposed only the package
reader and hid the native side.

The inspection now takes the native image facts that target admission
parsed for the root's own bytes, not only the PE CLI-header flag. When
inventory reads those bytes as a package, the package reader comes
first, then the carrier's static readers, then open_binary.

A probe names exactly one operation, so the static readers cannot be
grouped into one entry without changing the advertised schema. They
stay separate rows and share one short rationale, because each tool's
description already says what it reads. Each format's reader list is
now a table.

* fix(artifacts): bind a deep provider for managed PEs only at a native boundary

A PE declaring a CLI header recommended open_binary with generic
function-level advice, so pure managed assemblies were steered to a
deep native provider. Its rationale again requires managed inspection
to report a native or mixed boundary, and a PE whose header is unknown
states the same condition.

* test(artifacts): assert universal slice inventory per host and prune probe snapshots

The universal Mach-O test assumed slice inventory on every host, but the
slice reader runs native lipo and is skipped off macOS, so it failed on the
Linux test shards and portable tests. The test now selects the host platform
through a HostPlatform mock: the slice inventory case runs only on a macOS
host, and the other-host case asserts unknown container coverage with only
the file occurrence on every host. Both keep the selected-slice subject
architecture and static reader order.

Pruning in the probe tests:
- Merge the ARM64 PE, ELF and Mach-O single-image probe tests into one
  parameterised case that asserts subject and root-node architecture, the
  complete static reader list, and that open_binary is the only probe beyond
  artifact bytes.
- Remove the Deno carrier ordering case from the native image probe test;
  the Deno CLI acceptance test covers the same three carriers through the
  public workflow and now asserts the same ordering and authority facts.
- Replace full next-probe arrays in the Bun, Deno, dotnet-bundle and
  PyInstaller CLI/MCP tests with a shared carrier assertion: package readers
  lead, the carrier's format reader is present, and open_binary is last and
  the only non-artifact-bytes probe. The per-format reader list stays owned
  by the native image probe test.

Malformed-header (undecoded machine), unknown architecture and package
subject identity coverage are unchanged.
2026-11-24 00:27:11 +00:00

266 lines
9.0 KiB
TypeScript

import { createHash } from "node:crypto";
import { readFile, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { afterAll, expect } from "vitest";
import { dotnetBundleFixture } from "../../src/artifacts/dotnet/DotnetBundle.fixture.js";
import { cArchiveExecutable } from "../../src/artifacts/pyinstaller/CArchive.fixture.js";
import { artifactExtractionResultSchema } from "../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import {
analysisViewResultSchema,
artifactInventorySummaryViewResultSchema,
} from "../../src/domain/analysisView/analysisViewResult.js";
import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js";
import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js";
import { expectCarrierProbes } from "../fixtures/nativeCarrierProbes.js";
// Compile SDK output validators for the tools a test calls, not the whole catalog.
const schemaValidation = createMcpSchemaValidation();
afterAll(() => schemaValidation.clear());
const checkProjectedMember = async (
client: Client,
expectedHostHash: string,
memberPath: string,
expectedHash: string,
) => {
const reply = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "summary" },
});
expect(reply.isError).not.toBe(true);
const summary = artifactInventorySummaryViewResultSchema.parse(
parseEvidence(reply.structuredContent).normalized_result,
);
expect(summary.summary.manifest.root_sha256).toBe(expectedHostHash);
const parentId = summary.parent_evidence_id;
expect(parseEvidence(reply.structuredContent).evidence_links).toContain(
parentId,
);
expect(summary.summary.source_complete).toBe(true);
const source = { kind: "retained-evidence", evidence_id: parentId };
const read = async (view: Record<string, unknown>) => {
const result = await client.callTool({
name: "inspect_analysis_view",
arguments: { source, view },
});
expect(result.isError).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(result.structuredContent).normalized_result,
);
if (page.kind !== "inventory") throw new Error("Unexpected view kind");
return page;
};
const occurrences = await read({
kind: "inventory",
collection: "occurrences",
logical_paths: [memberPath],
fields: ["logical_path", "format_metadata", "source_location"],
limit: 1,
});
expect(occurrences.parent_evidence_id).toBe(parentId);
expect(occurrences.items).toHaveLength(1);
const member = occurrences.items[0];
if (
member === undefined ||
!("occurrence_id" in member) ||
!("artifact_id" in member)
)
throw new Error("Expected a projected occurrence");
expect(member).toMatchObject({
logical_path: memberPath,
format_metadata: { kind: "dotnet-bundle-entry", major_version: 6 },
});
expect(member).not.toHaveProperty("limitations");
const nodes = await read({
kind: "inventory",
collection: "nodes",
artifact_ids: [member.artifact_id],
fields: ["sha256"],
limit: 1,
});
expect(nodes.items).toEqual([
{ artifact_id: member.artifact_id, sha256: expectedHash },
]);
};
for (const format of ["dotnet-bundle", "pyinstaller"] as const) {
test(`inspects and extracts ${format} through public CLI and stdio MCP`, async ({
cli,
workspace,
}) => {
const member =
format === "dotnet-bundle"
? Buffer.from("source-owned compressed resource ".repeat(1024))
: dotnetBundleFixture().bytes;
const memberPath =
format === "dotnet-bundle" ? "data/resource.txt" : "helper.exe";
const bytes =
format === "dotnet-bundle"
? dotnetBundleFixture([
{ path: memberPath, bytes: member, compressed: true, fileType: 0 },
]).bytes
: cArchiveExecutable({
layout: "2.1",
pythonVersion: 313,
members: [
{
name: memberPath,
typeCode: "b",
payload: member,
compress: false,
},
],
});
const path = workspace.path("renamed.bin");
await writeFile(path, bytes);
const environment = {
PATH: process.env.PATH ?? "",
HOME: workspace.root,
USERPROFILE: workspace.root,
XDG_CONFIG_HOME: workspace.path("config"),
XDG_CACHE_HOME: workspace.path("cache"),
XDG_STATE_HOME: workspace.path("state"),
REA_LOG_LEVEL: "silent",
HOPPER_LAUNCHER_PATH: workspace.path("unavailable-hopper"),
GHIDRA_INSTALL_DIR: workspace.path("unavailable-ghidra"),
};
const outputs: string[] = [];
const client = new Client(
{
name: "rea-dotnet-bundle-acceptance",
version: "1",
},
{ jsonSchemaValidator: schemaValidation },
);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
env: environment,
stderr: "pipe",
});
const checkExtraction = async (value: unknown) => {
const extraction = artifactExtractionResultSchema.parse(
parseEvidence(value).normalized_result,
);
outputs.push(extraction.output_root);
expect(extraction.containment_verified).toBe(true);
expect(
(await readFile(join(extraction.output_root, memberPath))).equals(
member,
),
).toBe(true);
};
try {
const inspected = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
environment,
});
expect(inspected.exitCode, inspected.stderr).toBe(0);
const inventory = artifactInspectionResultSchema.parse(
parseEvidence(inspected.json).normalized_result,
);
expect(inventory.subject).toMatchObject({
root_format: format,
root_sha256: createHash("sha256").update(bytes).digest("hex"),
});
if (format === "dotnet-bundle") {
// The apphost carrier is a PE, so its readers follow the package's.
expectCarrierProbes(inventory.next_probes, "pe", ["extract_artifact"]);
}
expect(
inventory.unexplored_branches.map(({ next_probe }) => next_probe),
).toEqual(inventory.next_probes);
const extracted = await cli.run({
arguments: ["extract-artifact", path, "--json"],
environment,
});
expect(extracted.exitCode, extracted.stderr).toBe(0);
await checkExtraction(extracted.json);
await client.connect(transport);
await client.listTools();
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const observed = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(observed.isError, JSON.stringify(observed)).not.toBe(true);
expect(
artifactInspectionResultSchema.parse(
parseEvidence(observed.structuredContent).normalized_result,
),
).toEqual(inventory);
if (format === "dotnet-bundle")
await checkProjectedMember(
client,
inventory.subject.root_sha256,
memberPath,
createHash("sha256").update(member).digest("hex"),
);
const materialized = await client.callTool({
name: "extract_artifact",
arguments: {},
});
expect(materialized.isError, JSON.stringify(materialized)).not.toBe(true);
await checkExtraction(materialized.structuredContent);
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
expect((await readFile(path)).equals(bytes)).toBe(true);
} finally {
await client.close();
await Promise.all(
outputs.map((output) => rm(output, { recursive: true, force: true })),
);
}
});
}
test("reports excessive bundle path depth as a public CLI limit", async ({
cli,
workspace,
}) => {
const path = workspace.path("deep-host.exe");
await writeFile(
path,
dotnetBundleFixture([
{ path: `${"a/".repeat(256)}file`, bytes: Buffer.alloc(0) },
]).bytes,
);
const result = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode, result.stderr).toBe(1);
expect(result.json).toMatchObject({
code: "truncated",
category: "truncated",
retryable: true,
details: {
reason: "limit",
truncated: true,
boundary: "capacity",
reader_limit: {
parameter: "artifact_limits.dotnet_bundle.path_parts",
effective_value: 256,
required_value: 257,
unit: "count",
can_increase: true,
},
},
});
});