Files
reverse-engineering-anything/tests/boundary/mcp/lifecycleModel.test.ts
T
morluto 02aa23afbc test(mcp): model target lifecycle sequences and scan Evidence for planted credentials (#15382)
* test(mcp): model target lifecycle sequences and scan Evidence for planted credentials

lifecycleModel.test.ts runs fast-check command sequences in-process against a
ManagedStaticProvider session: open_binary(A|B), close_binary,
reset_investigation, explicit and path-less managed calls, and
binary_session. A path-less managed call must analyze the model's open
target or be refused naming open_binary; an explicit path is never
remembered, and nothing open survives close_binary. On the revision
before #15345 it shrinks to a single path-less call with nothing open.

evidenceSecretScan.test.ts plants random canaries as a literal
Authorization value, a cookie seed and an ordinary header, and scans the
tool result, the retained record and the exported bundle for the raw,
base64 and SHA-256 forms. The ordinary header must stay visible. The two
literal credentials still recorded verbatim are known leaks for #15340
(open: #15347); a new or a fixed leak fails the test.

The fake capture builder moves from browserScenarioMcp.test.ts to the
shared browser scenario fixture so both suites use one copy.

* test(mcp): compare the open path directly and require the record in every scanned output

* test(mcp): drop the fixed literal-credential leaks and cover retained credentials
2026-12-01 02:35:27 +00:00

217 lines
7.3 KiB
TypeScript

import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import type { Client } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { fc } from "@fast-check/vitest";
import { expect, it } from "vitest";
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProvider.js";
import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
// Model-based lifecycle sequences over one in-process session. The model holds
// the open target; the invariants are that a path-less managed call analyzes
// exactly that target or is refused naming open_binary, an explicit path is
// never remembered, and nothing open survives close_binary. reset_investigation
// clears records but keeps the engine, so the open target survives it.
type FileKey = "A" | "B";
interface Model {
open: FileKey | undefined;
}
interface Real {
readonly client: Client;
readonly files: Readonly<Record<FileKey, string>>;
}
const MANAGED_TOOLS = [
"inspect_managed_artifact",
"inspect_managed_members",
"inspect_managed_native_boundaries",
] as const;
type ManagedTool = (typeof MANAGED_TOOLS)[number];
/** Two managed PE files with different members, removed after the test. */
const managedFiles = async (): Promise<Readonly<Record<FileKey, string>>> => {
const directory = await createTestTempDirectory("rea-lifecycle-model-");
const files = { A: join(directory, "a.dll"), B: join(directory, "b.dll") };
await writeFile(files.A, buildManagedPeFixture());
await writeFile(files.B, buildManagedPeFixture({ methodName: "Other" }));
return files;
};
const call = async (
{ client }: Real,
name: string,
args: Record<string, unknown> = {},
): Promise<CallToolResult> =>
(await client.callTool({ name, arguments: args })) as CallToolResult;
const succeed = async (
real: Real,
name: string,
args: Record<string, unknown> = {},
): Promise<CallToolResult> => {
const result = await call(real, name, args);
if (result.isError === true)
throw new Error(`${name} failed: ${JSON.stringify(result.content)}`);
return result;
};
const subjectPath = (result: CallToolResult): string | null =>
parseEvidence(result.structuredContent).subject.local_path;
class OpenBinary implements fc.AsyncCommand<Model, Real> {
constructor(readonly file: FileKey) {}
check = () => true;
async run(model: Model, real: Real) {
await succeed(real, "open_binary", { path: real.files[this.file] });
model.open = this.file;
}
toString = () => `open_binary(${this.file})`;
}
class CloseBinary implements fc.AsyncCommand<Model, Real> {
check = () => true;
async run(model: Model, real: Real) {
await succeed(real, "close_binary");
model.open = undefined;
}
toString = () => "close_binary";
}
class ResetInvestigation implements fc.AsyncCommand<Model, Real> {
check = () => true;
async run(_model: Model, real: Real) {
// Records are discarded; the engine and its open target are kept.
await succeed(real, "reset_investigation");
}
toString = () => "reset_investigation";
}
class ExplicitManaged implements fc.AsyncCommand<Model, Real> {
constructor(
readonly tool: ManagedTool,
readonly file: FileKey,
) {}
check = () => true;
async run(_model: Model, real: Real) {
const path = real.files[this.file];
const result = await succeed(real, this.tool, { path });
expect(subjectPath(result), `${this.tool} analyzes its path`).toBe(path);
}
toString = () => `${this.tool}(${this.file})`;
}
class PathlessManaged implements fc.AsyncCommand<Model, Real> {
constructor(readonly tool: ManagedTool) {}
check = () => true;
async run(model: Model, real: Real) {
const result = await call(real, this.tool);
if (model.open === undefined) {
expect(result.isError, `${this.tool} {} with nothing open`).toBe(true);
const { error } = parseMcpToolError(result);
expect(error.remediation.action).toContain("open_binary");
return;
}
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
expect(
subjectPath(result),
`${this.tool} {} analyzes the open target`,
).toBe(real.files[model.open]);
}
toString = () => `${this.tool}{}`;
}
class SessionStatus implements fc.AsyncCommand<Model, Real> {
check = () => true;
async run(model: Model, real: Real) {
const status = (await succeed(real, "binary_session"))
.structuredContent as {
readonly result: { readonly open: boolean; readonly path?: unknown };
};
expect(status.result.open, "binary_session open").toBe(
model.open !== undefined,
);
if (model.open !== undefined)
expect(status.result.path).toBe(real.files[model.open]);
}
toString = () => "binary_session";
}
const file = fc.constantFrom<FileKey>("A", "B");
const tool = fc.constantFrom(...MANAGED_TOOLS);
const commands = [
file.map((key) => new OpenBinary(key)),
fc.constant(new CloseBinary()),
fc.constant(new ResetInvestigation()),
fc.tuple(tool, file).map(([name, key]) => new ExplicitManaged(name, key)),
tool.map((name) => new PathlessManaged(name)),
fc.constant(new SessionStatus()),
];
const startSession = async (
files: Readonly<Record<FileKey, string>>,
): Promise<{
readonly real: Real;
readonly close: () => Promise<void>;
}> => {
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
new ManagedStaticProvider(),
]);
const { client, close } = await createApplicationMcpHarness({
session,
clientIdentity: { name: "lifecycle-model", version: "1" },
});
return { real: { client, files }, close };
};
it("keeps path-less calls on the open target across open, close and reset", async () => {
const files = await managedFiles();
await fc.assert(
fc.asyncProperty(
fc.commands(commands, { maxCommands: 12 }),
async (sequence) => {
const { real, close } = await startSession(files);
try {
await fc.asyncModelRun(
() => ({ model: { open: undefined }, real }),
sequence,
);
} finally {
await close();
}
},
),
{ seed: 15_314, numRuns: 60, interruptAfterTimeLimit: 30_000 },
);
});
it("analyzes the newly opened target, not an earlier explicit path", async () => {
// The #15314 report as a fixed sequence: an explicit path, then open B.
const { real, close } = await startSession(await managedFiles());
try {
await fc.asyncModelRun(
() => ({ model: { open: undefined }, real }),
[
new ExplicitManaged("inspect_managed_artifact", "A"),
new PathlessManaged("inspect_managed_members"),
new OpenBinary("B"),
new PathlessManaged("inspect_managed_members"),
new CloseBinary(),
new PathlessManaged("inspect_managed_artifact"),
],
);
} finally {
await close();
}
});