chore: merge main into feat/signature-posture

This commit is contained in:
morluto
2026-10-08 15:49:33 +08:00
85 changed files with 6711 additions and 105 deletions
@@ -0,0 +1,244 @@
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { describe, expect } from "vitest";
import {
FILE_TYPE,
LC,
dylibCommand,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const ENVIRONMENT = { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" };
const writeFiles = async (
root: string,
files: Readonly<Record<string, string | Uint8Array>>,
): Promise<void> => {
for (const [path, content] of Object.entries(files)) {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), content);
}
};
const fixtureApp = async (): Promise<string> => {
const app = join(
await createTestTempDirectory("rea-dylib-cli-"),
"Fixture.app",
);
await writeFiles(app, {
"Contents/Info.plist":
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
"Contents/MacOS/App": machoImage({
commands: [
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libgone.dylib"),
],
}),
"Contents/Frameworks/libcore.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib")],
}),
"Contents/Helpers/tool": machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib")],
}),
});
return app;
};
const withBrokenHelper = async (app: string): Promise<void> => {
const broken = machoImage({ commands: [rpathCommand("x")] });
// cmdsize 0 makes the command table unreadable.
new DataView(broken.buffer).setUint32(32 + 4, 0, true);
await writeFiles(app, { "Contents/Helpers/broken": broken });
};
describe("trace-dylib-resolution CLI", () => {
cliTest("traces every executable root of an app bundle", async ({ cli }) => {
const app = await fixtureApp();
const result = await cli.run({
arguments: ["trace-dylib-resolution", app, "--json"],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.root_path).toBe(app);
expect(trace.roots.map(({ image }) => image)).toEqual([
"Contents/Helpers/tool",
"Contents/MacOS/App",
]);
expect(
trace.edges.map(({ loader, install_name: name, resolution }) => [
loader,
name,
resolution.status,
resolution.image,
]),
).toEqual([
[
"Contents/Helpers/tool",
"@loader_path/libnone.dylib",
"unresolved",
null,
],
[
"Contents/MacOS/App",
"@rpath/libcore.dylib",
"resolved",
"Contents/Frameworks/libcore.dylib",
],
["Contents/MacOS/App", "@rpath/libgone.dylib", "unresolved", null],
]);
expect(trace.findings.map(({ kind }) => kind)).toEqual([
"required-load-unresolved",
"weak-load-unresolved",
]);
expect(
trace.images.every(({ sha256 }) => /^[0-9a-f]{64}$/u.test(sha256)),
).toBe(true);
});
cliTest(
"narrows roots and architecture, and rejects escaping roots",
async ({ cli }) => {
const app = await fixtureApp();
const narrowed = await cli.run({
arguments: [
"trace-dylib-resolution",
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64",
"--json",
],
environment: ENVIRONMENT,
});
expect(narrowed.exitCode).toBe(0);
expect(
(narrowed.json as { normalized_result: { roots: unknown } })
.normalized_result.roots,
).toEqual([{ image: "Contents/MacOS/App", architecture: "arm64" }]);
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
for (const root of [
"../outside",
"Contents/Info.plist",
"Contents/Linked/Tool",
]) {
const rejected = await cli.run({
arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
environment: ENVIRONMENT,
});
expect(rejected.exitCode).toBe(1);
expect(rejected.json).toMatchObject({ error: "Analysis failed" });
}
},
);
cliTest(
"resolves a standalone Mach-O against its own directory",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-standalone-");
await writeFiles(directory, {
tool: machoImage({
commands: [
dylibCommand(LC.LOAD_DYLIB, "@loader_path/lib/libhelper.dylib"),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/../escape.dylib"),
],
}),
"lib/libhelper.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
"unrelated.txt": "not traversed",
});
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
join(directory, "tool"),
"--json",
],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.roots).toEqual([{ image: "tool", architecture: "arm64" }]);
expect(trace.edges.map(({ resolution }) => resolution)).toEqual([
{ status: "resolved", image: "lib/libhelper.dylib" },
{ status: "undetermined", image: null },
]);
},
);
cliTest(
"reports unparsed Mach-O files found while enumerating roots",
async ({ cli }) => {
const app = await fixtureApp();
await withBrokenHelper(app);
const result = await cli.run({
arguments: ["trace-dylib-resolution", app, "--json"],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
(result.json as { normalized_result: unknown }).normalized_result,
);
expect(trace.coverage).toMatchObject({
status: "partial",
unparsed_images: ["Contents/Helpers/broken"],
});
},
);
});
describe.skipIf(process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
"reports an unreadable dependency as a permission failure",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-denied-");
await writeFiles(directory, {
tool: machoImage({
commands: [
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libsecret.dylib"),
],
}),
"libsecret.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
});
await chmod(join(directory, "libsecret.dylib"), 0o000);
try {
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
join(directory, "tool"),
"--json",
],
environment: ENVIRONMENT,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
details: {
reason: "unavailable",
detail: expect.stringContaining(
"Permission denied (EACCES) reading libsecret.dylib",
),
},
});
} finally {
await chmod(join(directory, "libsecret.dylib"), 0o644);
}
},
);
},
);
@@ -1,3 +1,4 @@
import { EVMOLE_PROVIDER_IDENTITY } from "../../../src/evm/EvmoleRelease.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -117,6 +118,7 @@ describe("canonical product catalog", () => {
IDA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
PWNTOOLS_PROVIDER_IDENTITY,
EVMOLE_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
ANDROID_APPLICATION_PROVIDER,
APPLE_APPLICATION_PROVIDER,
@@ -0,0 +1,597 @@
import { createHash } from "node:crypto";
import { access, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { evmInterfaceSchema } from "../../../src/domain/evm/evmInterface.js";
import { EvmoleInterfaceProvider } from "../../../src/evm/EvmoleInterfaceProvider.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
const unsupportedHost = process.platform !== "linux" || process.arch !== "x64";
const requestSchema = z.strictObject({
snapshot_path: z.string(),
reply_path: z.string(),
failure_marker_path: z.string(),
encoding: z.enum(["raw", "hex"]),
});
const fixture = async () => {
const workspace = await createTestWorkspace("rea-evm-interface-boundary-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = join(workspace.root, "selected.hex");
await writeFile(path, "0x60006000f3\n");
return { path, root: workspace.root };
};
it.runIf(!unsupportedHost).each(["SIGXCPU", "SIGXFSZ", "EFBIG"])(
"preserves %s with configured limits distinct from unknown effective limits",
async (failure) => {
const { path } = await fixture();
let ownedPath = "";
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
ownedPath = spawn.cwd ?? "";
if (failure === "EFBIG")
await writeFile(join(ownedPath, "resource.failure"), "F");
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: [
"-e",
failure === "EFBIG"
? 'process.stdout.write("resource diagnostic", () => { process.exitCode = 76; })'
: failure === "SIGXFSZ"
? 'process.on("SIGXFSZ", () => { process.removeAllListeners("SIGXFSZ"); process.kill(process.pid, "SIGXFSZ"); }); process.stdout.write("resource diagnostic", () => process.kill(process.pid, "SIGXFSZ")); setTimeout(() => {}, 1000);'
: `process.stdout.write("resource diagnostic", () => process.kill(process.pid, "${failure}"))`,
],
});
});
const result = await provider.inspect({ path, encoding: "hex" });
if (result.ok) throw new Error("Expected observed resource failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "resource_constraint",
details: {
resource: failure === "SIGXCPU" ? "cpu" : "file-size",
reported_limits: {
configured_soft_limits: { cpu_seconds: expect.any(Number) },
effective_soft_limits: null,
},
captured_output: { stdout: "resource diagnostic", truncated: false },
},
});
expect(result.error.message).toContain(
failure === "EFBIG" ? "exact write failure cause" : "exact signal cause",
);
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost).each(["missing", "wrong"])(
"does not classify a launcher exit 76 with %s worker failure evidence",
async (scenario) => {
const { path } = await fixture();
let ownedPath = "";
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
ownedPath = spawn.cwd ?? "";
if (scenario === "wrong")
await writeFile(
join(ownedPath, "resource.failure"),
Buffer.from([0xc6]),
);
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: [
"-e",
'process.stdout.write("launcher failure", () => { process.exitCode = 76; });',
],
});
});
const result = await provider.inspect({ path, encoding: "hex" });
if (result.ok) throw new Error("Expected launcher failure");
expect(projectAnalysisError(result.error).code).toBe("execution_failure");
expect(result.error).toMatchObject({
diagnostics: {
file_size_failure_marker: {
verified: false,
failure: expect.any(String),
},
captured_output: { stdout: "launcher failure", truncated: false },
},
});
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost)(
"retains actual diagnostic truncation when overflow and process cleanup both fail",
async () => {
const { path } = await fixture();
let ownedPath = "";
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
ownedPath = spawn.cwd ?? "";
const launched = await spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", 'process.stdout.write("x".repeat(1048577))'],
});
return {
...launched,
cleanup: async () => {
await launched.cleanup?.();
throw new Error("injected post-cleanup reporting failure");
},
};
});
const result = await provider.inspect({ path, encoding: "hex" });
if (result.ok) throw new Error("Expected compounded lifecycle failure");
expect(result.error).toMatchObject({
cleanupIncomplete: true,
diagnostics: {
reason: "injected post-cleanup reporting failure",
previous_error: { failure_kind: "output-limit" },
captured_output: { truncated: true, stderr: "" },
},
});
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost).each([1048576, 1048577])(
"keeps complete diagnostics or rejects a valid worker reply with %s diagnostic bytes",
async (size) => {
const { path } = await fixture();
let ownedPath = "";
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
ownedPath = spawn.cwd ?? "";
const requestPath = spawn.arguments.at(-1);
if (requestPath === undefined) throw new Error("Request missing");
const request = requestSchema.parse(
JSON.parse(await readFile(requestPath, "utf8")),
);
const bytes = Buffer.from("60006000f3", "hex");
await writeFile(
request.reply_path,
JSON.stringify({
ok: true,
version: "0.9.3",
bytecode: {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
hex: bytes.toString("hex"),
},
raw: { functions: [] },
}),
);
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", `process.stderr.write("x".repeat(${String(size)}))`],
});
});
const result = await provider.inspect({ path, encoding: "hex" });
if (size === 1048576) {
if (!result.ok) throw result.error;
const report = evmInterfaceSchema.parse(result.value.result);
expect(report.diagnostics.stderr).toHaveLength(size);
expect(report.diagnostics.truncated).toBe(false);
} else {
if (result.ok)
throw new Error("Expected explicit diagnostic budget failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "unreadable_output",
details: { captured_output: { truncated: true } },
});
}
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it
.runIf(!unsupportedHost)
.each([
"success",
"format",
"unsupported",
"wrong-version",
"wrong-decoded-carrier",
"broken-reply",
"out-of-range-body",
])(
"binds source carrier/worker representation and releases owned files: %s",
async (scenario) => {
const { path } = await fixture();
let ownedRoot = "";
const provider = new EvmoleInterfaceProvider(
{ NODE_OPTIONS: "--inspect=0" },
async (spawn) => {
ownedRoot = spawn.cwd ?? "";
expect(spawn.hostEnvironment?.NODE_OPTIONS).toBeUndefined();
expect(spawn.arguments).toContain("--as=3221225472:");
expect(spawn.arguments).toContain("--disable-wasm-trap-handler");
const requestPath = spawn.arguments.at(-1);
if (requestPath === undefined) throw new Error("request missing");
const request = requestSchema.parse(
JSON.parse(await readFile(requestPath, "utf8")),
);
expect(request.encoding).toBe("hex");
expect(await readFile(request.snapshot_path, "utf8")).toBe(
"0x60006000f3\n",
);
const hex = scenario === "wrong-decoded-carrier" ? "00" : "60006000f3";
const bytes = Buffer.from(hex, "hex");
await writeFile(
request.reply_path,
scenario === "broken-reply"
? "broken"
: JSON.stringify(
["format", "unsupported"].includes(scenario)
? {
ok: false,
reason: scenario,
message: "Malformed hex carrier.",
}
: {
ok: true,
version: scenario === "wrong-version" ? "0.0.0" : "0.9.3",
bytecode: {
sha256: createHash("sha256")
.update(bytes)
.digest("hex"),
bytes: bytes.length,
hex,
},
raw: {
functions:
scenario === "out-of-range-body"
? [
{
selector: "aabbccdd",
bytecodeOffset: 5,
dispatch: "abi",
},
]
: [],
},
},
),
);
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", 'process.stderr.write("upstream warning")'],
});
},
);
const result = await provider.inspect({ path, encoding: "hex" });
if (scenario === "success") {
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
artifact: { path, encoding: "hex", bytes: 13 },
bytecode: { hex: "60006000f3", bytes: 5 },
diagnostics: { stderr: "upstream warning" },
});
expect(result.value.rawResult).toEqual({ functions: [] });
} else
expect(result).toMatchObject({
ok: false,
error: {
_tag:
scenario === "format"
? "AnalysisInputError"
: scenario === "unsupported"
? "AnalysisUnsupportedTargetError"
: "AnalysisOutputError",
},
});
if (!result.ok)
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
captured_output: {
stdout: "",
stderr: "upstream warning",
truncated: false,
},
},
});
expect(await readFile(path, "utf8")).toBe("0x60006000f3\n");
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost).each(["cancelled", "output-limit", "process"])(
"preserves lifecycle failure and independently releases an acquired worker: %s",
async (scenario) => {
const { path } = await fixture();
const controller = new AbortController();
let pid: number | undefined;
let ownedRoot = "";
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
ownedRoot = spawn.cwd ?? "";
const launched = await spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: [
"-e",
scenario === "cancelled"
? 'process.stdout.write("ready\\n");setInterval(()=>undefined,1000)'
: scenario === "output-limit"
? 'process.stdout.write("x".repeat(1048577))'
: 'process.stderr.write("worker failed");process.exit(7)',
],
});
pid = launched.process.pid;
if (scenario === "cancelled") {
await waitForProviderProcessReady(launched.process);
setImmediate(() => controller.abort());
}
return launched;
});
expect(
await provider.inspect(
{ path, encoding: "hex" },
{ signal: controller.signal },
),
).toMatchObject({
ok: false,
error: {
_tag:
scenario === "cancelled"
? "AnalysisCancelledError"
: scenario === "output-limit"
? "AnalysisOutputError"
: "ProviderAdapterError",
},
});
if (pid === undefined) throw new Error("worker not acquired");
const acquiredPid = pid;
expect(() => process.kill(acquiredPid, 0)).toThrow();
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost)(
"distinguishes unavailable limiter, absent carrier and prelaunch cancellation",
async () => {
const { path } = await fixture();
expect(
await new EvmoleInterfaceProvider({
REA_EVM_PRLIMIT_COMMAND: path + ".absent",
}).inspect({ path, encoding: "hex" }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
expect(
await new EvmoleInterfaceProvider({}).inspect({
path: path + ".absent",
encoding: "raw",
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const controller = new AbortController();
controller.abort();
expect(
await new EvmoleInterfaceProvider({}).inspect(
{ path, encoding: "raw" },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
},
);
it.runIf(unsupportedHost)(
"reports unverified host coverage before acquiring a provider",
async () => {
expect(
await new EvmoleInterfaceProvider({}).inspect({
path: "/selected.hex",
encoding: "hex",
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
},
);
it.runIf(!unsupportedHost)(
"preserves actual snapshot-write cancellation and root cleanup",
async () => {
const { path } = await fixture();
const controller = new AbortController();
let ownedRoot = "";
const provider = new EvmoleInterfaceProvider(
{},
() => {
throw new Error("must not launch worker");
},
async () => {
const root = await PrivateRuntimeRoot.create({
prefix: "rea-evm-cancel-",
});
ownedRoot = root.path;
controller.abort();
return root;
},
);
expect(
await provider.inspect(
{ path, encoding: "hex" },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost)(
"reports private storage denial without claiming selected carrier read denial",
async () => {
const { path } = await fixture();
const provider = new EvmoleInterfaceProvider({}, undefined, () =>
Promise.reject(
Object.assign(new Error("private root denied"), { code: "EACCES" }),
),
);
expect(await provider.inspect({ path, encoding: "hex" })).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
diagnostics: { phase: "worker", reason: "private root denied" },
},
});
},
);
it.runIf(!unsupportedHost)(
"retains original format failure when owned-root cleanup fails",
async () => {
const { path, root } = await fixture();
const provider = new EvmoleInterfaceProvider(
{},
async (spawn) => {
const requestPath = spawn.arguments.at(-1);
if (requestPath === undefined) throw new Error("request missing");
const request = requestSchema.parse(
JSON.parse(await readFile(requestPath, "utf8")),
);
await writeFile(
request.reply_path,
JSON.stringify({
ok: false,
reason: "format",
message: "Odd selected hex.",
}),
);
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", "process.exit(0)"],
});
},
() =>
Promise.resolve({
path: root,
close: () => Promise.reject(new Error("root cleanup failed")),
}),
);
expect(await provider.inspect({ path, encoding: "hex" })).toMatchObject({
ok: false,
error: {
cleanupIncomplete: true,
cleanupResources: [root],
diagnostics: {
reason: "root cleanup failed",
previous_error: { category: "invalid_input" },
},
},
});
},
);
it.runIf(!unsupportedHost).each(["late-cancellation", "cleanup-failure"])(
"retains captured warnings after a successful worker: %s",
async (scenario) => {
const { path } = await fixture();
const controller = new AbortController();
let ownedRoot = "";
const provider = new EvmoleInterfaceProvider(
{},
async (spawn) => {
const requestPath = spawn.arguments.at(-1);
if (requestPath === undefined) throw new Error("request missing");
const request = requestSchema.parse(
JSON.parse(await readFile(requestPath, "utf8")),
);
const bytes = Buffer.from("60006000f3", "hex");
await writeFile(
request.reply_path,
JSON.stringify({
ok: true,
version: "0.9.3",
bytecode: {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
hex: bytes.toString("hex"),
},
raw: { functions: [] },
}),
);
return spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", 'process.stderr.write("upstream warning")'],
});
},
async () => {
const root = await PrivateRuntimeRoot.create({
prefix: "rea-evm-late-",
});
ownedRoot = root.path;
return {
path: root.path,
close: async () => {
await root.close();
if (scenario === "late-cancellation") controller.abort();
else throw new Error("reported cleanup failure");
},
};
},
);
const result = await provider.inspect(
{ path, encoding: "hex" },
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected lifecycle failure");
const output = { stdout: "", stderr: "upstream warning", truncated: false };
expect(projectAnalysisError(result.error)).toMatchObject({
category:
scenario === "late-cancellation" ? "cancelled" : "execution_failure",
details:
scenario === "late-cancellation"
? { captured_output: output }
: { diagnostics: { captured_output: output } },
});
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(!unsupportedHost).each(["directory", "missing-interpreter"])(
"identifies configured limiter constraints without blaming the carrier: %s",
async (scenario) => {
const { path, root } = await fixture();
const limiter =
scenario === "directory" ? root : join(root, "broken-limiter");
if (scenario === "missing-interpreter")
await writeFile(limiter, "#!/rea-missing-limiter-interpreter\n", {
mode: 0o700,
});
let ownedRoot: string | undefined;
const provider = new EvmoleInterfaceProvider(
{ REA_EVM_PRLIMIT_COMMAND: limiter },
undefined,
async () => {
const runtime = await PrivateRuntimeRoot.create({
prefix: "rea-evm-limiter-",
});
ownedRoot = runtime.path;
return runtime;
},
);
const result = await provider.inspect({ path, encoding: "hex" });
if (result.ok) throw new Error("Expected unavailable limiter");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
category: "unsupported_provider",
details: { provider_id: "evmole-interface" },
});
expect(result.error.message).toContain(limiter);
if (ownedRoot !== undefined)
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(path, "utf8")).toBe("0x60006000f3\n");
},
);
@@ -0,0 +1,195 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
FILE_TYPE,
LC,
dylibCommand,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const withClient = async (
verify: (client: Client) => Promise<void>,
): Promise<void> => {
const session = createTestBinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "dylib-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await verify(client);
} finally {
await client.close();
await server.close();
}
};
const structuredResult = (value: unknown): unknown =>
z.object({ result: z.unknown() }).parse(value).result;
it("traces dylib resolution for an opened app bundle and rejects a changed target", async () => {
const app = join(
await createTestTempDirectory("rea-dylib-mcp-"),
"Fixture.app",
);
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await mkdir(join(app, "Contents/Frameworks"), { recursive: true });
await writeFile(
join(app, "Contents/Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
const executable = join(app, "Contents/MacOS/App");
await writeFile(
executable,
machoImage({
commands: [
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
],
}),
);
await writeFile(
join(app, "Contents/Frameworks/libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
);
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: app },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: {},
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const trace = dylibResolutionResultSchema.parse(
structuredResult(called.structuredContent),
);
expect(trace.edges).toEqual([
expect.objectContaining({
install_name: "@rpath/libcore.dylib",
resolution: {
status: "resolved",
image: "Contents/Frameworks/libcore.dylib",
},
}),
]);
const escaping = await client.callTool({
name: "trace_dylib_resolution",
arguments: { roots: ["Contents/../../outside"] },
});
expect(escaping.isError).toBe(true);
await writeFile(executable, machoImage({}));
const changed = await client.callTool({
name: "trace_dylib_resolution",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(JSON.stringify(changed.structuredContent)).toContain("integrity");
});
});
it("rejects targets that are not Mach-O", async () => {
const directory = await createTestTempDirectory("rea-dylib-mcp-plist-");
const path = join(directory, "Info.plist");
await writeFile(path, "<plist><dict/></plist>");
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: {},
});
expect(called.isError).toBe(true);
expect(JSON.stringify(called.structuredContent)).toContain("unavailable");
});
});
it("traces a standalone Mach-O file whose name ends in .app", async () => {
const directory = await createTestTempDirectory("rea-dylib-mcp-file-");
await writeFile(
join(directory, "Tool.app"),
machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib")],
}),
);
await writeFile(
join(directory, "libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
);
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: join(directory, "Tool.app") },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: {},
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const trace = dylibResolutionResultSchema.parse(
structuredResult(called.structuredContent),
);
expect(trace.edges).toEqual([
expect.objectContaining({
resolution: { status: "resolved", image: "libcore.dylib" },
}),
]);
});
});
it.skipIf(process.getuid?.() === 0)(
"keeps a permission denied while canonicalizing the opened bundle",
async () => {
const parent = await createTestTempDirectory("rea-dylib-mcp-revoked-");
const app = join(parent, "Revoked.app");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(
join(app, "Contents/Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(join(app, "Contents/MacOS/App"), machoImage({}));
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: app },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
await chmod(parent, 0o000);
try {
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: {},
});
expect(called.isError).toBe(true);
expect(JSON.stringify(called.structuredContent)).toMatch(
/Permission denied \(EACCES\)/u,
);
} finally {
await chmod(parent, 0o755);
}
});
},
);
@@ -0,0 +1,78 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
evmInterfaceFixture,
evmInterfaceExecution,
} from "../../fixtures/evm/interface.js";
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const value = evmInterfaceFixture();
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(ok(evmInterfaceExecution(value))),
});
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(session, session, { evmInterface: service });
const client = new Client({ name: "evm-interface-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_evm_interface",
);
if (advertised?.outputSchema === undefined)
throw new Error("EVM interface inspection must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, { path: value.artifact.path, encoding: "hex" }),
).toBe(true);
expect(
ajv.validate(inputSchema, {
path: value.artifact.path,
encoding: "hex",
approval: true,
}),
).toBe(false);
const response = await client.callTool({
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_evm_interface").outputSchema.parse(
response.structuredContent,
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(value);
expect(parsed.result).toEqual(evidence.normalized_result);
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(
(
await client.callTool({
name: "inspect_evm_interface",
arguments: { path: "relative.hex", encoding: "hex" },
})
).isError,
).toBe(true);
});
+44
View File
@@ -0,0 +1,44 @@
import { createHash } from "node:crypto";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import type { EvmInterface } from "../../../src/domain/evm/evmInterface.js";
/** Source-owned transport seam, independent of real engine verification. */
export const evmInterfaceFixture = (
path = "/artifacts/source-owned.hex",
): EvmInterface => ({
artifact: { path, sha256: "a".repeat(64), bytes: 10, encoding: "hex" },
bytecode: {
sha256: createHash("sha256")
.update(Buffer.from("60006000f3", "hex"))
.digest("hex"),
bytes: 5,
hex: "60006000f3",
digest_algorithm: "sha256",
kind: "unknown",
deployment_authenticity: "unknown",
hardfork: "unknown",
},
evidence_kind: "inferred",
functions: [],
discovery_completeness: "unknown",
runtime_execution: "not-performed",
diagnostics: { stdout: "", stderr: "", truncated: false },
limitations: ["Interface completeness remains unknown."],
});
/** Bind a fixture to its explicit producing seam and carrier identity. */
export const evmInterfaceExecution = (value = evmInterfaceFixture()) =>
createAnalysisExecution(
value,
{ id: "fixture-evm", name: "Source-owned EVM seam", version: "1" },
{
rawResult: { functions: [] },
subject: {
path: value.artifact.path,
format: "file",
sha256: value.artifact.sha256,
},
limitations: value.limitations,
locations: [{ kind: "artifact-path", path: value.artifact.path }],
},
);