mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
test(evidence): consolidate public bundle delivery and import checks (#13543)
This commit is contained in:
1 parent
963535fb15
commit
933cd8382c
2 files changed
+220
-374
No files matched your search
@@ -11,6 +11,7 @@ import {
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { expect } from "vitest";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
@@ -91,41 +92,81 @@ cliTest(
|
||||
fieldErrors: [{ path: field, code: "too_small", missing: false }],
|
||||
});
|
||||
expect(result.json).not.toHaveProperty("details.path");
|
||||
expect(await readdir(root)).toEqual(["bundle.json"]);
|
||||
expect(await readFile(join(root, "bundle.json"), "utf8")).toBe(encoded);
|
||||
}
|
||||
expect(await readdir(root)).toEqual(["bundle.json"]);
|
||||
expect(await readFile(join(root, "bundle.json"), "utf8")).toBe(encoded);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves whitespace in selected Evidence filenames",
|
||||
"exports canonical Evidence to the exact selected filename with accurate receipts and overwrite",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-spaced-path-");
|
||||
const source = " bundle name.json";
|
||||
const output = " exported bundle.json";
|
||||
const bundle = revisionBundle();
|
||||
const encoded = JSON.stringify(bundle);
|
||||
const outputPath = join(root, output);
|
||||
const history = revisionBundle();
|
||||
const extra = createEvidence(
|
||||
unknownTarget("not-observed"),
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "observe", parameters: {}, result: { observed: true } },
|
||||
);
|
||||
const bundle = createEvidenceBundle(
|
||||
[...history.records, extra],
|
||||
history.unknowns,
|
||||
);
|
||||
const encoded = JSON.stringify(bundle, null, 2);
|
||||
await writeFile(join(root, source), encoded);
|
||||
const imported = await cli.run({
|
||||
arguments: ["evidence-import", source, "--json"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(imported.exitCode, imported.stderr).toBe(0);
|
||||
expect(imported.json).toEqual({ imported: 2, unknowns_added: 2, total: 2 });
|
||||
const exported = await cli.run({
|
||||
arguments: ["evidence-export", source, output, "--json"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(imported.json).toEqual({ imported: 3, unknowns_added: 2, total: 3 });
|
||||
|
||||
const args = ["evidence-export", source, output, "--json"];
|
||||
const exported = await cli.run({ arguments: args, cwd: root });
|
||||
expect(exported.exitCode, exported.stderr).toBe(0);
|
||||
expect(JSON.parse(await readFile(join(root, output), "utf8"))).toEqual(
|
||||
bundle,
|
||||
);
|
||||
const bytes = await readFile(outputPath);
|
||||
const receipt = {
|
||||
path: outputPath,
|
||||
bytes: bytes.length,
|
||||
records: 3,
|
||||
unknowns: 2,
|
||||
};
|
||||
expect(exported.json).toMatchObject(receipt);
|
||||
expect(JSON.parse(bytes.toString("utf8"))).toEqual(bundle);
|
||||
|
||||
const digest = createHash("sha256").update(bytes).digest("hex");
|
||||
const compared = await cli.run({
|
||||
arguments: ["compare", source, output, "--json"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(compared.exitCode, compared.stderr).toBe(0);
|
||||
expect(compared.json).toMatchObject({ status: "unchanged" });
|
||||
expect(compared.json).toMatchObject({
|
||||
status: "unchanged",
|
||||
left_bundle_sha256: digest,
|
||||
right_bundle_sha256: digest,
|
||||
});
|
||||
|
||||
const previous = "previous output\n";
|
||||
await writeFile(outputPath, previous);
|
||||
const collision = await cli.run({ arguments: args, cwd: root });
|
||||
expect(collision.exitCode).toBe(1);
|
||||
expect(collision.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "write", reason: "exists", path: outputPath },
|
||||
message: expect.stringContaining("allow overwrite"),
|
||||
});
|
||||
expect(await readFile(outputPath, "utf8")).toBe(previous);
|
||||
|
||||
const replaced = await cli.run({
|
||||
arguments: [...args, "--full-output", "--overwrite"],
|
||||
cwd: root,
|
||||
});
|
||||
expect(replaced.exitCode, replaced.stderr).toBe(0);
|
||||
expect(replaced.json).toMatchObject({ data: receipt });
|
||||
expect((await readFile(outputPath)).equals(bytes)).toBe(true);
|
||||
expect(await readFile(join(root, source), "utf8")).toBe(encoded);
|
||||
expect((await readdir(root)).sort()).toEqual([source, output].sort());
|
||||
},
|
||||
@@ -193,28 +234,18 @@ cliTest(
|
||||
}
|
||||
|
||||
const file = join(root, "fresh.json");
|
||||
const arguments_ = ["evidence-export", source, file, "--json"];
|
||||
const fresh = await cli.run({ arguments: arguments_ });
|
||||
const fresh = await cli.run({
|
||||
arguments: ["evidence-export", source, file, "--json"],
|
||||
});
|
||||
expect(fresh.exitCode, fresh.stderr).toBe(0);
|
||||
const exported = await readFile(file, "utf8");
|
||||
expect(JSON.parse(exported)).toEqual(emptyBundle);
|
||||
|
||||
const existingBytes = "previous output\n";
|
||||
await writeFile(file, existingBytes);
|
||||
const collision = await cli.run({ arguments: arguments_ });
|
||||
expect(collision.exitCode).toBe(1);
|
||||
expect(collision.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "write", reason: "exists", path: file },
|
||||
message: expect.stringContaining("allow overwrite"),
|
||||
const bytes = await readFile(file);
|
||||
expect(fresh.json).toMatchObject({
|
||||
path: file,
|
||||
bytes: bytes.length,
|
||||
records: 0,
|
||||
unknowns: 0,
|
||||
});
|
||||
expect(await readFile(file, "utf8")).toBe(existingBytes);
|
||||
|
||||
const replacement = await cli.run({
|
||||
arguments: [...arguments_, "--overwrite"],
|
||||
});
|
||||
expect(replacement.exitCode, replacement.stderr).toBe(0);
|
||||
expect(JSON.parse(await readFile(file, "utf8"))).toEqual(emptyBundle);
|
||||
expect(JSON.parse(bytes.toString("utf8"))).toEqual(emptyBundle);
|
||||
expect(await readFile(source, "utf8")).toBe(sourceBytes);
|
||||
expect((await readdir(root)).sort()).toEqual([
|
||||
"bundle.json",
|
||||
@@ -224,32 +255,16 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for([
|
||||
"evidence-import",
|
||||
"evidence-export",
|
||||
"compare-left",
|
||||
"compare-right",
|
||||
])(
|
||||
"explains a bundle BOM with the format owner's recovery through $0",
|
||||
async (operation, { cli }) => {
|
||||
cliTest(
|
||||
"refuses BOM-prefixed bundle export with the JSON format recovery",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-bundle-bom-cli-");
|
||||
const path = join(root, "bundle.json");
|
||||
const canonical = join(root, "canonical.json");
|
||||
const output = join(root, "exported.json");
|
||||
const encoded = JSON.stringify(revisionBundle());
|
||||
const bom = `\uFEFF${encoded}`;
|
||||
const bom = `\uFEFF${JSON.stringify(revisionBundle())}`;
|
||||
await writeFile(path, bom);
|
||||
await writeFile(canonical, encoded);
|
||||
const arguments_ =
|
||||
operation === "evidence-import"
|
||||
? [operation, path]
|
||||
: operation === "evidence-export"
|
||||
? [operation, path, output]
|
||||
: operation === "compare-left"
|
||||
? ["compare", path, canonical]
|
||||
: ["compare", canonical, path];
|
||||
const result = await cli.run({
|
||||
arguments: [...arguments_, "--json"],
|
||||
arguments: ["evidence-export", path, output, "--json"],
|
||||
environment: { REA_LOG_LEVEL: "silent" },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
@@ -258,18 +273,8 @@ cliTest.for([
|
||||
details: {
|
||||
path,
|
||||
reason: "invalid-json",
|
||||
content_issues: [
|
||||
{
|
||||
reason: "invalid_format",
|
||||
message: expect.stringMatching(
|
||||
/byte-order mark.*UTF-8 without a byte-order mark/iu,
|
||||
),
|
||||
},
|
||||
],
|
||||
content_issues: [{ reason: "invalid_format" }],
|
||||
},
|
||||
message: expect.stringMatching(
|
||||
/byte-order mark.*UTF-8 without a byte-order mark/iu,
|
||||
),
|
||||
remediation: {
|
||||
action: expect.stringMatching(
|
||||
/byte-order mark.*UTF-8 without a byte-order mark/iu,
|
||||
@@ -314,95 +319,58 @@ cliTest.for([
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"reports record and residual-unknown revision counts in export receipts",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-export-counts-");
|
||||
const history = revisionBundle();
|
||||
const extra = createEvidence(
|
||||
unknownTarget("not-observed"),
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "observe", parameters: {}, result: { observed: true } },
|
||||
);
|
||||
const fullHistory = createEvidenceBundle(
|
||||
[...history.records, extra],
|
||||
history.unknowns,
|
||||
);
|
||||
for (const [label, bundle, full, records, unknowns] of [
|
||||
["empty", createEvidenceBundle([]), false, 0, 0],
|
||||
["revisions", fullHistory, true, 3, 2],
|
||||
] as const) {
|
||||
const source = join(root, `${label}.json`);
|
||||
const output = join(root, `${label}-exported.json`);
|
||||
await writeFile(source, JSON.stringify(bundle));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"evidence-export",
|
||||
source,
|
||||
output,
|
||||
"--json",
|
||||
...(full ? ["--full-output"] : []),
|
||||
],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const receipt = full
|
||||
? (result.json as { data: unknown }).data
|
||||
: result.json;
|
||||
const bytes = await readFile(output);
|
||||
expect(receipt).toMatchObject({
|
||||
path: output,
|
||||
bytes: bytes.length,
|
||||
records,
|
||||
unknowns,
|
||||
});
|
||||
expect(JSON.parse(bytes.toString("utf8"))).toEqual(bundle);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports a standalone Evidence record as the wrong input file kind",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-record-input-");
|
||||
const path = join(root, "record.json");
|
||||
const record = revisionBundle().records[0];
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
await writeFile(path, JSON.stringify(record));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: { path, detected_kind: "evidence-record" },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects altered Evidence and incomplete unknown history before reporting counts",
|
||||
"distinguishes wrong-kind input, altered Evidence and incomplete Unknown history",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-import-invalid-");
|
||||
const path = join(root, "bundle.json");
|
||||
const bundle = revisionBundle();
|
||||
for (const invalid of [
|
||||
{
|
||||
...bundle,
|
||||
records: bundle.records.map((record) => ({
|
||||
...record,
|
||||
normalized_result: "altered",
|
||||
})),
|
||||
},
|
||||
{ ...bundle, unknowns: bundle.unknowns.slice(1) },
|
||||
]) {
|
||||
await writeFile(path, JSON.stringify(invalid));
|
||||
const [record, ...otherRecords] = bundle.records;
|
||||
const firstUnknown = bundle.unknowns[0];
|
||||
if (record === undefined || firstUnknown === undefined)
|
||||
throw new Error("Fixture needs one Evidence record and Unknown history");
|
||||
for (const [input, failure] of [
|
||||
[
|
||||
record,
|
||||
{
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
path,
|
||||
operation: "read",
|
||||
reason: "wrong-kind",
|
||||
detected_kind: "evidence-record",
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
...bundle,
|
||||
records: [
|
||||
{ ...record, normalized_result: "altered" },
|
||||
...otherRecords,
|
||||
],
|
||||
},
|
||||
{
|
||||
code: "evidence_integrity_mismatch",
|
||||
message: expect.stringContaining("records.0.evidence_id"),
|
||||
},
|
||||
],
|
||||
[
|
||||
{ ...bundle, unknowns: bundle.unknowns.slice(1) },
|
||||
{
|
||||
code: "evidence_integrity_mismatch",
|
||||
message: expect.stringContaining(
|
||||
`${firstUnknown.unknown_id} revision history has a gap`,
|
||||
),
|
||||
},
|
||||
],
|
||||
] as const) {
|
||||
await writeFile(path, JSON.stringify(input));
|
||||
const result = await cli.run({
|
||||
arguments: ["evidence-import", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "evidence_integrity_mismatch",
|
||||
});
|
||||
expect(result.json).toMatchObject(failure);
|
||||
expect(result.json).not.toHaveProperty("imported");
|
||||
}
|
||||
},
|
||||
@@ -439,9 +407,9 @@ cliTest(
|
||||
records: Array<{ normalized_result: unknown }>;
|
||||
}
|
||||
).records;
|
||||
expect(Object.keys(records)).toEqual(["0"]);
|
||||
const normalizedResult = records[0]?.normalized_result;
|
||||
expect(typeof normalizedResult).toBe("object");
|
||||
expect(normalizedResult).not.toBeNull();
|
||||
expect(Object.keys(normalizedResult as object)).toEqual(["__proto__"]);
|
||||
expect(Object.hasOwn(normalizedResult as object, "__proto__")).toBe(true);
|
||||
expect((normalizedResult as Record<string, unknown>)["__proto__"]).toEqual({
|
||||
answer: 7,
|
||||
@@ -449,47 +417,6 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"preserves cell text when formatting retained Evidence as Markdown",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-evidence-markdown-cells-");
|
||||
const path = join(root, "bundle.json");
|
||||
const result = {
|
||||
text: "left|right\\tail\nnext",
|
||||
type: "List<string>",
|
||||
literal: "© <br>",
|
||||
};
|
||||
const record = createEvidence(
|
||||
unknownTarget("not-observed"),
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "ordinary-json",
|
||||
parameters: {},
|
||||
result,
|
||||
},
|
||||
);
|
||||
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
|
||||
const base = [
|
||||
"inspect-evidence-bundle",
|
||||
JSON.stringify({ path, detail: "complete" }),
|
||||
"--filter-output",
|
||||
"records.0.normalized_result",
|
||||
];
|
||||
const json = await cli.run({ arguments: [...base, "--json"] });
|
||||
expect(json.exitCode, json.stderr).toBe(0);
|
||||
expect(json.stdout).toContain(JSON.stringify(result.text));
|
||||
expect(json.stdout).toContain(JSON.stringify(result.type));
|
||||
expect(json.stdout).toContain(JSON.stringify(result.literal));
|
||||
const markdown = await cli.run({
|
||||
arguments: [...base, "--format", "md"],
|
||||
});
|
||||
expect(markdown.exitCode, markdown.stderr).toBe(0);
|
||||
expect(markdown.stdout).toContain("left\\|right\\\\tail<br>next");
|
||||
expect(markdown.stdout).toContain("List<string>");
|
||||
expect(markdown.stdout).toContain("&copy; <br>");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"refuses an earlier-format record inside a current bundle",
|
||||
async ({ cli }) => {
|
||||
|
||||
@@ -2,16 +2,19 @@ import { unknownTarget } from "../../../src/domain/targetIdentity.js";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
parseEvidenceBundle,
|
||||
safeParseEvidenceBundle,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { ANALYSIS_SNAPSHOT_TARGET } from "../../../src/domain/analysisSnapshot.fixture.js";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
@@ -19,74 +22,10 @@ import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidencePro
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
||||
|
||||
it("exports and imports GameCube DOL Evidence without losing its subject identity", async () => {
|
||||
const root = await createTestTempDirectory("rea-dol-bundle-mcp-");
|
||||
const path = join(root, "bundle.json");
|
||||
const record = createEvidence(
|
||||
{
|
||||
path: join(root, "game.dol"),
|
||||
sha256: "d".repeat(64),
|
||||
format: "gamecube-dol",
|
||||
architecture: "powerpc",
|
||||
},
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_artifact",
|
||||
parameters: {},
|
||||
result: { observed: true },
|
||||
},
|
||||
);
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("bundle round trip must not run a provider");
|
||||
});
|
||||
expect(session.recordEvidence(record).ok).toBe(true);
|
||||
const source = await connectEvidenceMcp("dol-source", session);
|
||||
const importedSession = createTestBinarySession(() => {
|
||||
throw new Error("bundle import must not run a provider");
|
||||
});
|
||||
const target = await connectEvidenceMcp("dol-target", importedSession);
|
||||
try {
|
||||
const inline = await source.client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(inline.isError).not.toBe(true);
|
||||
expect(inline.structuredContent).toMatchObject({
|
||||
result: {
|
||||
artifacts: [{ format: "gamecube-dol", architecture: "powerpc" }],
|
||||
},
|
||||
});
|
||||
const exported = await source.client.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(exported.isError).not.toBe(true);
|
||||
const imported = await target.client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(imported.isError).not.toBe(true);
|
||||
const restored = await target.client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(restored.structuredContent).toEqual(inline.structuredContent);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
source.client.close(),
|
||||
source.server.close(),
|
||||
session.close(),
|
||||
target.client.close(),
|
||||
target.server.close(),
|
||||
importedSession.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves BOM recovery through public bundle import", async () => {
|
||||
const root = await createTestTempDirectory("rea-bundle-bom-mcp-");
|
||||
const path = join(root, "bundle.json");
|
||||
await writeFile(path, "\uFEFF{}");
|
||||
await writeFile(path, `\uFEFF${JSON.stringify(createEvidenceBundle([]))}`);
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("bundle import must not start a provider");
|
||||
});
|
||||
@@ -99,9 +38,11 @@ it("preserves BOM recovery through public bundle import", async () => {
|
||||
expect(parseMcpToolError(response)).toMatchObject({
|
||||
error: {
|
||||
code: "evidence_integrity_mismatch",
|
||||
message: expect.stringMatching(
|
||||
/byte-order mark.*UTF-8 without a byte-order mark/iu,
|
||||
),
|
||||
details: {
|
||||
path,
|
||||
reason: "invalid-json",
|
||||
content_issues: [{ reason: "invalid_format" }],
|
||||
},
|
||||
remediation: {
|
||||
action: expect.stringMatching(
|
||||
/byte-order mark.*UTF-8 without a byte-order mark/iu,
|
||||
@@ -114,131 +55,115 @@ it("preserves BOM recovery through public bundle import", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the complete session Evidence bundle in the tool result", async () => {
|
||||
const evidence = createEvidence(
|
||||
unknownTarget("not-observed"),
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "observe", parameters: {}, result: { value: "seen" } },
|
||||
);
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client(
|
||||
{ name: "inline-evidence-bundle", version: "1" },
|
||||
{ jsonSchemaValidator: createMcpSchemaValidation() },
|
||||
);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: {
|
||||
records: [
|
||||
{
|
||||
evidence_id: evidence.evidence_id,
|
||||
normalized_result: { value: "seen" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects bundle field stripping at MCP import without changing retained evidence", async () => {
|
||||
it("retains complete Evidence across rejected and successful MCP bundle imports", async () => {
|
||||
const root = await createTestTempDirectory("rea-evidence-bundle-mcp-");
|
||||
const sourceSession = createBundleSourceSession();
|
||||
const targetSession = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
const {
|
||||
session: sourceSession,
|
||||
evidence,
|
||||
subject,
|
||||
} = createBundleSourceSession(root);
|
||||
const targetSession = createTestBinarySession(() => {
|
||||
throw new Error("bundle import must not start a provider");
|
||||
});
|
||||
expect(targetSession.recordEvidence(evidence).ok).toBe(true);
|
||||
const source = await connectEvidenceMcp("bundle-source", sourceSession);
|
||||
const target = await connectEvidenceMcp("bundle-target", targetSession);
|
||||
const { client: sourceClient } = source;
|
||||
const { client: targetClient } = target;
|
||||
const bundlePath = join(root, "exported.json");
|
||||
const targetExportPath = join(root, "round-trip.json");
|
||||
|
||||
try {
|
||||
const { sourceJson, records, evidenceIndex } = await exportFixtureBundle(
|
||||
sourceClient,
|
||||
bundlePath,
|
||||
const contents = await exportFixtureBundle(source.client, bundlePath);
|
||||
const bundle = parseEvidenceBundle(JSON.parse(contents));
|
||||
const evidenceIndex = bundle.records.findIndex(
|
||||
({ evidence_id }) => evidence_id === evidence.evidence_id,
|
||||
);
|
||||
const initial = structured(
|
||||
await targetClient.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
}),
|
||||
).result;
|
||||
expect(bundle.records[evidenceIndex]).toEqual(evidence);
|
||||
expect(bundle.artifacts).toContainEqual({
|
||||
digest: { sha256: subject.sha256 },
|
||||
format: "gamecube-dol",
|
||||
architecture: "powerpc",
|
||||
});
|
||||
expect(bundle.unknowns).toHaveLength(1);
|
||||
expect(await getBundle(source.client)).toEqual(bundle);
|
||||
const initial = createEvidenceBundle([evidence]);
|
||||
expect(await getBundle(target.client)).toEqual(initial);
|
||||
|
||||
for (const [label, path] of unsupportedBundleFields(evidenceIndex)) {
|
||||
const candidate = structuredClone(sourceJson);
|
||||
const candidate = structuredClone(bundle);
|
||||
setPath(candidate, path, "unsupported-metadata");
|
||||
const malformedPath = join(root, `${label.replaceAll(" ", "-")}.json`);
|
||||
await writeFile(malformedPath, JSON.stringify(candidate));
|
||||
const rejected = await targetClient.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: malformedPath },
|
||||
expect(safeParseEvidenceBundle(candidate), label).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "invalid-bundle",
|
||||
cause: {
|
||||
issues: expect.arrayContaining([
|
||||
{
|
||||
code: "unrecognized_keys",
|
||||
path: path.slice(0, -1),
|
||||
keys: [path.at(-1)],
|
||||
message: expect.any(String),
|
||||
},
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(parseMcpToolError(rejected), label).toMatchObject({
|
||||
error: { code: "evidence_integrity_mismatch" },
|
||||
});
|
||||
expect(
|
||||
structured(
|
||||
await targetClient.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
}),
|
||||
).result,
|
||||
label,
|
||||
).toEqual(initial);
|
||||
}
|
||||
|
||||
const imported = await targetClient.callTool({
|
||||
const malformed = structuredClone(bundle);
|
||||
setPath(
|
||||
malformed,
|
||||
["records", evidenceIndex, "subject", "identity", "future_field"],
|
||||
"unsupported-metadata",
|
||||
);
|
||||
const malformedPath = join(root, "malformed.json");
|
||||
await writeFile(malformedPath, JSON.stringify(malformed));
|
||||
const rejected = await target.client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: malformedPath },
|
||||
});
|
||||
expect(parseMcpToolError(rejected)).toMatchObject({
|
||||
error: { code: "evidence_integrity_mismatch" },
|
||||
});
|
||||
expect(await getBundle(target.client)).toEqual(initial);
|
||||
|
||||
const imported = await target.client.callTool({
|
||||
name: "import_evidence_bundle",
|
||||
arguments: { path: bundlePath },
|
||||
});
|
||||
if (imported.isError === true)
|
||||
throw new Error(JSON.stringify(parseMcpToolError(imported)));
|
||||
await targetClient.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: targetExportPath },
|
||||
expect(structured(imported).result).toEqual({
|
||||
imported: bundle.records.length - 1,
|
||||
unknowns_added: 1,
|
||||
total: bundle.records.length,
|
||||
});
|
||||
expect(JSON.parse(await readFile(targetExportPath, "utf8"))).toEqual(
|
||||
sourceJson,
|
||||
expect(await getBundle(target.client)).toEqual(bundle);
|
||||
const targetExportPath = join(root, "round-trip.json");
|
||||
structured(
|
||||
await target.client.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: targetExportPath },
|
||||
}),
|
||||
);
|
||||
const observedRecord = records[evidenceIndex]!;
|
||||
expect(observedRecord.parameters).toEqual({ caller: { note: "preserve" } });
|
||||
expect(observedRecord.normalized_result).toEqual({
|
||||
producer: { extension: "preserve" },
|
||||
});
|
||||
expect(object(observedRecord.analysis_profile).parameters).toEqual({
|
||||
loader: { mode: "full" },
|
||||
});
|
||||
expect(await readFile(targetExportPath, "utf8")).toBe(contents);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
sourceClient.close(),
|
||||
source.client.close(),
|
||||
source.server.close(),
|
||||
sourceSession.close(),
|
||||
targetClient.close(),
|
||||
target.client.close(),
|
||||
target.server.close(),
|
||||
targetSession.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
const createBundleSourceSession = () => {
|
||||
const createBundleSourceSession = (root: string) => {
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const evidence = createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
|
||||
const subject = {
|
||||
path: join(root, "game.dol"),
|
||||
sha256: "d".repeat(64),
|
||||
format: "gamecube-dol",
|
||||
architecture: "powerpc",
|
||||
} as const;
|
||||
const evidence = createEvidence(subject, provider, {
|
||||
operation: "observe",
|
||||
parameters: { caller: { note: "preserve" } },
|
||||
result: { producer: { extension: "preserve" } },
|
||||
@@ -253,10 +178,9 @@ const createBundleSourceSession = () => {
|
||||
},
|
||||
locations: [{ kind: "address", address: "0x1000" }],
|
||||
});
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("bundle export must not start a provider");
|
||||
});
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
for (const extra of [
|
||||
createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
|
||||
@@ -275,17 +199,13 @@ const createBundleSourceSession = () => {
|
||||
}),
|
||||
])
|
||||
expect(session.recordEvidence(extra).ok).toBe(true);
|
||||
return session;
|
||||
return { session, evidence, subject };
|
||||
};
|
||||
|
||||
const exportFixtureBundle = async (
|
||||
client: Client,
|
||||
path: string,
|
||||
): Promise<{
|
||||
readonly sourceJson: unknown;
|
||||
readonly records: Record<string, unknown>[];
|
||||
readonly evidenceIndex: number;
|
||||
}> => {
|
||||
): Promise<string> => {
|
||||
const unknown = await client.callTool({
|
||||
name: "record_unknown",
|
||||
arguments: {
|
||||
@@ -305,13 +225,7 @@ const exportFixtureBundle = async (
|
||||
arguments: { path },
|
||||
});
|
||||
expect(exported.isError).not.toBe(true);
|
||||
const sourceJson = JSON.parse(await readFile(path, "utf8")) as unknown;
|
||||
const records = array(object(sourceJson).records).map(object);
|
||||
const evidenceIndex = records.findIndex(
|
||||
(record) => record.operation === "observe",
|
||||
);
|
||||
expect(evidenceIndex).toBeGreaterThanOrEqual(0);
|
||||
return { sourceJson, records, evidenceIndex };
|
||||
return readFile(path, "utf8");
|
||||
};
|
||||
|
||||
const unsupportedBundleFields = (
|
||||
@@ -405,3 +319,8 @@ const structured = (result: Awaited<ReturnType<Client["callTool"]>>) => {
|
||||
throw new Error("Missing structured MCP result");
|
||||
return result.structuredContent as Record<string, unknown>;
|
||||
};
|
||||
|
||||
const getBundle = async (client: Client) =>
|
||||
structured(
|
||||
await client.callTool({ name: "get_evidence_bundle", arguments: {} }),
|
||||
).result;
|
||||
Reference in new issue
Block a user