mirror of
https://github.com/morluto/rea.git
synced 2026-11-28 07:08:45 +00:00
* feat(errors)!: add the TargetFailure model, its projection table and conformance registry Introduce one domain-owned TargetFailure value whose kind alone derives the public code, category, retryability, recovery and details, for CLI and MCP alike. Selected-file malformed and truncated refusals are the first area on it: AnalysisMalformedTargetError is replaced by AnalysisTargetFailureError, and ParseFailure's byte-structure variants are TargetFailure variants rather than a parallel type. The shared stableArtifactParserFailureCli loop is replaced by a declarative registry (tests/support/targetFailure/readers/*.ts) and one generated suite that runs every registered case through the CLI and MCP. BREAKING CHANGE: selected-file malformed and truncated refusals add details.failure_kind, and a truncated target's remediation now says to re-acquire the complete file instead of choosing another target. Codes are unchanged. Affected operations: every operation that refuses a selected file's malformed or truncated bytes, including the ELF, PE, Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel module, binary hardening, managed PE/CLI and IL2CPP readers. * test(managed): name the target failure error in the merged status test * docs(reference): name the error CSV instead of linking a non-page file * fix(tests): expect the path reason for non-regular dyld inputs #14225 refuses a non-regular dyld input as ArtifactReaderFailure("path"); dylibFileLifetime still expected "format" and fails on main's shard 9. * fix(tests): expect io, invariant and path where #14225 reclassified stableArtifact expected "format" for an impossible descriptor byte count (now io) and an invalid chunk size (now InternalInvariantError); directoryArtifactReaderOpen expected "format" for a non-file entry (now path, the same change as #14238). All three fail on main. * fix(errors)!: raise container reader byte faults as malformed or truncated targets Delete the ambiguous `format` reason from ArtifactReaderFailure and ArtifactOperationError. Each container reader now raises its owner's fact once, through malformedArtifact / truncatedArtifact, with format, offset, field and measured extents. Short reads inside a measured extent are read-coverage integrity failures, path-kind refusals are `path`, foreign or recovery-requiring inputs are `unsupported`, host tool output is `io`, and REA defects are InternalInvariantError. The trace, NTFS journal, release exposure, web capture, native macOS and web artifact adapters project the reader's parsed facts as AnalysisTargetFailureError instead of invalid_request. Inventory malformed, truncated, unsupported and cancelled reasons take their code from the TargetFailure projection table, so a truncated container is unsupported_target with failure_kind "truncated" on both paths. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact, analyze_javascript_application, inspect_desktop_application, inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg, trace_dylib_resolution, trace_web_module_imports and trace_web_source_location report damaged container bytes as unsupported_target (details.reason "malformed" or "truncated", with failure_kind and format) instead of artifact_operation_failed with reason "format", and a truncated container as unsupported_target instead of truncated. inspect_playwright_trace, inspect_ntfs_journal, audit_release_exposure, the web capture inspection operations and the caller-selected import and source maps report damaged selected bytes as unsupported_target instead of invalid_request. The `format` reason no longer appears in details.reason. * test(artifacts): expect target failure codes in compiled CLI and MCP suites * fix(errors)!: refuse malformed SQLite, pwntools and EVM inputs as target failures The SQLite engine's `format` reason is renamed to `malformed` at its owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an AnalysisTargetFailureError at the selected path with format "sqlite". The pwntools and EVM worker replies keep their wire reason "format", which their workers define, and the adapters translate it once into a malformed target failure with the profile's format (elf, elf-core, evm-bytecode) instead of an invalid_format argument issue. SQLite joins the target-failure conformance registry. BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout, inspect_recorded_crash and inspect_evm_interface report a selected file's malformed bytes as unsupported_target with details.failure_kind "malformed", format_failure, format and path, instead of invalid_request with an invalid_format issue on path. * fix(errors): give the integrity kind a schema-valid code and list the reference page artifact_integrity_mismatch's projection schema requires declared and calculated digests, which a TargetFailure of kind integrity does not carry, so the kind now projects artifact_operation_failed with category integrity_mismatch. The model test validates every kind's projection against analysisErrorProjectionSchema. The reference page joins the documentation sidebar. * fix(artifacts): report a short carrier read as a changed file and keep unsupported desktop probes local A Bun or Node SEA short read inside a range already checked against the measured size meant the file changed, not that it was truncated. The carrier range reader and Bun's readExact now raise read-coverage integrity for it, and keep 'outside the file' as the truncated case. DesktopFileInspection records an unsupported managed-metadata probe as a row issue again, so later file checks still run. * test(errors): expect target failure facts in the pwntools and EVM reply suites The literal-replacement scenario now reads the failure's detail instead of an issues[] message, and a malformed reply wrapped by cleanup failure reports category unsupported_target. * test(errors): register PE DOS-signature and truncated IPS refusals and drop their per-command copies The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit signatures) and the truncated Apple IPS body move into the conformance registry, which runs them through the CLI and MCP and now also checks that a refusal leaves the selected file unchanged. The per-command tests keep only their valid-image controls. * test(sqlite): drop the malformed-database provider test the conformance registry covers inspect_sqlite_database/not-a-database in the target-failure registry runs the same non-SQLite bytes through the CLI and MCP, asserts the malformed target facts and checks the selected file is unchanged. * feat(errors)!: make failure_kind the identifier and derive code and retry from it Apply the owner review on #14239 to the TargetFailure model: - remove details.format_failure; failure_kind is the only identifier; - give integrity, conflict and io their own codes (target_integrity_mismatch, input_conflict, host_io_failed) and derive inventory malformed, truncated and unsupported codes from the same table; - add a retry hint (none, backoff, after_change) derived from the kind, with io refined by its transient errno fact; retryable stays the unchanged-retry flag and is true exactly for backoff; - rename the limit-cut result code and category truncated to partial; - drop cancelled and resource from the target kinds and spell identifiers in American English (unrecognized); - return a target failure a tool handler throws as a projected isError result instead of letting the SDK flatten it to text. BREAKING CHANGE: details.format_failure is removed (read details.failure_kind). The truncated result code and category are now partial. Target integrity failures report target_integrity_mismatch, host read failures host_io_failed and disagreeing inputs input_conflict. Inventory operations (inventory_artifact, inspect_artifact, extract_artifact and the other inventory callers) report truncated container bytes as unsupported_target. Every target failure carries a top-level retry hint. * test(sqlite): expect a malformed target for non-database bytes in the CLI suite * fix(artifacts): keep changed-file short reads, invalid offsets and EOF declarations apart PyInstaller reads inside the measured size, and .NET bundle manifest refills, now raise read-coverage integrity on a zero-byte read instead of truncated. A .NET bundle field and a Godot PCK directory entry that extend past the file are truncated (with offset and extents) instead of malformed. An absent or invalid ASAR packed offset is malformed; only a valid range past the archive is truncated. The .NET manifest string offset is reported in file coordinates. * fix(pwntools): report a short ELF header as a truncated target The layout and recorded-crash workers raise a distinct truncated reason when the file ends inside the ELF identification or header, and the decoder projects it as failure_kind truncated instead of inferring it from the message. * fix(errors)!: report managed coverage gaps and IL2CPP pair conflicts as target failures Managed readers interpret an issue code once, in managedIssueTargetFailure: a coverage gap is an unsupported target, every other rule violation is a malformed target, and the inventory metadata status is derived from that same fact. managedInspectionTargetFailure now returns only AnalysisTargetFailureError. An IL2CPP binary that parses but does not link to its metadata is a conflict target failure that lists both inputs and blames neither, in place of an invalid_request with two issue entries. Metadata version 108 is an unsupported target. The CLI spells each conflict input's field by the command's option name. BREAKING CHANGE: inspect_managed_artifact, inspect_managed_members, inspect_managed_native_boundaries and the managed comparison operations report unsupported metadata or signature forms as an AnalysisTargetFailureError (failure_kind unsupported, format pe-cli, field, offset) instead of a bare unsupported target. inspect_il2cpp_metadata reports a binary/metadata pair that does not link as code input_conflict with failure_kind conflict and details.inputs, instead of invalid_request with details.issues, and metadata version 108 with failure_kind unsupported. * fix(artifacts): verify the carrier before blaming a short read on the bytes The NTFS $MFT decoder, positional members (FIT, uImage, Bun, Deno) and .NET bundle members now re-verify the source before reporting a short stream as malformed, so a file that changed during the read reports the change. The truncation site builds the model's measured extent. * fix(errors)!: report inventory refusals as target failures of the selected path An inventory, inspection or extraction refused damaged or unsupported container bytes as an ArtifactOperationError whose reason repeated the format owner's kind. It carried no path or retry hint, so the conformance registry could not express container cases. translateArtifactFailure now takes the selected path and returns the reader's TargetFailure as an AnalysisTargetFailureError. The malformed, truncated and unsupported reasons, their classification rows and their presentation branch are deleted from ArtifactOperationError. Readers' unsupported refusals carry their format facts through unsupportedArtifact. Container cases move into the conformance registry, which now opens the target first for session tools such as inspect_artifact. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the bundle readers report a refused container as a target failure of details.path with a top-level retry. details.reason is the owner's description and details.detail is removed. * docs(il2cpp): describe pair conflicts as input_conflict with both inputs * docs(android): name unsupported_target for truncated boot image structures * fix(errors)!: report a target that changed during the read as failure_kind changed Inventory integrity failures whose check means the target moved under the read (container, member and unpacked-entry identity, read coverage, traversal coverage) now take the model's changed projection: code artifact_changed, retry backoff and details.failure_kind changed. A selected target that no longer matches the one the session admitted gets its own admitted-identity check and keeps its reopen recovery. BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact and the other inventory operations report a target that changed during the read as artifact_changed (retryable, failure_kind changed) instead of artifact_operation_failed. Admission-identity refusals report integrity_check admitted-identity instead of container-identity. * test(artifacts): raise the cleanup fixture's decode refusal with its format facts * fix(errors)!: report unsupported and unrecognized targets on the TargetFailure model AnalysisUnsupportedTargetError carried a free-text reason and remediation beside the TargetFailure model, so unsupported refusals had no format, failure_kind or retry hint, and their recovery was prose written at each producer. The class is deleted. Producers raise unsupportedTarget or unrecognizedTarget with the owner's format, and consumers read targetFailureOfKind. The projection table renders the recovery and names the operations the owner lists in related.operations. The foreign-bytes identity loop moves into the conformance registry. BREAKING CHANGE: unsupported and unrecognized targets report failure_kind, format and retry. Their remediation comes from the target-failure table; producer-written remediation sentences are folded into details.reason or replaced by details.related_operations. * test(artifacts): expect admitted-identity for selections replaced before admission A selected source replaced before admission fails the admitted-identity check rather than container-identity since the changed/admitted split. * test(go): name the fixture and result when an MZ carrier is not refused through MCP * style: format the migrated target-failure tests * test(errors): expect the PE readers' native-binary format label for foreign bytes * test(verify): expect target failures for damaged ELF, core and EVM inputs in real-provider verifiers The binary-layout, recorded-crash and EVM verifiers still expected invalid_input for malformed or truncated selected bytes. The pwntools and EVM adapters now report those as unsupported_target with failure_kind; a missing path remains invalid_input. * test(web): expect the partial code for a refused source-map admission The limit-cut code is partial; this Windows-lane test arrived from main with the old truncated spelling. * fix(artifacts): keep refusal facts on DMG verdicts and the selected bundle path hdiutil's "image not recognized" verdict raised the unsupported reason without the owner's facts, so the inventory translation treated it as a reader defect. It now carries an unsupported dmg target failure, and the reader-failure constructor requires facts for every target reason. A bundle resource refusal names the caller's selected bundle path rather than its resolved target. The real-provider verifiers and the Android, source-location acceptance tests expect the model's target-failure categories and codes. * test(errors): assert unsupported refusals' kind and format, and align verifiers and the Electron guide * test(errors): check the MCP target failure as the text clients receive The stdio transport removes the private structured carrier from every isError result, so the conformance suite asserted a field that never reaches clients and failed every case. The projected diagnostic is checked from the JSON text instead. * test(errors): raise main's new unsupported-target fixtures through the model * test(artifacts): expect artifact_changed when selected bytes change after inventory Bundle resources replaced after open and unselected JavaScript sources rewritten after inventory now fail a change check, so they report artifact_changed with retry backoff rather than artifact_operation_failed. * fix(errors): report a session digest mismatch as admitted-identity The digest the session admitted does not change when the same request is repeated, so targetDigestChangedFailure was inviting a backoff retry that fails the same way. It now names admitted-identity, which stays artifact_operation_failed and not retryable, and tells the caller to reopen. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): classify unused PyInstaller compressed input as layout zlib stops at the first complete stream, so a declared span that arrives intact but is not fully consumed is trailing junk or a second stream, not a file that changed. A source that ends before that span stays read-coverage. The cached-carrier test replaces the file with a different size so a shared timestamp cannot hide the rewrite. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(applications): expect unsupported_target for a damaged trace stream A trace member whose CRC fails is a malformed zip target. The partial Evidence assertion now checks that code, failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(artifacts): assert Android refusal kinds and drop the SEA registry case details.reason is the owner's description, so the boot-image refusals assert failure_kind and format. A malformed SEA blob inside an ELF stays an outer-format inventory with a recognition limitation, which the Node SEA reader tests already cover, so it is not an inspect_artifact refusal. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): pass the selected path into translated target failures translateArtifactFailure names the caller-selected path on a format refusal. Directory inspection and a retained artifact scope both know that path and now supply it. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(artifacts): charge global pax records against the tar metadata budget Repeated pax global headers were copied into one map without a charge, so each header could stay inside the extended-header allowance while the map grew without a bound. The retained metadata budget is charged for the merged map's keys, values and entries before that map is allocated. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(dylib): expect admitted-identity when the opened target is replaced The session keeps the digest it admitted, so replacing the executable and repeating trace_dylib_resolution is not a retryable container change. Co-authored-by: morluto <morluto@users.noreply.github.com> * style: format the inventory path translation and conformance suite * fix(artifacts): keep the unsupported-target migration in files the inventory merge replaced * test(errors): expect target failures for ZIP inventory refusals and input_conflict for an unlinked IL2CPP pair * test(artifacts): expect a malformed target failure for an ISO 9660 directory cycle * test(web): expect a malformed target failure on the captured source path * test(artifacts): expect a malformed ZIP target failure for a corrupt Zstandard member * test(javascript): read the owner's input facts from details.reason and recovery from the projection * test(iso9660): assert the malformed target failure fields details.reason is the owner's description. The compiled CLI refusal is identified by failure_kind and format. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(errors): assert selection and unsupported view fields A desktop root that is not a directory is a selection failure, so the CLI reports invalid_request. An analysis view the parent cannot supply is unsupported evidence; the tests read failure_kind, format, field and related_operations. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(errors): keep binary plist UID facts on unsupported targets Pass the reader's UnsupportedBinaryPlistUidError failure through instead of rebuilding a bplist refusal that drops field and undecodedContent. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(errors): keep oversized binary plist UID facts on keyed archives Assert the reader projects format, field, and undecoded content from the parser failure instead of a rebuilt bplist refusal. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
617 lines
20 KiB
JavaScript
617 lines
20 KiB
JavaScript
#!/usr/bin/env node
|
|
import assert from "node:assert/strict";
|
|
import { createHash } from "node:crypto";
|
|
import { access, readFile, readdir, writeFile } from "node:fs/promises";
|
|
import { constants } from "node:fs";
|
|
import { isAbsolute, join } from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { parseEvidence } from "../dist/domain/evidence.js";
|
|
import { isOwnershipPsExecution } from "./lib/ownership-ps-trace.mjs";
|
|
import {
|
|
requireMcpOutput,
|
|
requireMcpToolError,
|
|
} from "./lib/mcp-verifier-results.mjs";
|
|
import { createVerifierCommands } from "./lib/verify-commands.mjs";
|
|
import {
|
|
assertVerifierCleanupComplete,
|
|
createVerifierRun,
|
|
completeVerifierRun,
|
|
} from "./lib/verifier-run.mjs";
|
|
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
|
|
|
|
const manifest = JSON.parse(
|
|
await readFile(new URL("../package.json", import.meta.url), "utf8"),
|
|
);
|
|
const expectedEngine = `evmole@${manifest.dependencies.evmole}`;
|
|
const solcModule = process.env.REA_VERIFY_SOLC_MODULE;
|
|
const strace = process.env.REA_VERIFY_STRACE_COMMAND;
|
|
if (
|
|
process.platform !== "linux" ||
|
|
process.arch !== "x64" ||
|
|
!isAbsolute(solcModule ?? "") ||
|
|
!isAbsolute(strace ?? "")
|
|
)
|
|
throw new Error(
|
|
"verify:evm:interface requires Linux x64, caller-supplied util-linux prlimit and absolute REA_VERIFY_SOLC_MODULE pointing to unchanged solc 0.8.30 and absolute REA_VERIFY_STRACE_COMMAND. No target or chain is executed.",
|
|
);
|
|
try {
|
|
await access(
|
|
process.env.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
|
constants.X_OK,
|
|
);
|
|
await access(solcModule, constants.R_OK);
|
|
await access(strace, constants.X_OK);
|
|
} catch (cause) {
|
|
throw new Error(
|
|
"verify:evm:interface prerequisite unavailable: selected solc module, strace or util-linux prlimit",
|
|
{ cause },
|
|
);
|
|
}
|
|
const solc = (await import(pathToFileURL(solcModule).href)).default;
|
|
assert.equal(solc.version(), "0.8.30+commit.73712a01.Emscripten.clang");
|
|
const source = await readFile(
|
|
new URL("./fixtures/evm-interface.sol", import.meta.url),
|
|
"utf8",
|
|
);
|
|
const entrypoint =
|
|
process.argv[2] ?? fileURLToPath(new URL("./rea.mjs", import.meta.url));
|
|
const run = createVerifierRun();
|
|
const commands = await createVerifierCommands();
|
|
const environment = Object.fromEntries(
|
|
Object.entries(process.env).filter(([, value]) => typeof value === "string"),
|
|
);
|
|
const root = await VerifierFixture.open({ prefix: "rea-evm-verifier-" });
|
|
const client = new Client({ name: "evm-interface-verifier", version: "1" });
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [entrypoint, "mcp"],
|
|
env: environment,
|
|
stderr: "pipe",
|
|
});
|
|
const failures = [];
|
|
/** @type {Awaited<ReturnType<typeof completeVerifierRun>> | undefined} */
|
|
let verifier;
|
|
let cases = 0;
|
|
try {
|
|
await client.connect(transport);
|
|
const tools = await client.listTools();
|
|
assert.ok(tools.tools.some(({ name }) => name === "inspect_evm_interface"));
|
|
const inspect = async (
|
|
mode,
|
|
path,
|
|
encoding,
|
|
expectedCategory,
|
|
scope = { command: process.execPath, prefix: [], client },
|
|
) => {
|
|
let value;
|
|
if (mode === "cli") {
|
|
let stdout;
|
|
try {
|
|
({ stdout } = await commands.exec(
|
|
scope.command,
|
|
[
|
|
...scope.prefix,
|
|
entrypoint,
|
|
"inspect-evm-interface",
|
|
path,
|
|
encoding,
|
|
"--json",
|
|
],
|
|
{
|
|
env: scope.environment ?? environment,
|
|
timeout: 45_000,
|
|
maxBuffer: 32 * 1024 * 1024,
|
|
},
|
|
));
|
|
} catch (cause) {
|
|
if (cause?.name !== "VerifierCommandExitError") throw cause;
|
|
stdout = cause.snapshot.stdout.text;
|
|
}
|
|
value = JSON.parse(stdout);
|
|
} else {
|
|
const reply = await scope.client.callTool({
|
|
name: "inspect_evm_interface",
|
|
arguments: { path, encoding },
|
|
});
|
|
value =
|
|
expectedCategory !== undefined
|
|
? requireMcpToolError(reply)
|
|
: requireMcpOutput(reply, "inspect_evm_interface");
|
|
}
|
|
if (expectedCategory !== undefined) {
|
|
assert.equal(value.category, expectedCategory, JSON.stringify(value));
|
|
return value;
|
|
}
|
|
assert.equal(
|
|
value.category,
|
|
undefined,
|
|
`Unexpected public failure: ${JSON.stringify(value)}`,
|
|
);
|
|
const evidence = parseEvidence(value);
|
|
const report = evidence.normalized_result;
|
|
assert.equal(report.diagnostics.truncated, false);
|
|
assert.equal(evidence.provider.version, expectedEngine);
|
|
assert.equal(evidence.confidence, "inferred");
|
|
assert.equal(report.artifact.path, path);
|
|
assert.equal(report.artifact.encoding, encoding);
|
|
const carrier = await readFile(path);
|
|
assert.equal(
|
|
report.artifact.sha256,
|
|
createHash("sha256").update(carrier).digest("hex"),
|
|
);
|
|
assert.equal(evidence.subject.identity.sha256, report.artifact.sha256);
|
|
assert.equal(report.artifact.bytes, carrier.length);
|
|
assert.equal(
|
|
report.bytecode.sha256,
|
|
createHash("sha256")
|
|
.update(Buffer.from(report.bytecode.hex, "hex"))
|
|
.digest("hex"),
|
|
);
|
|
assert.equal(report.bytecode.bytes, report.bytecode.hex.length / 2);
|
|
for (const key of ["kind", "hardfork", "deployment_authenticity"])
|
|
assert.equal(report.bytecode[key], "unknown");
|
|
assert.equal(report.discovery_completeness, "unknown");
|
|
assert.equal(report.runtime_execution, "not-performed");
|
|
assert.deepEqual(
|
|
report.functions.map((fn) => ({
|
|
selector: fn.selector.slice(2),
|
|
bytecodeOffset: fn.bytecode_offset,
|
|
dispatch: fn.dispatch,
|
|
...(fn.inferred_arguments === null
|
|
? {}
|
|
: { arguments: fn.inferred_arguments }),
|
|
...(fn.inferred_state_mutability === null
|
|
? {}
|
|
: { stateMutability: fn.inferred_state_mutability }),
|
|
})),
|
|
evidence.raw_result.functions ?? [],
|
|
);
|
|
if (mode === "mcp") assert.deepEqual(value.normalized_result, report);
|
|
return report;
|
|
};
|
|
// Ownership inventory runs ps from fixed system locations, so a caller PATH
|
|
// without ps neither hides nor replaces it and inspection still completes.
|
|
const ownershipProbe = join(root.path, "ownership-prerequisite.hex");
|
|
await writeFile(ownershipProbe, "0x00");
|
|
const pathWithoutPs = await inspect("cli", ownershipProbe, "hex", undefined, {
|
|
command: process.execPath,
|
|
prefix: [],
|
|
client,
|
|
environment: { ...environment, PATH: root.path },
|
|
});
|
|
assert.equal(pathWithoutPs.bytecode.hex, "00");
|
|
cases++;
|
|
for (const [name, optimizer, viaIR] of [
|
|
["plain", false, false],
|
|
["optimized", true, false],
|
|
["via-ir", true, true],
|
|
]) {
|
|
const output = JSON.parse(
|
|
solc.compile(
|
|
JSON.stringify({
|
|
language: "Solidity",
|
|
sources: { "Interface.sol": { content: source } },
|
|
settings: {
|
|
optimizer: { enabled: optimizer, runs: 200 },
|
|
viaIR,
|
|
evmVersion: "cancun",
|
|
outputSelection: {
|
|
"*": {
|
|
"*": [
|
|
"evm.deployedBytecode.object",
|
|
"evm.methodIdentifiers",
|
|
"abi",
|
|
],
|
|
},
|
|
},
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
assert.ok(
|
|
!output.errors?.some(({ severity }) => severity === "error"),
|
|
JSON.stringify(output.errors),
|
|
);
|
|
const artifact = output.contracts["Interface.sol"].InterfaceFixture;
|
|
const hex = artifact.evm.deployedBytecode.object;
|
|
const expected = Object.values(artifact.evm.methodIdentifiers)
|
|
.map((selector) => "0x" + selector)
|
|
.sort();
|
|
const forms = [
|
|
["hex", ` \t0x${hex.toUpperCase()}\r\n`],
|
|
["raw", Buffer.from(hex, "hex")],
|
|
];
|
|
for (const [encoding, data] of forms) {
|
|
const path = join(root.path, `${name}.${encoding}`);
|
|
await writeFile(path, data);
|
|
const original = await readFile(path);
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const report = await inspect(mode, path, encoding);
|
|
assert.equal(report.bytecode.hex, hex);
|
|
assert.equal(report.bytecode.metadata.status, "decoded");
|
|
assert.deepEqual(report.bytecode.metadata.compiler_version, {
|
|
representation: "release-bytes",
|
|
value: "0.8.30",
|
|
});
|
|
assert.equal(
|
|
report.bytecode.metadata.bytecode_offset +
|
|
report.bytecode.metadata.cbor_bytes +
|
|
2,
|
|
Buffer.from(hex, "hex").length,
|
|
);
|
|
assert.ok(
|
|
report.bytecode.metadata.entries.some(
|
|
({ key, value }) =>
|
|
key.kind === "text" &&
|
|
key.value === "solc" &&
|
|
value.kind === "bytes" &&
|
|
value.value === "00081e",
|
|
),
|
|
);
|
|
assert.deepEqual(
|
|
report.functions
|
|
.filter(({ dispatch }) => dispatch === "abi")
|
|
.map(({ selector }) => selector)
|
|
.sort(),
|
|
expected,
|
|
);
|
|
assert.ok(
|
|
report.functions.every(
|
|
({ bytecode_offset }) => bytecode_offset < report.bytecode.bytes,
|
|
),
|
|
);
|
|
const set = report.functions.find(
|
|
({ selector }) =>
|
|
selector === "0x" + artifact.evm.methodIdentifiers["set(uint256)"],
|
|
);
|
|
assert.equal(set.inferred_arguments, "uint256");
|
|
assert.equal(set.inferred_state_mutability, "nonpayable");
|
|
cases++;
|
|
}
|
|
assert.deepEqual(await readFile(path), original);
|
|
}
|
|
}
|
|
for (const [name, data, encoding] of [
|
|
["empty", "0x", "hex"],
|
|
["empty-raw", Buffer.alloc(0), "raw"],
|
|
["incomplete-push", Buffer.from([0x7f]), "raw"],
|
|
["no-dispatch", "60006000f3", "hex"],
|
|
]) {
|
|
const path = join(root.path, name);
|
|
await writeFile(path, data);
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const report = await inspect(mode, path, encoding);
|
|
assert.equal(report.functions.length, 0);
|
|
cases++;
|
|
}
|
|
}
|
|
for (const [name, hex, expected] of [
|
|
["zero-selector", "60003560e01c630000000014601057005b00", ["0x00000000"]],
|
|
["push-immediate", "63123456785060006000f3", []],
|
|
]) {
|
|
const path = join(root.path, name);
|
|
await writeFile(path, hex);
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const report = await inspect(mode, path, "hex");
|
|
assert.deepEqual(
|
|
report.functions.map(({ selector }) => selector),
|
|
expected,
|
|
);
|
|
cases++;
|
|
}
|
|
}
|
|
for (const [encoding, data] of [
|
|
["raw", Buffer.from("ef0001", "hex")],
|
|
["hex", "0xef0001"],
|
|
]) {
|
|
const path = join(root.path, "eof." + encoding);
|
|
await writeFile(path, data);
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const failure = await inspect(mode, path, encoding, "unsupported_target");
|
|
assert.equal(failure.code, "unsupported_target");
|
|
assert.equal(failure.details.path, path);
|
|
assert.match(failure.details.reason, /EF00/);
|
|
assert.equal(failure.details.failure_kind, "unsupported");
|
|
assert.equal(failure.details.format, "evm-bytecode");
|
|
cases++;
|
|
}
|
|
}
|
|
for (const [name, data] of [
|
|
["odd", "0x1"],
|
|
["invalid-hex", "xyz"],
|
|
["interior-space", "60 00"],
|
|
["bom", "\uFEFF6000"],
|
|
["utf8", Buffer.from([0xff])],
|
|
]) {
|
|
const path = join(root.path, name);
|
|
await writeFile(path, data);
|
|
for (const mode of ["cli", "mcp"]) {
|
|
// An undecodable hex carrier is the target's bytes, not the request.
|
|
const failure = await inspect(mode, path, "hex", "unsupported_target");
|
|
assert.equal(failure.details.failure_kind, "malformed");
|
|
assert.equal(failure.details.format, "evm-bytecode");
|
|
cases++;
|
|
}
|
|
}
|
|
for (const mode of ["cli", "mcp"]) {
|
|
await inspect(mode, join(root.path, "absent"), "raw", "invalid_input");
|
|
cases++;
|
|
}
|
|
for (const [option, expected] of [
|
|
["--as=2147483648", "address_space_bytes=2147483648"],
|
|
["--cpu=20", "cpu_seconds=20"],
|
|
["--fsize=8388608", "file_size_bytes=8388608"],
|
|
]) {
|
|
const limiter = environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
|
const prefix = [
|
|
option,
|
|
"--",
|
|
process.execPath,
|
|
"--disable-wasm-trap-handler",
|
|
];
|
|
const limitedClient = new Client({
|
|
name: "limited-evm-verifier",
|
|
version: "1",
|
|
});
|
|
const limitedTransport = new StdioClientTransport({
|
|
command: limiter,
|
|
args: [...prefix, entrypoint, "mcp"],
|
|
env: environment,
|
|
stderr: "pipe",
|
|
});
|
|
try {
|
|
await limitedClient.connect(limitedTransport);
|
|
const scope = { command: limiter, prefix, client: limitedClient };
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const report = await inspect(
|
|
mode,
|
|
join(root.path, "zero-selector"),
|
|
"hex",
|
|
undefined,
|
|
scope,
|
|
);
|
|
assert.ok(report.limitations.some((item) => item.includes(expected)));
|
|
cases++;
|
|
}
|
|
} finally {
|
|
// A close that fails keeps the root until release confirms it.
|
|
await root.closeEarly([
|
|
() => limitedClient.close(),
|
|
() => limitedTransport.close(),
|
|
]);
|
|
}
|
|
}
|
|
const brokenLimiter = join(root.path, "broken-limiter");
|
|
await writeFile(brokenLimiter, "#!/rea-verifier-missing-interpreter\n", {
|
|
mode: 0o700,
|
|
});
|
|
const signalLimiter = join(root.path, "signal-limiter");
|
|
await writeFile(signalLimiter, '#!/bin/sh\nulimit -c 0\nkill -XCPU "$$"\n', {
|
|
mode: 0o700,
|
|
});
|
|
const fileLimiter = join(root.path, "file-size-limiter");
|
|
const unmarkedLimiter = join(root.path, "unmarked-file-size-limiter");
|
|
await writeFile(
|
|
unmarkedLimiter,
|
|
'#!/bin/sh\nprintf "launcher exit 76\\n" >&2\nexit 76\n',
|
|
{ mode: 0o700 },
|
|
);
|
|
// Fixture-only launcher: run the actual Node/WASM worker with a one-byte
|
|
// file allowance, keeping the usual address-space, CPU and core budgets.
|
|
await writeFile(
|
|
fileLimiter,
|
|
'#!/bin/sh\nwhile [ "$#" -gt 0 ] && [ "$1" != "--" ]; do shift; done\n[ "$#" -gt 0 ] || exit 64\nshift\nexec /usr/bin/prlimit --as=3221225472: --cpu=30: --fsize=1: --core=0: -- "$@"\n',
|
|
{ mode: 0o700 },
|
|
);
|
|
for (const [limiter, category, resource] of [
|
|
[root.path, "unsupported_provider"],
|
|
[brokenLimiter, "unsupported_provider"],
|
|
[signalLimiter, "resource_constraint", "cpu"],
|
|
[fileLimiter, "resource_constraint", "file-size"],
|
|
[unmarkedLimiter, "execution_failure"],
|
|
]) {
|
|
const selectedEnvironment = {
|
|
...environment,
|
|
REA_EVM_PRLIMIT_COMMAND: limiter,
|
|
};
|
|
const selectedClient = new Client({
|
|
name: "unavailable-evm-limiter-verifier",
|
|
version: "1",
|
|
});
|
|
const selectedTransport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [entrypoint, "mcp"],
|
|
env: selectedEnvironment,
|
|
stderr: "pipe",
|
|
});
|
|
try {
|
|
await selectedClient.connect(selectedTransport);
|
|
const scope = {
|
|
command: process.execPath,
|
|
prefix: [],
|
|
client: selectedClient,
|
|
environment: selectedEnvironment,
|
|
};
|
|
for (const mode of ["cli", "mcp"]) {
|
|
const error = await inspect(
|
|
mode,
|
|
join(root.path, "zero-selector"),
|
|
"hex",
|
|
category,
|
|
scope,
|
|
);
|
|
if (category === "resource_constraint") {
|
|
assert.equal(error.code, "resource_constraint");
|
|
assert.equal(error.details.resource, resource);
|
|
assert.equal(
|
|
error.details.reported_limits.effective_soft_limits,
|
|
null,
|
|
);
|
|
assert.equal(
|
|
typeof error.details.reported_limits.configured_soft_limits
|
|
.cpu_seconds,
|
|
"number",
|
|
);
|
|
assert.ok(
|
|
JSON.stringify(error).includes(
|
|
resource === "cpu" ? "SIGXCPU" : "EFBIG",
|
|
),
|
|
);
|
|
} else if (category === "execution_failure") {
|
|
assert.equal(error.code, "execution_failure");
|
|
assert.ok(JSON.stringify(error).includes("launcher exit 76"));
|
|
assert.ok(JSON.stringify(error).includes("file_size_failure_marker"));
|
|
} else {
|
|
assert.equal(error.code, "capability_unavailable");
|
|
assert.ok(JSON.stringify(error).includes(limiter));
|
|
}
|
|
cases++;
|
|
}
|
|
} finally {
|
|
// A close that fails keeps the root until release confirms it.
|
|
await root.closeEarly([
|
|
() => selectedClient.close(),
|
|
() => selectedTransport.close(),
|
|
]);
|
|
}
|
|
}
|
|
for (const [name, encoding] of [
|
|
["plain.hex", "hex"],
|
|
["via-ir.raw", "raw"],
|
|
]) {
|
|
await commands.exec(
|
|
strace,
|
|
[
|
|
"-ff",
|
|
"-e",
|
|
"trace=network,execve,execveat",
|
|
"-s",
|
|
"4096",
|
|
"-o",
|
|
join(root.path, `offline.trace.${name}`),
|
|
process.execPath,
|
|
entrypoint,
|
|
"inspect-evm-interface",
|
|
join(root.path, name),
|
|
encoding,
|
|
"--json",
|
|
],
|
|
{
|
|
env: { ...environment, PATH: "/usr/bin:/bin" },
|
|
timeout: 45_000,
|
|
maxBuffer: 32 * 1024 * 1024,
|
|
},
|
|
);
|
|
}
|
|
const observedExecutables = new Set();
|
|
for (const file of await readdir(root.path)) {
|
|
if (!file.startsWith("offline.trace.")) continue;
|
|
const localSocketDescriptors = new Set();
|
|
for (const line of (await readFile(join(root.path, file), "utf8")).split(
|
|
"\n",
|
|
)) {
|
|
if (/execve(?:at)?\(/.test(line)) {
|
|
const match = /^execve\("([^"]+)"/.exec(line);
|
|
assert.notEqual(match, null, `Unresolved executable identity: ${line}`);
|
|
assert.ok(
|
|
line.endsWith(" = 0") || / = -1 [A-Z]+/.test(line),
|
|
`Incomplete exec observation: ${line}`,
|
|
);
|
|
const ownershipInspection = isOwnershipPsExecution(line);
|
|
assert.ok(
|
|
[
|
|
process.execPath,
|
|
environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
|
].includes(match[1]) || ownershipInspection,
|
|
`Unexpected host execution: ${line}`,
|
|
);
|
|
observedExecutables.add(match[1]);
|
|
} else if (/^[a-z]+\(/.test(line)) {
|
|
assert.ok(
|
|
permitsStdioSocketObservation(line, localSocketDescriptors),
|
|
`Unexpected attempted network operation: ${line}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
assert.ok(observedExecutables.has(process.execPath));
|
|
assert.ok(
|
|
observedExecutables.has(
|
|
environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
|
),
|
|
);
|
|
cases += 2;
|
|
} catch (cause) {
|
|
failures.push(cause);
|
|
} finally {
|
|
root.releaseAfter(() => commands.close());
|
|
root.releaseAfter(() => client.close());
|
|
root.releaseAfter(() => transport.close());
|
|
root.releaseAfter(async () => {
|
|
verifier = await completeVerifierRun(run);
|
|
assertVerifierCleanupComplete(verifier.process_lineage);
|
|
});
|
|
try {
|
|
await root.release();
|
|
} catch (cause) {
|
|
failures.push(cause);
|
|
}
|
|
}
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
status: failures.length === 0 ? "passed" : "failed",
|
|
public_cases: cases,
|
|
compiler: solc.version(),
|
|
engine: expectedEngine,
|
|
...(failures.length === 0
|
|
? {
|
|
target_execution: "exec-syscalls-verified-absent",
|
|
network_requests: "socket-syscalls-verified-absent",
|
|
}
|
|
: {}),
|
|
verifier,
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
);
|
|
if (failures.length !== 0)
|
|
throw Object.assign(
|
|
new AggregateError(
|
|
failures,
|
|
"Offline EVM interface verification failed; cleanup failures retained.",
|
|
),
|
|
// The caller can retry the retained root from the final failure.
|
|
root.released ? {} : { cleanupLeases: [root] },
|
|
);
|
|
|
|
function permitsStdioSocketObservation(line, localDescriptors) {
|
|
if (line.startsWith("socketpair(AF_UNIX,")) {
|
|
const pair = /\[(\d+), (\d+)\]\)\s+= 0$/.exec(line);
|
|
if (pair !== null) {
|
|
localDescriptors.add(pair[1]);
|
|
localDescriptors.add(pair[2]);
|
|
}
|
|
return true;
|
|
}
|
|
const name = /^getsockname\((\d+), \{sa_family=AF_UNIX\}/.exec(line);
|
|
if (name !== null) {
|
|
localDescriptors.add(name[1]);
|
|
return true;
|
|
}
|
|
// A failed descriptor query performs no request and identifies no socket.
|
|
if (line.startsWith("getsockname(") && / = -1 ENOTSOCK/.test(line))
|
|
return true;
|
|
const metadata =
|
|
/^(?:getsockopt\((\d+), SOL_SOCKET, SO_TYPE,|setsockopt\((\d+), SOL_SOCKET, SO_(?:RCVBUF|SNDBUF),|shutdown\((\d+), SHUT_WR\))/.exec(
|
|
line,
|
|
);
|
|
const descriptor = metadata?.[1] ?? metadata?.[2] ?? metadata?.[3];
|
|
// Allow descriptor queries/buffer configuration only after observing a local
|
|
// stdio socket. Other socket creation, connection and data operations fail.
|
|
return descriptor !== undefined && localDescriptors.has(descriptor);
|
|
}
|