fix(native): preserve universal Mach-O container identity

Keep FAT container format distinct from selected slice architecture through target admission, Evidence, snapshots, and CLI/MCP lifecycle results. Preserve native, Hopper, Ghidra, extraction, and dylib routing for the Mach-O family.

Reject selected FAT ranges overlapping their table or too short for a Mach-O header. Replace empty-slice fixtures with in-bounds executable headers and cover thin, universal, single-slice, FAT64, and swapped containers.

Validation: static and architecture checks, generated docs, targeted producer and public MCP tests. Provider routing uses controlled fixtures; no live Hopper, IDA, JADX, or Ghidra analysis was performed for this change.
This commit is contained in:
morluto
2026-10-12 09:29:07 +08:00
parent 87b9793c53
commit b38429cb6a
28 changed files with 608 additions and 143 deletions
@@ -20,12 +20,47 @@ import {
} from "../../../src/application/AppBundleExecutable.js";
import {
dosMz,
fat,
pe,
thinMach,
} from "../../../src/domain/binaryTarget.fixture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.each([{ cpus: [0x0100000c] }, { cpus: [0x01000007, 0x0100000c] }])(
"preserves a FAT container's format in the resolved target and Evidence ($cpus)",
async ({ cpus }) => {
const directory = await createTestTempDirectory("rea-universal-target-");
const path = join(directory, "image");
await writeFile(path, fat(cpus));
const resolved = await parseBinaryTarget(path, {
hostArchitecture: "arm64",
});
if (!resolved.ok) throw resolved.error;
expect(resolved.value).toMatchObject({
kind: "executable",
format: "mach-o-universal",
architecture: "arm64",
});
const evidence = createEvidence(
resolved.value,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "inspect_macho",
parameters: {},
result: null,
},
);
expect(
parseEvidence(JSON.parse(JSON.stringify(evidence))).subject,
).toMatchObject({
format: "mach-o-universal",
architecture: "arm64",
});
},
);
describe("binary target I/O: app plist permissions and decoding", () => {
it.each([
["EACCES", "permission denied reading app Info.plist"],
@@ -8,11 +8,13 @@ import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
CPU,
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
dyldEnvironmentCommand,
fatImage,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
@@ -112,6 +114,44 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
});
});
it("traces architecture slices from a universal Mach-O target", async () => {
const root = await createTestTempDirectory("rea-dylib-universal-");
const executable = join(root, "Universal");
const cpu = process.arch === "arm64" ? CPU.arm64 : CPU.x86_64;
const architecture = process.arch === "arm64" ? "arm64" : "x86_64";
await writeFile(
executable,
fatImage([
{
cpu,
bytes: machoImage({
cpu,
commands: [buildVersionCommand(1)],
}),
},
]),
);
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: executable },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: { architecture },
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const trace = dylibResolutionResultSchema.parse(
structuredResult(called.structuredContent),
);
expect(trace.roots).toEqual([{ image: "Universal", architecture }]);
});
});
it("rejects targets that are not Mach-O", async () => {
const directory = await createTestTempDirectory("rea-dylib-mcp-plist-");
const path = join(directory, "Info.plist");
@@ -7,57 +7,75 @@ import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js"
import {
machoImage,
rpathCommand,
CPU,
fatImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
it("rejects changed signature targets through MCP and accepts reopening the new version", async () => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
await writeFile(path, machoImage({}));
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
expect((await open()).isError).not.toBe(true);
await writeFile(
path,
machoImage({ commands: [rpathCommand("new-version")] }),
it.each(["mach-o", "mach-o-universal"] as const)(
"rejects changed %s signature targets through MCP and accepts reopening the new version",
async (format) => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
});
const image = (commands: readonly Uint8Array[] = []) =>
format === "mach-o"
? machoImage({ commands })
: fatImage(
[CPU.arm64, CPU.x86_64].map((cpu) => ({
cpu,
bytes: machoImage({ cpu, commands }),
})),
);
await writeFile(path, image());
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
const opened = await open();
expect(opened.isError).not.toBe(true);
expect(
toolContract("open_binary").outputSchema.parse(opened.structuredContent)
.result,
).toMatchObject({ format });
await writeFile(path, image([rpathCommand("new-version")]));
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
subject: { format },
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
},
);
@@ -0,0 +1,73 @@
import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
const sliceReader = vi.hoisted(() => ({
reached: vi.fn(),
failure: null as unknown,
}));
vi.mock("../../../../src/artifacts/MachOSliceArtifactReader.js", () => ({
MachOSliceArtifactReader: class {
async *entries() {
sliceReader.reached();
yield* [];
throw sliceReader.failure;
}
close() {
return Promise.resolve();
}
provenance() {
return [];
}
},
}));
it("routes universal Mach-O extraction through slice inventory", async () => {
sliceReader.reached.mockClear();
sliceReader.failure = new ArtifactReaderFailure(
"unavailable",
"fixture reached universal slice inventory",
);
const root = await createTestTempDirectory("rea-extract-universal-");
const image = join(root, "Universal");
await writeFile(image, Buffer.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0]));
const output = join(root, "output");
const result = await new ArtifactProvider(process.env)
.createClient(universalTarget(image))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "ArtifactOperationError",
reason: "unavailable",
detail: "fixture reached universal slice inventory",
},
});
expect(sliceReader.reached).toHaveBeenCalledOnce();
await expect(access(output)).rejects.toThrow();
});
const universalTarget = (path: string): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "executable",
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["arm64"],
});