feat(javascript): record Electron integrity mismatches
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const run = async (arguments_: readonly string[]): Promise<unknown> => {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
["scripts/rea.mjs", ...arguments_, "--json"],
|
||||
{ cwd: process.cwd(), maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
};
|
||||
|
||||
it.each(["analyze-javascript-application", "analyze"])(
|
||||
"%s carries the integrity policy into shared JavaScript analysis",
|
||||
async (command) => {
|
||||
const { archive, addon } = await createStrippedAsarAddon();
|
||||
const result = await run([
|
||||
command,
|
||||
archive,
|
||||
"--integrity-policy",
|
||||
"record-and-continue",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
parameters: { integrity_policy: "record-and-continue" },
|
||||
normalized_result: {
|
||||
integrity_contradictions: [
|
||||
{ logical_path: addon, trust: "observed-untrusted" },
|
||||
],
|
||||
graph: { coverage: { status: "partial" } },
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects the JavaScript integrity policy on binary-only inspection", async () => {
|
||||
await expect(
|
||||
run(["inspect", "unused.asar", "--integrityPolicy", "record-and-continue"]),
|
||||
).rejects.toMatchObject({
|
||||
code: 1,
|
||||
stdout: expect.stringContaining("Unknown flag: --integrityPolicy"),
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackage, createPackageWithOptions } from "@electron/asar";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { createJavaScriptArtifactReader } from "../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
|
||||
import { readJavaScriptArtifactFiles } from "../../../src/artifacts/javascript/JavaScriptArtifactFiles.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../../src/artifacts/inventory/scanCanonical.js";
|
||||
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("records an explicitly continued Electron addon mismatch as untrusted evidence", async () => {
|
||||
const { archive, addon, original, stripped } =
|
||||
await createStrippedAsarAddon();
|
||||
const rejected = await analyzeJavaScriptApplication({ input_path: archive });
|
||||
if (rejected.ok) throw new Error("Expected strict integrity failure");
|
||||
expect(projectAnalysisError(rejected.error)).toMatchObject({
|
||||
code: "artifact_integrity_mismatch",
|
||||
details: {
|
||||
logical_path: addon,
|
||||
declared_sha256: expect.any(String),
|
||||
calculated_sha256: expect.any(String),
|
||||
unpacked: true,
|
||||
},
|
||||
remediation: {
|
||||
action: expect.stringContaining("integrity_policy=record-and-continue"),
|
||||
},
|
||||
});
|
||||
|
||||
const continued = await analyzeJavaScriptApplication({
|
||||
input_path: archive,
|
||||
integrity_policy: "record-and-continue",
|
||||
});
|
||||
if (!continued.ok) throw new Error("Expected explicit continuation");
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
continued.value.normalized_result,
|
||||
);
|
||||
const contradiction = result.integrity_contradictions.find(
|
||||
({ logical_path }) => logical_path === addon,
|
||||
);
|
||||
expect(contradiction).toMatchObject({
|
||||
logical_path: addon,
|
||||
declared_sha256: createHash("sha256").update(original).digest("hex"),
|
||||
observed_sha256: createHash("sha256").update(stripped).digest("hex"),
|
||||
trust: "observed-untrusted",
|
||||
});
|
||||
expect(result.graph.coverage.status).toBe("partial");
|
||||
expect(result.graph.coverage.omitted_count).toBe(0);
|
||||
expect(result.graph.limitations).toContain(
|
||||
`Artifact integrity metadata contradicts observed bytes at ${addon}; the observed bytes are untrusted.`,
|
||||
);
|
||||
expect(continued.value.parameters).toMatchObject({
|
||||
format: "auto",
|
||||
integrity_policy: "record-and-continue",
|
||||
});
|
||||
expect(result.statistics.parsed_javascript_files).toBeGreaterThan(0);
|
||||
expect(JSON.stringify(result.graph)).toContain(
|
||||
createHash("sha256").update(stripped).digest("hex"),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a contradicted nested ASAR opaque during JavaScript reconstruction", async () => {
|
||||
const root = await createTestTempDirectory("rea-mismatched-nested-asar-");
|
||||
const nestedSource = join(root, "nested-source");
|
||||
const outerSource = join(root, "outer-source");
|
||||
const archive = join(root, "app.asar");
|
||||
const nestedArchive = join(outerSource, "nested.asar");
|
||||
const nestedSecret = "export const nestedOnly = 'not inventoried';\n";
|
||||
await mkdir(nestedSource);
|
||||
await mkdir(outerSource);
|
||||
await writeFile(join(nestedSource, "main.js"), nestedSecret);
|
||||
await writeFile(join(outerSource, "main.js"), "export const outer = true;\n");
|
||||
await createPackage(nestedSource, nestedArchive);
|
||||
await createPackageWithOptions(outerSource, archive, {
|
||||
unpack: "nested.asar",
|
||||
});
|
||||
const unpackedNested = join(`${archive}.unpacked`, "nested.asar");
|
||||
const nestedBytes = await readFile(unpackedNested);
|
||||
nestedBytes[0] = (nestedBytes[0] ?? 0) ^ 0xff;
|
||||
await writeFile(unpackedNested, nestedBytes);
|
||||
|
||||
const analyzed = await analyzeJavaScriptApplication({
|
||||
input_path: archive,
|
||||
integrity_policy: "record-and-continue",
|
||||
});
|
||||
if (!analyzed.ok) throw new Error("Expected explicit continuation");
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
analyzed.value.normalized_result,
|
||||
);
|
||||
expect(result.integrity_contradictions).toMatchObject([
|
||||
{ logical_path: "nested.asar", trust: "observed-untrusted" },
|
||||
]);
|
||||
expect(result.statistics.nested_asar_containers).toBe(0);
|
||||
expect(JSON.stringify(result)).not.toContain(nestedSecret);
|
||||
expect(result.graph.coverage.status).toBe("partial");
|
||||
expect(result.graph.coverage.omitted_count).toBeNull();
|
||||
});
|
||||
|
||||
it("retains semantic resource limits alongside recorded integrity contradictions", async () => {
|
||||
const expression = Array.from(
|
||||
{ length: 20 },
|
||||
() => '(true ? "a" : "b")',
|
||||
).join(" + ");
|
||||
const declarations = ['const value0 = "x";'];
|
||||
for (let index = 1; index <= 30; index += 1) {
|
||||
const previous = `value${String(index - 1)}`;
|
||||
declarations.push(
|
||||
`const value${String(index)} = ${previous} + ${previous};`,
|
||||
);
|
||||
}
|
||||
declarations.push("const answer = value30;");
|
||||
const { archive } = await createStrippedAsarAddon([
|
||||
{ path: "app.js", contents: `const answer = { nested: ${expression} };` },
|
||||
{ path: "growth.js", contents: declarations.join("\n") },
|
||||
]);
|
||||
const analyzed = await analyzeJavaScriptApplication({
|
||||
input_path: archive,
|
||||
integrity_policy: "record-and-continue",
|
||||
});
|
||||
if (!analyzed.ok) throw new Error("Expected explicit continuation");
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
analyzed.value.normalized_result,
|
||||
);
|
||||
expect(result.integrity_contradictions).toHaveLength(1);
|
||||
expect(result.graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omitted_count: null,
|
||||
limits: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_candidates",
|
||||
unit: "items",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "javascript_semantic_primitive_bytes",
|
||||
unit: "bytes",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a nested ASAR introduced after inventory as artifact drift", async () => {
|
||||
const root = await createTestTempDirectory("rea-new-nested-asar-");
|
||||
const nestedSource = join(root, "nested-source");
|
||||
await mkdir(nestedSource);
|
||||
await writeFile(join(root, "main.js"), "export const outer = true;\n");
|
||||
await writeFile(
|
||||
join(nestedSource, "main.js"),
|
||||
"export const nested = true;\n",
|
||||
);
|
||||
const snapshot = await scanCanonicalArtifactInventory(root, {});
|
||||
await createPackage(nestedSource, join(root, "new.asar"));
|
||||
const reader = createJavaScriptArtifactReader(root, "directory");
|
||||
try {
|
||||
await expect(
|
||||
readJavaScriptArtifactFiles(reader, snapshot),
|
||||
).rejects.toMatchObject({
|
||||
reason: "integrity",
|
||||
message: "Nested ASAR was not present in inventory: new.asar",
|
||||
});
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { afterEach, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createStrippedAsarAddon } from "../../fixtures/strippedAsarAddon.js";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { ElectronActiveObservationPort } from "../../../src/application/javascript/ElectronActiveObservationPort.js";
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../../src/domain/javascript/electronActiveObservation.fixture.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const resources: Array<{ close(): Promise<unknown> }> = [];
|
||||
@@ -37,6 +39,52 @@ afterEach(async () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("lets MCP JavaScript analysis continue only with recorded untrusted ASAR bytes", async () => {
|
||||
const { archive, addon } = await createStrippedAsarAddon();
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({ name: "asar-integrity-policy", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const rejected = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: archive },
|
||||
});
|
||||
expect(parseMcpToolError(rejected)).toMatchObject({
|
||||
error: {
|
||||
code: "artifact_integrity_mismatch",
|
||||
remediation: {
|
||||
action: expect.stringContaining("integrity_policy=record-and-continue"),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const continued = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: {
|
||||
input_path: archive,
|
||||
integrity_policy: "record-and-continue",
|
||||
},
|
||||
});
|
||||
expect(continued.isError).not.toBe(true);
|
||||
expect(continued.structuredContent).toMatchObject({
|
||||
parameters: { integrity_policy: "record-and-continue" },
|
||||
normalized_result: {
|
||||
integrity_contradictions: [
|
||||
{ logical_path: addon, trust: "observed-untrusted" },
|
||||
],
|
||||
graph: { coverage: { status: "partial" } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes endpoint-scoped Electron discovery and inspection as Evidence", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-mcp-");
|
||||
temporary.push(root);
|
||||
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
|
||||
import { createTestTempDirectory } from "./temporaryDirectory.js";
|
||||
|
||||
interface AdditionalAsarFile {
|
||||
readonly path: string;
|
||||
readonly contents: string;
|
||||
}
|
||||
|
||||
/** Create an Electron ASAR, then model a distro-stripped unpacked native addon. */
|
||||
export const createStrippedAsarAddon = async (
|
||||
additionalFiles: readonly AdditionalAsarFile[] = [],
|
||||
) => {
|
||||
const root = await createTestTempDirectory("rea-stripped-asar-addon-");
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "app.asar");
|
||||
const addon = "node_modules/btime/binding.node";
|
||||
const addonPath = join(source, "node_modules", "btime", "binding.node");
|
||||
const original = Buffer.from("upstream native addon bytes");
|
||||
const stripped = Buffer.from("stripped native addon");
|
||||
await mkdir(join(source, "node_modules", "btime"), { recursive: true });
|
||||
await writeFile(join(source, "main.js"), "module.exports = 'observed';\n");
|
||||
await writeFile(addonPath, original);
|
||||
for (const file of additionalFiles) {
|
||||
const path = join(source, file.path);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, file.contents);
|
||||
}
|
||||
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
|
||||
await writeFile(
|
||||
join(`${archive}.unpacked`, "node_modules", "btime", "binding.node"),
|
||||
stripped,
|
||||
);
|
||||
return { root, archive, addon, original, stripped };
|
||||
};
|
||||
Reference in New Issue
Block a user