From c001100e57dda8eefb8d488be62d506046c69059 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:14:53 -0500 Subject: [PATCH] test(firmware): consolidate OTA integrity and transport proof (#13381) --- ...taPayloadArtifactReader.boundaries.test.ts | 47 +-- .../AndroidOtaPayloadArtifactReader.test.ts | 310 +++--------------- .../ArtifactGraphConstruction.test.ts | 19 -- tests/acceptance/androidOtaPayloadCli.test.ts | 126 +++++-- .../boundary/mcp/androidOtaPayloadMcp.test.ts | 193 ++++++----- 5 files changed, 281 insertions(+), 414 deletions(-) diff --git a/src/artifacts/AndroidOtaPayloadArtifactReader.boundaries.test.ts b/src/artifacts/AndroidOtaPayloadArtifactReader.boundaries.test.ts index 988b58875d..09efbb113c 100644 --- a/src/artifacts/AndroidOtaPayloadArtifactReader.boundaries.test.ts +++ b/src/artifacts/AndroidOtaPayloadArtifactReader.boundaries.test.ts @@ -36,13 +36,17 @@ const entries = async (reader: AndroidOtaPayloadArtifactReader) => { return result; }; -it("refuses a v1 payload as unavailable rather than as a container", async () => { +it("reports the unsupported version at explicit OTA reader admission", async () => { const reader = new AndroidOtaPayloadArtifactReader( await fixture(v1AndroidOtaPayload()), ); try { await expect(entries(reader)).rejects.toMatchObject({ reason: "unavailable", + cause: { + kind: "unsupported", + message: expect.stringContaining("Android OTA payload major version 1"), + }, }); } finally { await reader.close(); @@ -92,12 +96,18 @@ it("keeps a complete manifest without reading a truncated oversized metadata sig expect(await entries(reader)).toMatchObject([{ path: "boot.img" }]); expect(reader.formatMetadata()).toMatchObject({ blob_truncated: true, + manifest_size: manifestEnd - 24, + metadata_signature_size: metadataSignature.length, metadata_signature_count: null, }); - for (const [, , length, offset] of reads.mock - .calls as readonly (readonly unknown[])[]) { - expect(Number(length) + Number(offset)).toBeLessThanOrEqual(manifestEnd); - } + const ranges = reads.mock.calls.map( + ([, , length, offset]: readonly unknown[]) => ({ + offset: Number(offset), + end: Number(offset) + Number(length), + }), + ); + expect(ranges).toContainEqual({ offset: 24, end: manifestEnd }); + expect(ranges.every(({ end }) => end <= manifestEnd)).toBe(true); } finally { reads.mockRestore(); await reader.close(); @@ -105,33 +115,6 @@ it("keeps a complete manifest without reading a truncated oversized metadata sig } }); -it("streams a mismatched REPLACE partition and leaves its declared hash to the scanner", async () => { - const reader = new AndroidOtaPayloadArtifactReader( - await fixture( - buildAndroidOtaPayload({ - partitions: [ - { - name: "boot", - newHash: Buffer.alloc(32, 0xaa), - operations: [{ type: 0, data: Buffer.from("BOOT") }], - }, - ], - }), - ), - ); - try { - const [entry] = await entries(reader); - expect(entry?.declaredIntegrity).toEqual({ - algorithm: "sha256", - digest: "aa".repeat(32), - }); - const bytes = await buffer(await reader.open(entry!)); - expect(bytes.subarray(0, 4).toString("latin1")).toBe("BOOT"); - } finally { - await reader.close(); - } -}); - it("refuses over-budget operation data before reading the sparse carrier body", async () => { const maximum = ANDROID_OTA_MAX_OPERATION_DATA_BYTES; const manifestOnly = buildAndroidOtaPayload({ diff --git a/src/artifacts/AndroidOtaPayloadArtifactReader.test.ts b/src/artifacts/AndroidOtaPayloadArtifactReader.test.ts index 58518c4f1e..40b516fe87 100644 --- a/src/artifacts/AndroidOtaPayloadArtifactReader.test.ts +++ b/src/artifacts/AndroidOtaPayloadArtifactReader.test.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { readFile, writeFile } from "node:fs/promises"; +import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { buffer } from "node:stream/consumers"; @@ -8,16 +8,12 @@ import { expect, it } from "vitest"; import { AndroidOtaPayloadArtifactReader } from "./AndroidOtaPayloadArtifactReader.js"; import { ArtifactEntryContentUnavailable } from "../resources/ArtifactReader.js"; -import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; -import { extractArtifact } from "./extraction/ArtifactExtraction.js"; import { buildAndroidOtaPayload, - deltaAndroidOtaPayload, fullAndroidOtaPayload, v1AndroidOtaPayload, } from "../domain/firmware/androidOtaPayload.fixture.js"; import { zipArchive } from "../domain/desktop/zipArchive.fixture.js"; -import { classifyArtifactBytesAtPath } from "../../tests/fixtures/artifactClassification.js"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js"; @@ -27,91 +23,31 @@ const writeCarrier = async (name: string, bytes: Buffer): Promise => { return path; }; -it("classifies OTA payload bytes as a container by magic, not by suffix", () => { - expect( - classifyArtifactBytesAtPath("update.bin", fullAndroidOtaPayload()), - ).toEqual({ - kind: "container", - format: "android-ota-payload", - }); - expect( - classifyArtifactBytesAtPath("payload.bin", Buffer.from("nope")), - ).toEqual({ - kind: "resource", - format: "file", - }); - expect( - classifyArtifactBytesAtPath("payload.bin", v1AndroidOtaPayload()), - ).toEqual({ - kind: "resource", - format: "file", - }); -}); - -it("classifies a nested payload.bin member by CrAU magic", async () => { - const nested = fullAndroidOtaPayload(); - expect(classifyArtifactBytesAtPath("ota/payload.bin", nested)).toEqual({ - kind: "container", - format: "android-ota-payload", - }); +it("distinguishes supported OTA payload bytes from opaque ZIP members", async () => { const archive = zipArchive([ - { name: "payload.bin", data: nested, method: 0 }, + { name: "update.bin", data: fullAndroidOtaPayload(), method: 0 }, + { name: "old/payload.bin", data: v1AndroidOtaPayload(), method: 0 }, + { name: "notes/payload.bin", data: Buffer.from("nope"), method: 0 }, ]); - expect(classifyArtifactBytesAtPath("update.zip", archive)).toEqual({ - kind: "container", - format: "zip", - }); const snapshot = await scanCanonicalArtifactInventory( await writeCarrier("update.zip", archive), ); expect(snapshot.manifest.root_format).toBe("zip"); + for (const [logical_path, artifact_format, artifact_kind] of [ + ["update.bin", "android-ota-payload", "container"], + ["old/payload.bin", "file", "resource"], + ["notes/payload.bin", "file", "resource"], + ]) { + expect( + snapshot.occurrences.find((row) => row.logical_path === logical_path), + ).toMatchObject({ + artifact_format, + artifact_kind, + }); + } expect( - snapshot.occurrences.find((row) => row.logical_path === "payload.bin"), - ).toMatchObject({ - artifact_format: "android-ota-payload", - artifact_kind: "container", - }); -}); - -it("inventories full-payload partitions, groups, signatures and extractable images", async () => { - const bytes = fullAndroidOtaPayload(); - const snapshot = await scanCanonicalArtifactInventory( - await writeCarrier("payload.bin", bytes), - ); - expect(snapshot.manifest.root_format).toBe("android-ota-payload"); - expect(snapshot.coverage.status).toBe("complete"); - expect(snapshot.limitations.join(" ")).toContain("not verified"); - const root = snapshot.occurrences.find((row) => row.logical_path === "."); - expect(root).toMatchObject({ - artifact_kind: "container", - format_metadata: { - kind: "android-ota-payload", - magic: "CrAU", - major_version: 2, - payload_kind: "full", - signatures_verified: false, - snapshot_enabled: true, - vabc_enabled: true, - security_patch_level: "2024-01-05", - }, - }); - expect(root?.format_metadata).toMatchObject({ - kind: "android-ota-payload", - dynamic_partition_groups: [{ name: "super", partition_names: ["system"] }], - apex_info: [{ package_name: "com.android.runtime" }], - }); - const members = snapshot.occurrences.filter( - (row) => row.logical_path !== ".", - ); - expect(members.map((row) => [row.logical_path, row.hash_status])).toEqual([ - ["boot.img", "verified"], - ["system.img", "verified"], - ]); - expect(members[0]?.format_metadata).toMatchObject({ - kind: "android-ota-partition", - name: "boot", - extractable: true, - }); + snapshot.occurrences.map(({ logical_path }) => logical_path).sort(), + ).toEqual([".", "notes/payload.bin", "old/payload.bin", "update.bin"]); }); it.each([ @@ -144,90 +80,6 @@ it.each([ }, ); -it("inventories a delta payload and leaves non-extractable partitions unread", async () => { - const snapshot = await scanCanonicalArtifactInventory( - await writeCarrier("delta.bin", deltaAndroidOtaPayload()), - ); - expect(snapshot.manifest.root_format).toBe("android-ota-payload"); - expect( - snapshot.occurrences.find(({ logical_path }) => logical_path === "."), - ).toMatchObject({ - format_metadata: { kind: "android-ota-payload", max_timestamp: null }, - }); - expect( - snapshot.limitations.some((note) => note.includes("max_timestamp")), - ).toBe(false); - const vendor = snapshot.occurrences.find( - (row) => row.logical_path === "vendor.img", - ); - expect(vendor).toMatchObject({ - hash_status: "unavailable", - format_metadata: { - kind: "android-ota-partition", - extractable: false, - operation_counts: [ - { type: "SOURCE_COPY", type_code: 4, count: 1 }, - { type: "BROTLI_BSDIFF", type_code: 10, count: 1 }, - ], - }, - }); - expect(vendor?.limitations.join(" ")).toContain("not applied"); -}); - -it("extracts reconstructed REPLACE and ZERO images", async () => { - const path = await writeCarrier("payload.bin", fullAndroidOtaPayload()); - const resourceScope = new ArtifactResourceScope(); - try { - const extracted = await extractArtifact({ - inputPath: path, - inputFormat: "android-ota-payload", - outputRoot: join(path, "..", "out"), - environment: process.env, - integrityPolicy: "fail", - resourceScope, - }); - expect(extracted.containment_verified).toBe(true); - const boot = await readFile(join(extracted.output_root, "boot.img")); - expect(boot.subarray(0, 7).toString("latin1")).toBe("BOOTIMG"); - const system = await readFile(join(extracted.output_root, "system.img")); - expect(system.equals(Buffer.alloc(8192))).toBe(true); - } finally { - await resourceScope.close(); - } -}); - -it("refuses to extract a delta partition", async () => { - const path = await writeCarrier("delta.bin", deltaAndroidOtaPayload()); - const reader = new AndroidOtaPayloadArtifactReader(path); - try { - const entries = []; - for await (const entry of reader.entries()) entries.push(entry); - await expect(reader.open(entries[0]!)).rejects.toBeInstanceOf( - ArtifactEntryContentUnavailable, - ); - } finally { - await reader.close(); - } - const resourceScope = new ArtifactResourceScope(); - try { - await expect( - extractArtifact({ - inputPath: path, - inputFormat: "android-ota-payload", - outputRoot: join(path, "..", "out"), - environment: process.env, - integrityPolicy: "fail", - resourceScope, - }), - ).rejects.toMatchObject({ - reason: "unavailable", - message: expect.stringContaining("vendor.img"), - }); - } finally { - await resourceScope.close(); - } -}); - it("keeps the manifest when a partition exceeds the extraction limit", async () => { const path = await writeCarrier( "large.bin", @@ -275,15 +127,9 @@ it("keeps the manifest when a partition exceeds the extraction limit", async () it("keeps partition inventory when the blob is truncated", async () => { const full = fullAndroidOtaPayload(); - const snapshot = await scanCanonicalArtifactInventory( - await writeCarrier("payload.bin", full), - ); - const blobOffset = snapshot.occurrences.find( - (row) => row.logical_path === ".", - )?.format_metadata; - expect(blobOffset?.kind).toBe("android-ota-payload"); - if (blobOffset?.kind !== "android-ota-payload") return; - const truncated = full.subarray(0, blobOffset.blob_offset + 1); + const metadataBytes = + Number(full.readBigUInt64BE(12)) + full.readUInt32BE(20); + const truncated = full.subarray(0, 24 + metadataBytes + 1); const kept = await scanCanonicalArtifactInventory( await writeCarrier("truncated.bin", truncated), ); @@ -298,86 +144,11 @@ it("keeps partition inventory when the blob is truncated", async () => { partitions: [{ name: "boot" }, { name: "system" }], }); expect( - kept.occurrences.find((row) => row.logical_path === "boot.img") - ?.hash_status, - ).toBe("unavailable"); -}); - -it("streams a reconstructed partition whose hash matches the manifest", async () => { - const path = await writeCarrier( - "boot.bin", - buildAndroidOtaPayload({ - partitions: [ - { - name: "boot", - operations: [{ type: 0, data: Buffer.from("KERNEL") }], - }, - ], - }), - ); - const reader = new AndroidOtaPayloadArtifactReader(path); - try { - const listed = []; - for await (const item of reader.entries()) listed.push(item); - const [entry] = listed; - const bytes = await buffer(await reader.open(entry!)); - expect(bytes.subarray(0, 6).toString("latin1")).toBe("KERNEL"); - expect(createHash("sha256").update(bytes).digest("hex")).toBe( - entry?.declaredIntegrity && "digest" in entry.declaredIntegrity - ? entry.declaredIntegrity.digest - : "", - ); - } finally { - await reader.close(); - } -}); - -it("applies the caller's integrity policy to a partition hash mismatch", async () => { - const path = await writeCarrier( - "mismatch.bin", - buildAndroidOtaPayload({ - partitions: [ - { - name: "boot", - newHash: Buffer.alloc(32, 0xff), - operations: [{ type: 0, data: Buffer.from("KERNEL") }], - }, - ], - }), - ); - await expect(scanCanonicalArtifactInventory(path)).rejects.toMatchObject({ - reason: "integrity", - }); - const recorded = await scanCanonicalArtifactInventory(path, { - integrity: "record-and-continue", - }); - expect( - recorded.occurrences.find((row) => row.logical_path === "boot.img"), - ).toMatchObject({ hash_status: "mismatched" }); - expect(recorded.integrity_contradictions).toEqual([ - expect.objectContaining({ - logical_path: "boot.img", - trust: "observed-untrusted", - }), + kept.occurrences.filter(({ logical_path }) => logical_path !== "."), + ).toMatchObject([ + { logical_path: "boot.img", hash_status: "unavailable" }, + { logical_path: "system.img", hash_status: "verified" }, ]); - const resourceScope = new ArtifactResourceScope(); - try { - const extracted = await extractArtifact({ - inputPath: path, - inputFormat: "android-ota-payload", - outputRoot: join(path, "..", "out"), - environment: process.env, - integrityPolicy: "record-and-continue", - resourceScope, - }); - const boot = await readFile(join(extracted.output_root, "boot.img")); - expect(boot.subarray(0, 6).toString("latin1")).toBe("KERNEL"); - expect(extracted.integrity_contradictions).toEqual([ - expect.objectContaining({ logical_path: "boot.img" }), - ]); - } finally { - await resourceScope.close(); - } }); it("checks the stored OTA operation bytes when a partition hash is absent", async () => { @@ -398,17 +169,24 @@ it("checks the stored OTA operation bytes when a partition hash is absent", asyn ); const reader = new AndroidOtaPayloadArtifactReader(path); try { - for await (const entry of reader.entries()) { - expect(entry.path).toBe("boot.img"); - const opened = reader.open(entry).then(buffer); - if (data === original) { - expect((await opened).equals(original)).toBe(true); - } else { - await expect(opened).rejects.toMatchObject({ - reason: "integrity", - message: expect.stringContaining("operation 0"), - }); - } + const entries = []; + for await (const entry of reader.entries()) entries.push(entry); + expect(entries).toHaveLength(1); + const [entry] = entries; + if (entry === undefined) throw new Error("Missing boot partition"); + expect(entry).toMatchObject({ + path: "boot.img", + declaredIntegrity: null, + }); + const opened = reader.open(entry).then(buffer); + if (data === original) { + expect((await opened).equals(original)).toBe(true); + } else { + await expect(opened).rejects.toMatchObject({ + reason: "integrity", + integrityCheck: "declared-digest", + message: expect.stringContaining("operation 0"), + }); } } finally { await reader.close(); diff --git a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts b/src/artifacts/inventory/ArtifactGraphConstruction.test.ts index 1acf10b07f..32e207e09c 100644 --- a/src/artifacts/inventory/ArtifactGraphConstruction.test.ts +++ b/src/artifacts/inventory/ArtifactGraphConstruction.test.ts @@ -45,10 +45,6 @@ import { } from "../../../tests/fixtures/espImage.js"; import { devicetreeFixture } from "../../domain/firmware/devicetree.fixture.js"; import { fitFixture } from "../fit/FitImage.fixture.js"; -import { - fullAndroidOtaPayload, - v1AndroidOtaPayload, -} from "../../domain/firmware/androidOtaPayload.fixture.js"; it("joins only observed PE signature bytes across stream chunks", () => { const bytes = pe(0x8664, 8190); @@ -595,21 +591,6 @@ it("classifies nested HEX and S-record content as containers by bytes", () => { ).toEqual({ kind: "resource", format: "file" }); }); -it("classifies nested Android OTA payloads as containers by CrAU magic", () => { - expect( - classifyArtifactBytesAtPath("ota/payload.bin", fullAndroidOtaPayload()), - ).toEqual({ - kind: "container", - format: "android-ota-payload", - }); - expect( - classifyArtifactBytesAtPath("ota/payload.bin", v1AndroidOtaPayload()), - ).toEqual({ - kind: "resource", - format: "file", - }); -}); - it("classifies nested ESP images as containers by bytes", () => { const image = espImage({ segments: ESP32C3_APP_SEGMENTS }); expect(classifyArtifactBytesAtPath("ota/update.dat", image)).toEqual({ diff --git a/tests/acceptance/androidOtaPayloadCli.test.ts b/tests/acceptance/androidOtaPayloadCli.test.ts index 4995c82bba..280cfc9ae8 100644 --- a/tests/acceptance/androidOtaPayloadCli.test.ts +++ b/tests/acceptance/androidOtaPayloadCli.test.ts @@ -212,10 +212,22 @@ cliTest( ], }); await writeFile(source, bytes); - const environment = { TMPDIR: root, TMP: root, TEMP: root }; + const output = join(root, "out"); + const observed = createHash("sha256").update(data).digest("hex"); + const contradiction = { + logical_path: "boot.img", + declared_sha256: "ab".repeat(32), + observed_sha256: observed, + trust: "observed-untrusted", + }; const refused = await cli.run({ - arguments: ["extract-artifact", source, "--json"], - environment, + arguments: [ + "extract-artifact", + source, + "--output-root", + output, + "--json", + ], }); expect(refused.exitCode).toBe(1); expect(refused.json).toMatchObject({ @@ -223,7 +235,7 @@ cliTest( details: { logical_path: "boot.img", declared_sha256: "ab".repeat(32), - calculated_sha256: createHash("sha256").update(data).digest("hex"), + calculated_sha256: observed, }, }); expect(await readdir(root)).toEqual(["payload.bin"]); @@ -241,14 +253,33 @@ cliTest( parseEvidence(recorded.json).normalized_result, ); const graph = inspection.substeps[0]!.evidence.normalized_result; + expect( + graph.occurrences.find(({ logical_path }) => logical_path === "boot.img"), + ).toMatchObject({ hash_status: "mismatched" }); expect(graph.integrity_contradictions).toEqual([ - expect.objectContaining({ - logical_path: "boot.img", - declared_sha256: "ab".repeat(32), - observed_sha256: createHash("sha256").update(data).digest("hex"), - trust: "observed-untrusted", - }), + expect.objectContaining(contradiction), ]); + + const continued = await cli.run({ + arguments: [ + "extract-artifact", + source, + "--output-root", + output, + "--integrity-policy", + "record-and-continue", + "--json", + ], + }); + expect(continued.exitCode, continued.stdout + continued.stderr).toBe(0); + const result = artifactExtractionResultSchema.parse( + parseEvidence(continued.json).normalized_result, + ); + expect(result).toMatchObject({ + containment_verified: true, + integrity_contradictions: [contradiction], + }); + expect((await readFile(join(output, "boot.img"))).equals(data)).toBe(true); expect((await readFile(source)).equals(bytes)).toBe(true); }, ); @@ -269,6 +300,9 @@ cliTest( const graph = inspection.substeps[0]!.evidence.normalized_result; expect(graph.manifest.root_format).toBe("android-ota-payload"); expect(graph.coverage.status).toBe("complete"); + expect(graph.limitations).toContainEqual( + expect.stringMatching(/signatures?.*not verified/iu), + ); expect( graph.occurrences.find((row) => row.logical_path === ".") ?.format_metadata, @@ -288,10 +322,15 @@ cliTest( ); expect(result.containment_verified).toBe(true); expect( - (await readFile(join(result.output_root, "boot.img"))) - .subarray(0, 7) - .toString("latin1"), - ).toBe("BOOTIMG"); + (await readFile(join(result.output_root, "boot.img"))).equals( + Buffer.from("BOOTIMG"), + ), + ).toBe(true); + expect( + (await readFile(join(result.output_root, "system.img"))).equals( + Buffer.alloc(8192), + ), + ).toBe(true); }, ); @@ -304,8 +343,14 @@ cliTest( const inspected = await cli.run({ arguments: ["inspect-artifact", source, "--json"], }); - expect(inspected.exitCode).not.toBe(0); - expect(`${inspected.stdout}\n${inspected.stderr}`).toContain("unsupported"); + expect(inspected.exitCode).toBe(1); + expect(inspected.json).toMatchObject({ + code: "target_unavailable", + details: { + constraint: "file_format_rejected", + reason: expect.stringContaining("Android OTA payload major version 1"), + }, + }); }, ); @@ -325,12 +370,49 @@ cliTest( const graph = inspection.substeps[0]!.evidence.normalized_result; expect(graph.manifest.root_format).toBe("android-ota-payload"); expect( - graph.occurrences.find((row) => row.logical_path === "vendor.img"), - ).toMatchObject({ hash_status: "unavailable" }); - const extracted = await cli.run({ - arguments: ["extract-artifact", source, "--json"], - environment: { TMPDIR: root, TMP: root, TEMP: root }, + graph.occurrences.find(({ logical_path }) => logical_path === "."), + ).toMatchObject({ + format_metadata: { payload_kind: "delta", max_timestamp: null }, }); - expect(extracted.exitCode).not.toBe(0); + expect( + graph.limitations.some((note) => note.includes("max_timestamp")), + ).toBe(false); + expect( + graph.occurrences.find( + ({ logical_path }) => logical_path === "vendor.img", + ), + ).toMatchObject({ + hash_status: "unavailable", + limitations: expect.arrayContaining([ + expect.stringContaining("not applied"), + ]), + format_metadata: { + kind: "android-ota-partition", + extractable: false, + operation_counts: [ + { type: "SOURCE_COPY", type_code: 4, count: 1 }, + { type: "BROTLI_BSDIFF", type_code: 10, count: 1 }, + ], + }, + }); + const extracted = await cli.run({ + arguments: [ + "extract-artifact", + source, + "--output-root", + join(root, "out"), + "--json", + ], + }); + expect(extracted.exitCode).toBe(1); + expect(extracted.json).toMatchObject({ + code: "artifact_operation_failed", + details: { + operation: "extract_artifact", + reason: "unavailable", + detail: expect.stringContaining("vendor.img"), + }, + }); + expect(await readdir(root)).toEqual(["payload.bin"]); }, ); diff --git a/tests/boundary/mcp/androidOtaPayloadMcp.test.ts b/tests/boundary/mcp/androidOtaPayloadMcp.test.ts index fcc3499193..a861e67a5f 100644 --- a/tests/boundary/mcp/androidOtaPayloadMcp.test.ts +++ b/tests/boundary/mcp/androidOtaPayloadMcp.test.ts @@ -1,90 +1,133 @@ -import { readFile, rm, writeFile } from "node:fs/promises"; +import { readFile, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { parseEvidence } from "../../../src/domain/evidence.js"; -import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js"; +import { + analysisViewResultSchema, + artifactInventorySummaryViewResultSchema, +} from "../../../src/domain/analysisView/analysisViewResult.js"; import { artifactExtractionResultSchema } from "../../../src/domain/artifactGraph.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { fullAndroidOtaPayload, v1AndroidOtaPayload, } from "../../../src/domain/firmware/androidOtaPayload.fixture.js"; -it.each(["compact"] as const)( - "retains Android OTA payload facts through compiled MCP (%s)", - async (profile) => { - const root = await createTestTempDirectory("rea-android-ota-mcp-"); - const path = join(root, "payload.bin"); - await writeFile(path, fullAndroidOtaPayload()); - const { call } = await connectLocalToolsMcp({ - REA_MCP_TOOL_FAMILIES: "session,artifact", - REA_MCP_INPUT_SCHEMA_PROFILE: profile, - REA_MCP_OUTPUT_SCHEMA_PROFILE: profile, - }); - let outputRoot: string | undefined; - try { - const opened = await call("open_binary", { path }); - expect(opened.isError, JSON.stringify(opened)).not.toBe(true); - expect(opened.structuredContent).toMatchObject({ - result: { - kind: "archive", - format: "android-ota-payload", - architecture: null, - }, - }); - const reply = await call("inspect_artifact", {}); - expect(reply.isError, JSON.stringify(reply)).not.toBe(true); - const inspection = artifactInspectionResultSchema.parse( - parseEvidence(reply.structuredContent).normalized_result, - ); - const inventory = inspection.substeps[0]!.evidence.normalized_result; - expect(inventory.coverage.status).toBe("complete"); - expect(inventory.occurrences).toContainEqual( - expect.objectContaining({ - logical_path: ".", - format_metadata: expect.objectContaining({ - kind: "android-ota-payload", - payload_kind: "full", - signatures_verified: false, - security_patch_level: "2024-01-05", - }), - }), - ); - const summary = await call("inspect_artifact", { detail: "summary" }); - expect(summary.isError, JSON.stringify(summary)).not.toBe(true); - const summaryRoot = JSON.stringify( - parseEvidence(summary.structuredContent).normalized_result, - ); - expect(summaryRoot).toContain('"kind":"android-ota-payload-summary"'); - expect(summaryRoot).not.toContain('"operation_counts"'); - const extracted = await call("extract_artifact", {}); - expect(extracted.isError, JSON.stringify(extracted)).not.toBe(true); - const result = artifactExtractionResultSchema.parse( - parseEvidence(extracted.structuredContent).normalized_result, - ); - outputRoot = result.output_root; - expect(result.containment_verified).toBe(true); - expect( - (await readFile(join(result.output_root, "boot.img"))) - .subarray(0, 7) - .toString("latin1"), - ).toBe("BOOTIMG"); - } finally { - if (outputRoot !== undefined) await rm(outputRoot, { recursive: true }); - } - }, -); - -it("refuses a v1 Android OTA payload through compiled MCP open_binary", async () => { - const root = await createTestTempDirectory("rea-android-ota-mcp-v1-"); +it("extracts and retains complete OTA facts behind a compact MCP summary", async () => { + const root = await createTestTempDirectory("rea-android-ota-mcp-"); const path = join(root, "payload.bin"); - await writeFile(path, v1AndroidOtaPayload()); - const { call } = await connectLocalToolsMcp({ - REA_MCP_TOOL_FAMILIES: "session,artifact", - }); + const bytes = fullAndroidOtaPayload(); + await writeFile(path, bytes); + const { call } = await connectLocalToolsMcp({}); const opened = await call("open_binary", { path }); - expect(opened.isError).toBe(true); - expect(JSON.stringify(opened)).toContain("unsupported"); + expect(opened.isError, JSON.stringify(opened)).not.toBe(true); + expect(opened.structuredContent).toMatchObject({ + result: { + kind: "archive", + format: "android-ota-payload", + architecture: null, + }, + }); + + const inspected = await call("inspect_artifact", { detail: "summary" }); + expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true); + const { summary, parent_evidence_id } = + artifactInventorySummaryViewResultSchema.parse( + parseEvidence(inspected.structuredContent).normalized_result, + ); + expect(summary).toMatchObject({ + source_coverage: { status: "complete" }, + root_format_metadata: { + kind: "android-ota-payload-summary", + payload_kind: "full", + security_patch_level: "2024-01-05", + signatures_verified: false, + partition_count: 2, + extractable_partition_count: 2, + dynamic_partition_group_count: 1, + apex_info_count: 1, + }, + }); + for (const field of [ + "partitions", + "dynamic_partition_groups", + "apex_info", + "operation_counts", + ]) + expect(summary.root_format_metadata).not.toHaveProperty(field); + + const extracted = await call("extract_artifact", { + output_root: join(root, "out"), + }); + expect(extracted.isError, JSON.stringify(extracted)).not.toBe(true); + const result = artifactExtractionResultSchema.parse( + parseEvidence(extracted.structuredContent).normalized_result, + ); + expect(result.containment_verified).toBe(true); + expect( + (await readFile(join(result.output_root, "boot.img"))).equals( + Buffer.from("BOOTIMG"), + ), + ).toBe(true); + expect( + (await readFile(join(result.output_root, "system.img"))).equals( + Buffer.alloc(8192), + ), + ).toBe(true); + expect((await readFile(path)).equals(bytes)).toBe(true); + await unlink(path); + + const retained = await call("inspect_analysis_view", { + source: { kind: "retained-evidence", evidence_id: parent_evidence_id }, + view: { + kind: "inventory", + collection: "occurrences", + fields: ["logical_path", "format_metadata", "hash_status"], + }, + }); + expect(retained.isError, JSON.stringify(retained)).not.toBe(true); + const view = analysisViewResultSchema.parse( + parseEvidence(retained.structuredContent).normalized_result, + ); + expect(view).toMatchObject({ + kind: "inventory", + items: [ + { + logical_path: ".", + format_metadata: { + kind: "android-ota-payload", + magic: "CrAU", + major_version: 2, + payload_kind: "full", + signatures_verified: false, + snapshot_enabled: true, + vabc_enabled: true, + partitions: [{ name: "boot" }, { name: "system" }], + dynamic_partition_groups: [ + { name: "super", partition_names: ["system"] }, + ], + apex_info: [{ package_name: "com.android.runtime" }], + }, + }, + { + logical_path: "boot.img", + hash_status: "verified", + format_metadata: { name: "boot", extractable: true }, + }, + { logical_path: "system.img", hash_status: "verified" }, + ], + }); + + await writeFile(path, v1AndroidOtaPayload()); + const { error } = parseMcpToolError(await call("open_binary", { path })); + expect(error).toMatchObject({ + code: "target_unavailable", + details: { + constraint: "file_format_rejected", + reason: expect.stringContaining("Android OTA payload major version 1"), + }, + }); });