feat(wasm): inspect local artifacts with WABT (#1533)

* feat(wasm): inspect local artifacts with WABT

* fix(wasm): preserve custom names and failed cleanup ownership

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Thang Luu
2026-10-11 19:49:00 +08:00
committed by GitHub
co-authored by morluto
parent e4407dbed5
commit ffaf2c12f1
46 changed files with 2309 additions and 7 deletions
+9
View File
@@ -32,6 +32,7 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly wasmArtifactEnabled?: boolean;
readonly evmInterfaceEnabled?: boolean;
readonly processCaptureEnabled: boolean;
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
@@ -314,6 +315,14 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (name === "inspect_wasm_artifact")
return policy.wasmArtifactEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"Supply WABT 1.0.42 via absolute REA_WABT_BIN_DIRECTORY. No active binary target is required; tools are checked at execution.",
};
if (name === "inspect_pe_resources")
return { reason: "available", remediation: null };
if (name === "inspect_evm_interface")
+17
View File
@@ -0,0 +1,17 @@
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectWasmArtifactInput } from "../../domain/wasm/wasmArtifact.js";
import type { Result } from "../../domain/result.js";
/** Replaceable offline WASM inspection engine, independent of target execution and network clients. */
export interface WasmArtifactPort {
/** Retry removal of retained workspaces; failures preserve ownership for another attempt. */
close(): Promise<void>;
inspect(
input: InspectWasmArtifactInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,79 @@
import { expect, it } from "vitest";
import { WasmArtifactService } from "./WasmArtifactService.js";
import {
wasmArtifactFixture,
wasmArtifactExecution,
} from "../../../tests/fixtures/wasm/artifact.js";
import { ok } from "../../domain/result.js";
it.each([
{ path: "relative" },
{ path: "/module", glue_paths: ["relative"] },
{ path: "/module", candidate_paths: ["relative"] },
{ path: "/module", fetch: true },
])("rejects invalid selection before effects: %j", async (input) => {
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => {
throw new Error("Must not execute");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it.each(["path", "digest", "wat", "candidates", "glue"])(
"rejects mismatched upstream observation: %s",
async (problem) => {
const value = wasmArtifactFixture();
if (problem === "path") value.artifact.path = "/different";
if (problem === "wat") value.wat.sha256 = "b".repeat(64);
if (problem === "candidates") value.candidates = [];
const execution = wasmArtifactExecution(value);
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () =>
Promise.resolve(
ok({
...execution,
subject: {
path: "/artifacts/module.wasm",
format: "file",
sha256:
problem === "digest" ? "b".repeat(64) : value.artifact.sha256,
},
}),
),
});
expect(
await service.inspect({
path: "/artifacts/module.wasm",
...(problem === "glue" ? { glue_paths: ["/glue.js"] } : {}),
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
},
);
it("cancels before provider work and delivers observed Evidence on success", async () => {
const value = wasmArtifactFixture();
let calls = 0;
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => {
calls++;
return Promise.resolve(ok(wasmArtifactExecution(value)));
},
});
const controller = new AbortController();
controller.abort();
expect(
await service.inspect(
{ path: value.artifact.path },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
expect(calls).toBe(0);
expect(await service.inspect({ path: value.artifact.path })).toMatchObject({
ok: true,
value: { confidence: "observed", normalized_result: value },
});
});
+100
View File
@@ -0,0 +1,100 @@
import { createHash } from "node:crypto";
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { WasmArtifactPort } from "./WasmArtifactPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
inspectWasmArtifactInputSchema,
wasmArtifactSchema,
} from "../../domain/wasm/wasmArtifact.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
const OPERATION = "inspect_wasm_artifact";
/** Shared artifact validation and typed inline Evidence for CLI/MCP. */
export class WasmArtifactService {
constructor(readonly provider: WasmArtifactPort) {}
/** Join provider cleanup during shutdown or an explicit retry. */
close(): Promise<void> {
return this.provider.close();
}
/** Preserve exact selected artifact identity and validated upstream observations. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectWasmArtifactInputSchema.safeParse(rawInput);
if (!input.success)
return err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
cause: input.error,
}),
);
if (
![
input.data.path,
...input.data.glue_paths,
...input.data.candidate_paths,
].every(isAbsolute)
)
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const execution = inspected.value;
const report = wasmArtifactSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
createHash("sha256").update(report.data.wat.text).digest("hex") !==
report.data.wat.sha256 ||
JSON.stringify(report.data.glue.map((item) => item.artifact.path)) !==
JSON.stringify(input.data.glue_paths) ||
JSON.stringify(report.data.candidates.map((item) => item.path)) !==
JSON.stringify([
...new Set([input.data.path, ...input.data.candidate_paths]),
])
)
return err(
new AnalysisOutputError(
OPERATION,
"WABT adapter returned malformed data or changed the selected artifact identity.",
),
);
return ok(
createEvidence(execution.subject, execution.provider, {
operation: OPERATION,
parameters: input.data,
result: report.data,
...(execution.rawResult === null
? {}
: { rawResult: execution.rawResult }),
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
}