Files
reverse-engineering-anything/tests/boundary/mcp/pythonPycMcp.test.ts
morluto 89c1dd3c32 fix(errors): refuse malformed target bytes as a target, not invalid input (#14195)
* fix(errors): refuse malformed target bytes as a target, not invalid input

parseFailureAnalysisError is the shared owner that turns a byte-format
parser's ParseFailure into a public refusal. It mapped malformed and
truncated bytes to an AnalysisInputError on the path field. The envelope
then reported invalid_request, with inspect_input_contract recovery and
"correct the listed fields". The arguments were valid; the target bytes
were the problem. Readers that wrap the ParseFailureError in an
ArtifactReaderFailure, and ArtifactOperationError reason=malformed, were
classified the same way.

Add AnalysisMalformedTargetError. It keeps the parser's kind, format,
detail, offset and field, and projects as unsupported_target with
details.format_failure. Its recovery is to choose another operation or a
well-formed copy of the target. Route both parser entry points through it
and reclassify ArtifactOperationError reason=malformed. Argument and
selection errors (missing files, directories, symlinks, JSON arguments)
stay invalid_request.

Fixes #14170

* docs(maven): describe duplicate variant names as malformed metadata

Duplicate Gradle variant names go through malformedInput, which now
reports unsupported_target with details.format_failure: malformed.
Point the earlier statement at that section instead of the old
invalid_format code.

* test(errors): expect malformed-target refusals from CLI byte-format readers

Truncated IPS, ELF, PE and shortcut bytes now project as unsupported_target with format_failure=malformed. Update the CLI acceptance cases that still expected invalid_request.

* fix(errors): keep a cancelled read a cancellation whatever its abort reason

projectOwnedArtifactInputFailure read the reader failure's cause without
checking the reader's own reason. A cancelled read carries the caller's
opaque abort reason as that cause, so aborting with a ParseFailureError
turned the cancellation into a non-retryable malformed-target refusal
before the shared cancellation projection ran. Only a reader whose own
reason is malformed or truncated now yields a malformed target.

The ELF dependency checkpoint cancellation test now also aborts with a
parser failure as the reason, through the public provider read.

* test(pe): expect malformed-target refusals from the PE filesystem boundaries

Short non-PE bytes now refuse the target rather than the request field.
The missing-file, directory, symlink and child-path controls keep their
caller-input expectations.

* fix(elf): refuse malformed ELF note bytes as a target, not invalid input

inspect_elf_notes shared this PR's root cause: its parser reported
structural violations as a reader "format" failure, which the shared
stable-artifact projection treats as a request-field error, so truncated
or non-ELF bytes still returned invalid_request. The parser now raises
malformed or truncated ParseFailureErrors, which the shared projection
reports as a malformed target with format_failure and format facts.

Consumers that interpreted the old reader reason now use the parser's
facts: debug-link build-id observation keys on ParseFailureError kinds,
and binary hardening drops its rewrap of note-parser format failures
into BinaryFormatFailure, which the parser's own failure supersedes.

* test(errors): own the byte readers' malformed-target projection in one CLI table

The PR repeated the same malformed -> unsupported_target mapping in a
dedicated CLI test per command and again in each provider's filesystem
boundary test. The stable-artifact parser-failure CLI table now owns it:
every byte reader it covers (now including ELF dependencies, debug link,
unwind ranges and native initializers) refuses a truncated ELF header as
a malformed target with operation, path, format_failure, retained file
identity and no argument recovery.

Removed as redundant with that table: the truncated or non-ELF/non-PE
CLI tests for ELF debug link, dependencies, unwind ranges and notes,
native initializers, and PE imports and certificates; and the
malformed-file blocks in thirteen filesystem boundary tests, which keep
their directory, symlink, missing-file and child-path controls. Format
specific refusals (a truncated IPS body, a wrong shortcut CLSID, DWARF
units) keep their own tests, as do the owner tests in
parseFailureAnalysisError and ArtifactOperationFailure.

* test(errors): expect malformed target bytes as unsupported_target in acceptance tests

The first full acceptance run of this PR found five expectations still
asserting invalid_request for target-byte failures: the timing test's
truncated ELF, a truncated DTB, duplicate Rust dependency JSON, and PE32
and PE64 load-config images without an MZ header. Assert the
unsupported_target code, with format_failure malformed where the
non-MZ PE path matches the already-updated PE imports test.
2026-11-24 00:44:40 +00:00

283 lines
9.5 KiB
TypeScript

import {
canonicalOutputSchema,
withCanonicalOutputSchema,
} from "../../fixtures/canonicalOutputSchema.js";
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
import { afterAll, expect, it } from "vitest";
import { pythonPycSchema } from "../../../src/domain/python/pythonPyc.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
marshalCode,
pythonPycFixture,
pythonPycHeader,
} from "../../../src/python/PythonPyc.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
const completePycEvidenceSchema = toolContract(
"inspect_python_pyc",
).outputSchema.safeExtend({ normalized_result: pythonPycSchema });
const marshalInt64 = (value: bigint): Buffer => {
const payload = Buffer.alloc(8);
payload.writeBigInt64LE(value);
return Buffer.concat([Buffer.from([0x49]), payload]);
};
const marshalInt32 = (value: number): Buffer => {
const payload = Buffer.alloc(4);
payload.writeInt32LE(value);
return Buffer.concat([Buffer.from([0x69]), payload]);
};
const schemaValidation = createMcpSchemaValidation();
afterAll(() => schemaValidation.clear());
const connect = () =>
createApplicationMcpHarness({
session: createTestBinarySession(() => {
throw new Error("Python pyc inspection must not start a deep provider");
}),
serverOptions: {
environment: {
...process.env,
REA_MCP_MAX_INPUT_ELEMENTS: process.env.REA_MCP_MAX_INPUT_ELEMENTS,
},
},
schemaValidator: schemaValidation,
});
it("reads signed TYPE_INT64 constants and rejects a truncated payload", async () => {
const { client, close } = await connect();
try {
const root = await createTestTempDirectory("rea-python-pyc-mcp-int64-");
const path = join(root, "signed.pyc");
await writeFile(
path,
Buffer.concat([
pythonPycHeader(3531),
marshalCode("py311", {
consts: [
...[42n, -1n, -(1n << 63n), (1n << 63n) - 1n].map(marshalInt64),
marshalInt32(-42),
],
}),
]),
);
const response = await client.callTool({
name: "inspect_python_pyc",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const { normalized_result } = completePycEvidenceSchema.parse(
response.structuredContent,
);
expect(normalized_result.code_objects[0]?.consts).toEqual([
{ kind: "int", bits: 6, value: "42" },
{ kind: "int", bits: 1, value: "-1" },
{ kind: "int", bits: 64, value: "-9223372036854775808" },
{ kind: "int", bits: 63, value: "9223372036854775807" },
{ kind: "int", bits: 6, value: "-42" },
]);
const truncatedPath = join(root, "truncated.pyc");
await writeFile(
truncatedPath,
Buffer.concat([
pythonPycHeader(3531),
Buffer.from([0x49]),
Buffer.alloc(7),
]),
);
const truncated = await client.callTool({
name: "inspect_python_pyc",
arguments: { path: truncatedPath },
});
expect(truncated.isError).toBe(true);
expect(parseMcpToolError(truncated).error).toMatchObject({
code: "unsupported_target",
details: {
operation: "inspect_python_pyc",
format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u),
reason: expect.stringContaining("64-bit integer"),
},
});
} finally {
await close();
}
});
it("advertises inspect_python_pyc and reads nested code objects", async () => {
const { client, close } = await connect();
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_python_pyc",
);
expect(advertised?.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
if (advertised === undefined)
throw new Error("Missing inspect_python_pyc output schema");
const outputSchema: Record<string, unknown> = canonicalOutputSchema(
advertised.name,
);
const ajv = schemaValidation.assertions;
expect(ajv.validateSchema(outputSchema)).toBe(true);
const root = await createTestTempDirectory("rea-python-pyc-mcp-");
const path = join(root, "sample.pyc");
const nested = marshalCode("py311", {
name: "inner",
firstlineno: -7,
});
const bytes = Buffer.concat([
pythonPycHeader(3531),
marshalCode("py311", { firstlineno: -1, consts: [nested] }),
]);
await writeFile(path, bytes);
const response = await client.callTool(
{ name: "inspect_python_pyc", arguments: { path } },
{ toolDefinition: withCanonicalOutputSchema(advertised) },
);
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = completePycEvidenceSchema.parse(
response.structuredContent,
);
const sha256 = createHash("sha256").update(bytes).digest("hex");
expect(evidence).toMatchObject({
confidence: "observed",
subject: { identity: { format: "file", sha256 }, local_path: path },
normalized_result: {
artifact: { path, sha256, bytes: bytes.length },
header: { magic: 3531, python_version: "3.12", code_layout: "py311" },
},
});
expect(evidence.locations).toEqual([
{ kind: "artifact-path", path },
{ kind: "file-offset-range", start: 0, end: 16 },
{ kind: "file-offset-range", start: 16, end: bytes.length },
]);
expect(evidence.normalized_result.code_objects[0]?.firstlineno).toBe(-1);
expect(evidence.normalized_result.code_objects[1]?.name).toBe("inner");
expect(evidence.normalized_result.code_objects[1]?.firstlineno).toBe(-7);
expect(evidence.normalized_result.code_objects[0]?.consts).toContainEqual({
kind: "code",
name: "inner",
firstlineno: -7,
});
} finally {
await close();
}
});
it("requires an absolute path for inspect_python_pyc", async () => {
const { client, close } = await connect();
try {
const response = await client.callTool({
name: "inspect_python_pyc",
arguments: { path: "sample.pyc" },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_python_pyc" },
});
} finally {
await close();
}
});
it("advertised pyc output schema preserves historical signed fields", async () => {
const { client, close } = await connect();
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_python_pyc",
);
if (advertised === undefined)
throw new Error("Missing inspect_python_pyc output schema");
const root = await createTestTempDirectory("rea-python-pyc-mcp-flags-");
const path = join(root, "ambiguous-3410.pyc");
await writeFile(
path,
Buffer.concat([
pythonPycHeader(3410),
marshalCode("py38", { stacksize: 0xffffffff, flags: 0x80000000 }),
]),
);
const response = await client.callTool(
{ name: "inspect_python_pyc", arguments: { path } },
{ toolDefinition: withCanonicalOutputSchema(advertised) },
);
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const { normalized_result } = completePycEvidenceSchema.parse(
response.structuredContent,
);
expect(normalized_result.code_objects[0]).toMatchObject({
stacksize: -1,
flags: -0x80000000,
});
expect(normalized_result.limitations).toEqual(
expect.arrayContaining([expect.stringContaining("Magic 3410 is shared")]),
);
} finally {
await close();
}
});
it("rejects negative code fields for magics after constructor validation was added", async () => {
const { client, close } = await connect();
try {
const root = await createTestTempDirectory("rea-python-pyc-mcp-signed-");
const path = join(root, "negative-flags.pyc");
await writeFile(
path,
Buffer.concat([
pythonPycHeader(3411),
marshalCode("py38", { flags: 0x80000000 }),
]),
);
const response = await client.callTool({
name: "inspect_python_pyc",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "unsupported_target",
details: {
operation: "inspect_python_pyc",
format_failure: expect.stringMatching(/^(?:malformed|truncated)$/u),
reason: expect.stringContaining("co_flags is negative"),
},
});
} finally {
await close();
}
});
it("reports an unknown pyc magic as unsupported", async () => {
const { client, close } = await connect();
try {
const root = await createTestTempDirectory("rea-python-pyc-mcp-magic-");
const path = join(root, "unknown.pyc");
const bytes = pythonPycFixture("py311");
bytes.writeUInt16LE(1, 0);
await writeFile(path, bytes);
const response = await client.callTool({
name: "inspect_python_pyc",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "unsupported_target",
details: { operation: "inspect_python_pyc" },
});
} finally {
await close();
}
});