Files
reverse-engineering-anything/tests/boundary/mcp/webScriptSelectionMcp.test.ts
T
morluto 080635e7eb fix(artifacts)!: refuse an unusable extract_artifact output_root first, as caller input (#15387)
* fix(artifacts): refuse an unusable extract_artifact output_root before scanning

extract_artifact checked output_root only when it created the output tree,
after scanning the whole archive and preparing its reader. A destination
that already existed was refused there, and the refusal carried the
archive's complete inventory as its partial observation: 1.7 MB of error
text for a 2,000-entry ZIP.

The read-only SafeOutputTree.checkDestination admission, which firmware
and environment-bundle extraction already use, now runs before the archive
is read. SafeOutputTree.create still rechecks and acquires the destination
exclusively, so a destination that changes after the early check is still
refused there.

Refs #15326

* fix(artifacts)!: report a refused extract_artifact output_root as caller input

A destination refusal on extract_artifact is now an input error on
output_root, as firmware, UEFI, script and bundle export report theirs.
Every destination refusal conforms to the input contract and names the
fix instead of pointing at the schema.

BREAKING CHANGE: extract_artifact reports a refused output_root as
invalid_request with an issue at output_root (CLI: outputRoot) instead of
artifact_operation_failed with reason path. Destination refusals of
extract_firmware, UEFI extraction, export_web_scripts,
export_environment_bundle, environment-export/build and desktop build
exports no longer carry recovery.kind inspect_input_contract; read
remediation.action and details.issues instead.

Refs #15326

* test(artifacts): expect the caller-input refusal for a refused extract_artifact output_root

The provider extraction boundary tests still asserted ArtifactOperationError reason path, the shape this change replaces; they now expect AnalysisInputError with an issue at output_root.

* test(artifacts): prove extract_artifact refuses the destination before reading the source
2026-12-01 02:23:38 +00:00

298 lines
11 KiB
TypeScript

import { execFile } from "node:child_process";
import { access, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { expect, it, onTestFinished } from "vitest";
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
import { silentLogger } from "../../../src/logger.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { registerServiceTools } from "../../../src/server/serviceToolBindings.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
scriptCaptureEvidenceFixture,
scriptScenarioFixture,
} from "../../fixtures/webScriptCapture.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestMcp } from "../../support/mcp/mcpFixture.js";
import { closeVerifierResources } from "../../../scripts/lib/verifier-cleanup.mjs";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { webScriptExportResultSchema } from "../../../src/domain/webScriptExport.js";
it.skipIf(process.platform === "win32")(
"returns a capture_path invalid_request for a named pipe without waiting or publishing output",
async () => {
const root = await createTestTempDirectory("rea-script-selection-mcp-");
const capturePath = join(root, "capture.pipe");
const outputDirectory = join(root, "export");
await promisify(execFile)("mkfifo", [capturePath]);
const server = new EvidenceMcpServer(
{ name: "script-selection", version: "1" },
{},
undefined,
createToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const artifactResources = new ArtifactResourceScope();
registerServiceTools(
server,
{ webScripts: artifactResources },
{ logger: silentLogger },
);
const mcp = createTestMcp();
onTestFinished(() =>
closeVerifierResources([
() => mcp.close(),
() => artifactResources.close(),
]),
);
const client = await mcp.connect(server, {
name: "script-selection-test",
version: "1",
});
const outcome = await readWithoutFifoWriter(capturePath, () =>
client.callTool({
name: "export_web_scripts",
arguments: {
capture_path: capturePath,
output_directory: outputDirectory,
},
}),
);
expect(outcome.state).toBe("completed");
if (outcome.state !== "completed")
throw new Error("MCP capture selection waited for a FIFO writer");
expect(parseMcpToolError(outcome.result)).toMatchObject({
error: {
code: "invalid_request",
details: {
operation: "export_web_scripts",
issues: [
{
path: ["capture_path"],
reason: "invalid_value",
message: expect.stringContaining("regular file"),
},
],
},
},
});
expect(JSON.stringify(outcome.result)).toContain(capturePath);
await expect(access(outputDirectory)).rejects.toMatchObject({
code: "ENOENT",
});
},
);
it("refuses an existing output directory as invalid output_directory input", async () => {
const root = await createTestTempDirectory("rea-script-export-existing-mcp-");
const capturePath = join(root, "capture.json");
await writeFile(capturePath, JSON.stringify(scriptScenarioFixture()));
const outputDirectory = join(root, "retained");
await mkdir(outputDirectory);
await writeFile(join(outputDirectory, "marker.txt"), "keep");
const server = new EvidenceMcpServer(
{ name: "script-export-existing", version: "1" },
{},
undefined,
createToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const artifactResources = new ArtifactResourceScope();
registerServiceTools(
server,
{ webScripts: artifactResources },
{ logger: silentLogger },
);
const mcp = createTestMcp();
onTestFinished(() =>
closeVerifierResources([
() => mcp.close(),
() => artifactResources.close(),
]),
);
const client = await mcp.connect(server, {
name: "script-export-existing",
version: "1",
});
const result = await client.callTool({
name: "export_web_scripts",
arguments: { capture_path: capturePath, output_directory: outputDirectory },
});
expect(parseMcpToolError(result).error).toMatchObject({
code: "invalid_request",
category: "invalid_input",
// A schema-valid path the filesystem refused: the fix is named,
// not the input schema.
remediation: {
action: expect.stringContaining("Choose a different destination path"),
},
details: {
operation: "export_web_scripts",
issues: [
{
path: ["output_directory"],
reason: "invalid_value",
message: "Output root already exists",
},
],
},
});
expect(await readdir(outputDirectory)).toEqual(["marker.txt"]);
});
it("publishes script bytes and retains the returned Evidence without starting an analysis provider", async () => {
const root = await createTestTempDirectory("rea-script-export-retained-mcp-");
const capturePath = join(root, "capture.json");
const outputDirectory = join(root, "export");
const bytes = Buffer.from("export const callerValue = 'retained';\n");
await writeFile(
capturePath,
JSON.stringify(
scriptScenarioFixture([
{ url: "https://caller.test/app/main.js", bytes },
]),
),
);
const session = createTestBinarySession(() => {
throw new Error("local script export must not start an analysis provider");
});
const { client } = await createApplicationMcpHarness({
session,
clientIdentity: { name: "script-export-retention", version: "1" },
});
const response = await client.callTool({
name: "export_web_scripts",
arguments: { capture_path: capturePath, output_directory: outputDirectory },
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
expect(evidence.operation).toBe("export_web_scripts");
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
expect(session.exportEvidenceBundle().records).toEqual([evidence]);
const exported = webScriptExportResultSchema.parse(
evidence.normalized_result,
);
expect(exported.output_directory).toBe(outputDirectory);
expect(exported.scripts).toHaveLength(1);
const content = exported.scripts[0]?.content;
expect(content?.state).toBe("exported");
if (content?.state !== "exported")
throw new Error("script bytes were not published");
if (exported.analysis_input === null)
throw new Error("published script bytes have no analysis input root");
expect(
Buffer.compare(
await readFile(
join(exported.analysis_input.input_path, content.relative_path),
),
bytes,
),
).toBe(0);
expect(
JSON.parse(await readFile(exported.manifest.path, "utf8")),
).toMatchObject({
capture_path: capturePath,
output_directory: outputDirectory,
scripts: exported.scripts,
});
});
it("exports a capture selected by retained reference or by its retained summary", async () => {
const root = await createTestTempDirectory("rea-script-export-reference-");
const session = createTestBinarySession(() => {
throw new Error("local script export must not start an analysis provider");
});
const { client } = await createApplicationMcpHarness({
session,
clientIdentity: { name: "script-export-reference", version: "1" },
});
const capture = scriptCaptureEvidenceFixture();
expect(session.recordEvidence(capture).ok).toBe(true);
const summaryResponse = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: capture.evidence_id },
view: { kind: "summary" },
},
});
expect(summaryResponse.isError).not.toBe(true);
const summary = parseEvidence(summaryResponse.structuredContent);
expect(summary.operation).toBe("inspect_analysis_view");
for (const [name, evidenceId] of [
["reference", capture.evidence_id],
["summary", summary.evidence_id],
] as const) {
const outputDirectory = join(root, name);
const response = await client.callTool({
name: "export_web_scripts",
arguments: {
capture: { kind: "retained-evidence", evidence_id: evidenceId },
output_directory: outputDirectory,
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
// The export reads the complete capture, never the summary page.
expect(evidence.evidence_links).toEqual([capture.evidence_id]);
expect(evidence.parameters).toEqual({
capture: { kind: "retained-evidence", evidence_id: capture.evidence_id },
output_directory: outputDirectory,
});
const exported = webScriptExportResultSchema.parse(
evidence.normalized_result,
);
expect(exported).toMatchObject({
capture_path: null,
capture_sha256: null,
capture_kind: "browser-scenario",
source_evidence_id: capture.evidence_id,
output_directory: outputDirectory,
});
expect(exported.scripts.map(({ content }) => content.state)).toEqual([
"exported",
]);
}
const missingId = `ev_${"0".repeat(64)}`;
const missing = await client.callTool({
name: "export_web_scripts",
arguments: {
capture: { kind: "retained-evidence", evidence_id: missingId },
output_directory: join(root, "missing"),
},
});
expect(parseMcpToolError(missing).error).toMatchObject({
details: { evidence_id: missingId, reason: "missing" },
});
const ambiguous = await client.callTool({
name: "export_web_scripts",
arguments: {
capture_path: join(root, "capture.json"),
capture: { kind: "retained-evidence", evidence_id: capture.evidence_id },
output_directory: join(root, "ambiguous"),
},
});
expect(parseMcpToolError(ambiguous).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
path: ["capture"],
message: "Supply exactly one of capture_path or capture",
}),
],
},
});
for (const directory of ["missing", "ambiguous"])
await expect(access(join(root, directory))).rejects.toMatchObject({
code: "ENOENT",
});
});