diff --git a/docs/error-contract.schema.json b/docs/error-contract.schema.json index b79e8cee3..765e4813e 100644 --- a/docs/error-contract.schema.json +++ b/docs/error-contract.schema.json @@ -398,7 +398,29 @@ "calculated_sha256": { "anyOf": [{ "type": "string" }, { "type": "null" }] }, - "unpacked": { "type": "boolean" } + "unpacked": { "type": "boolean" }, + "checksum_mismatches": { + "type": "array", + "items": { + "type": "object", + "properties": { + "representation": { + "type": "string", + "enum": ["stored", "decoded"] + }, + "algorithm": { "type": "string" }, + "declared": { "type": "string" }, + "observed": { "type": "string" } + }, + "required": [ + "representation", + "algorithm", + "declared", + "observed" + ], + "additionalProperties": false + } + } }, "required": [ "logical_path", diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index 2ce8f5c3d..e5fce4450 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -260,6 +260,12 @@ Artifact integrity fails closed by default. A request can explicitly select `integrity_policy=record-and-continue` when the investigation needs verified siblings to continue after a mismatch. +Strict member failures include `details.checksum_mismatches` for conflicting +stored or decoded checksums, preserving each algorithm and declared/observed +value. An unsupported checksum algorithm leaves that verification facet unknown; +readable member bytes are still hashed and can be extracted, with the declared +algorithm and value retained in limitations. + Contradictory bytes are quarantined from nested expansion and recorded with declared and observed hashes, trust, provenance, path, and unpacked state. Verified siblings continue. Comparisons classify the result as a contradiction diff --git a/src/artifacts/ArtifactReader.ts b/src/artifacts/ArtifactReader.ts index 782f2c883..6bd1ca324 100644 --- a/src/artifacts/ArtifactReader.ts +++ b/src/artifacts/ArtifactReader.ts @@ -2,6 +2,11 @@ import type { Readable } from "node:stream"; import type { ArtifactCommand } from "../domain/artifactGraph.js"; import type { ZipPackageFormat } from "../domain/zipPackageFormat.js"; import type { ArtifactDecodedBudget } from "./ArtifactDecodedBudget.js"; +import type { + ArtifactChecksumObservation, + ArtifactIntegrityFailureDetails, +} from "../domain/artifactOperationError.js"; +export type { ArtifactChecksumObservation } from "../domain/artifactOperationError.js"; /** Archive-neutral entry metadata. Reader adapters never choose output paths. */ export interface ArtifactEntry { @@ -38,14 +43,6 @@ export interface ArtifactEntry { }; } -/** Checksum evidence for a member representation the scanner cannot hash itself. */ -export interface ArtifactChecksumObservation { - readonly representation: "stored" | "decoded"; - readonly algorithm: string; - readonly declared: string; - readonly observed: string; -} - /** Read-only adapter over one directory, archive, or virtual container. */ export interface ArtifactReader { readonly format: "directory" | ZipPackageFormat | "asar" | "pkg" | "file"; @@ -74,12 +71,7 @@ export class ArtifactReaderFailure extends Error { | "unavailable", message: string, options?: ErrorOptions, - readonly details?: Readonly<{ - logicalPath: string; - declaredSha256: string | null; - calculatedSha256: string | null; - unpacked: boolean; - }>, + readonly details?: ArtifactIntegrityFailureDetails, ) { super(message, options); this.name = "ArtifactReaderFailure"; diff --git a/src/artifacts/XarArtifactReader.ts b/src/artifacts/XarArtifactReader.ts index d869c3bbd..979bb4059 100644 --- a/src/artifacts/XarArtifactReader.ts +++ b/src/artifacts/XarArtifactReader.ts @@ -199,12 +199,12 @@ const memberLimitations = ( ...(unsupportedChecksum === undefined ? [] : [ - `Member declares unsupported checksum ${unsupportedChecksum.style}; integrity not verified.`, + `Member declares unsupported checksum ${unsupportedChecksum.style} ${unsupportedChecksum.value}; integrity not verified.`, ]), ...(unsupportedArchived === undefined ? [] : [ - `Member declares unsupported archived checksum ${unsupportedArchived.style}; stored-byte integrity not verified.`, + `Member declares unsupported archived checksum ${unsupportedArchived.style} ${unsupportedArchived.value}; stored-byte integrity not verified.`, ]), ...(member.data !== undefined && member.data.encoding !== "application/octet-stream" && @@ -725,10 +725,7 @@ export class XarArtifactReader implements ArtifactReader { data.encoding !== "application/octet-stream" && data.encoding !== "application/x-gzip"; const classified = - member.kind === "file" && - unsupportedChecksum === undefined && - unsupportedArchived === undefined && - !unsupportedEncoding + member.kind === "file" && !unsupportedEncoding ? await this.#nestedArchive(member) : { nested: undefined as XarNestedArchive | undefined, @@ -754,11 +751,7 @@ export class XarArtifactReader implements ArtifactReader { classified, ), adapterKey: member.path, - ...(unsupportedEncoding || - unsupportedChecksum !== undefined || - unsupportedArchived !== undefined - ? { contentUnavailable: true } - : {}), + ...(unsupportedEncoding ? { contentUnavailable: true } : {}), ...(classified.nested === undefined ? {} : { nestedArchive: classified.nested }), diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 4975071c7..67df1cb44 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -5,6 +5,7 @@ import { ArtifactReaderFailure, type ArtifactEntry, type ArtifactReader, + type ArtifactChecksumObservation, } from "../ArtifactReader.js"; import type { ArtifactNode } from "../../domain/artifactGraph.js"; import { @@ -159,6 +160,39 @@ interface DigestedEntry { readonly mismatchDetails: readonly string[]; } +const checksumDescription = ({ + representation, + algorithm, + declared, + observed, +}: ArtifactChecksumObservation): string => + `Declared ${representation} ${algorithm} ${declared} disagrees with observed ${observed}.`; + +const entryIntegrityFailure = ( + entry: ArtifactEntry, + logicalPath: string, + observed: { + readonly sha256: string; + readonly checksumMismatches: readonly ArtifactChecksumObservation[]; + }, +): ArtifactReaderFailure => { + const mismatchDetails = observed.checksumMismatches.map(checksumDescription); + return new ArtifactReaderFailure( + "integrity", + `Artifact integrity metadata disagrees with content: ${logicalPath}${mismatchDetails.length === 0 ? "" : ` (${mismatchDetails.join(" ")})`}`, + undefined, + { + logicalPath, + declaredSha256: entry.declaredSha256, + calculatedSha256: observed.sha256, + unpacked: entry.unpacked, + ...(observed.checksumMismatches.length === 0 + ? {} + : { checksumMismatches: observed.checksumMismatches }), + }, + ); +}; + const digestArtifactEntry = async ( context: ScanContext, currentReader: ArtifactReader, @@ -186,20 +220,24 @@ const digestArtifactEntry = async ( ).filter(({ declared, observed }) => declared !== observed); const mismatched = sha256Mismatch || checksumMismatch || storedMismatches.length > 0; + const checksumMismatches = [ + ...(checksumMismatch + ? [ + { + representation: "decoded" as const, + algorithm: checksum.algorithm, + declared: checksum.value, + observed: digest.also ?? "unavailable", + }, + ] + : []), + ...storedMismatches, + ]; if (mismatched && context.integrity.mode === "fail") - throw new ArtifactReaderFailure( - "integrity", - sha256Mismatch || checksum === undefined - ? `Artifact integrity metadata disagrees with content: ${logicalPath}` - : `Declared ${checksum.algorithm} checksum disagrees with content: ${logicalPath}`, - undefined, - { - logicalPath, - declaredSha256: entry.declaredSha256, - calculatedSha256: digest.sha256, - unpacked: entry.unpacked, - }, - ); + throw entryIntegrityFailure(entry, logicalPath, { + sha256: digest.sha256, + checksumMismatches, + }); if (sha256Mismatch && entry.declaredSha256 !== null) context.pendingContradictions.push({ logicalPath, @@ -227,17 +265,7 @@ const digestArtifactEntry = async ( : [], }), mismatched, - mismatchDetails: [ - ...(checksumMismatch - ? [ - `Declared ${checksum.algorithm} ${checksum.value} disagrees with observed ${digest.also ?? "unavailable"}.`, - ] - : []), - ...storedMismatches.map( - ({ representation, algorithm, declared, observed }) => - `Declared ${representation} ${algorithm} ${declared} disagrees with observed ${observed}.`, - ), - ], + mismatchDetails: checksumMismatches.map(checksumDescription), }; }; diff --git a/src/contracts/errorSchemas.ts b/src/contracts/errorSchemas.ts index a535f6abf..314cdd228 100644 --- a/src/contracts/errorSchemas.ts +++ b/src/contracts/errorSchemas.ts @@ -53,6 +53,16 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [ declared_sha256: z.string().nullable(), calculated_sha256: z.string().nullable(), unpacked: z.boolean(), + checksum_mismatches: z + .array( + z.strictObject({ + representation: z.enum(["stored", "decoded"]), + algorithm: z.string(), + declared: z.string(), + observed: z.string(), + }), + ) + .optional(), }) .strict(), }) diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index bd8e7e9c9..c398ccec5 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -249,6 +249,18 @@ const artifactStateErrorDetails = ( declared_sha256: error.artifactDetails.declaredSha256, calculated_sha256: error.artifactDetails.calculatedSha256, unpacked: error.artifactDetails.unpacked, + ...(error.artifactDetails.checksumMismatches === undefined + ? {} + : { + checksum_mismatches: error.artifactDetails.checksumMismatches.map( + ({ representation, algorithm, declared, observed }) => ({ + representation, + algorithm, + declared, + observed, + }), + ), + }), }; if (error instanceof ArtifactOperationError) return { diff --git a/src/domain/artifactOperationError.ts b/src/domain/artifactOperationError.ts index 76c94f348..bcf4bebef 100644 --- a/src/domain/artifactOperationError.ts +++ b/src/domain/artifactOperationError.ts @@ -1,5 +1,22 @@ import { AnalysisError } from "./analysisErrorBase.js"; +/** Declared and observed checksums of one consumed member representation. */ +export interface ArtifactChecksumObservation { + readonly representation: "stored" | "decoded"; + readonly algorithm: string; + readonly declared: string; + readonly observed: string; +} + +/** Evidence identifying an artifact member's failed integrity constraints. */ +export interface ArtifactIntegrityFailureDetails { + readonly logicalPath: string; + readonly declaredSha256: string | null; + readonly calculatedSha256: string | null; + readonly unpacked: boolean; + readonly checksumMismatches?: readonly ArtifactChecksumObservation[]; +} + /** Artifact inventory or extraction failed a typed safety boundary. */ export class ArtifactOperationError extends AnalysisError { readonly _tag = "ArtifactOperationError"; @@ -25,12 +42,7 @@ export class ArtifactOperationError extends AnalysisError { | "path" | "unavailable" | "io", - readonly artifactDetails?: Readonly<{ - logicalPath: string; - declaredSha256: string | null; - calculatedSha256: string | null; - unpacked: boolean; - }>, + readonly artifactDetails?: ArtifactIntegrityFailureDetails, /** The specific constraint that failed, such as the colliding path. */ readonly detail?: string, ) { diff --git a/tests/boundary/filesystem/installerPackageInventory.test.ts b/tests/boundary/filesystem/installerPackageInventory.test.ts index f9234cfd1..770c9acdd 100644 --- a/tests/boundary/filesystem/installerPackageInventory.test.ts +++ b/tests/boundary/filesystem/installerPackageInventory.test.ts @@ -1,16 +1,22 @@ import { createHash } from "node:crypto"; -import { writeFile } from "node:fs/promises"; +import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { z } from "zod"; import { MODE, gzipCpio, xarArchive, + rewriteXarToc, } from "../../../src/artifacts/InstallerPackage.fixture.js"; import { runProviderAnalysis } from "../../../src/composition/directAnalysis.js"; -import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js"; +import { + artifactInventoryResultSchema, + artifactExtractionResultSchema, +} from "../../../src/domain/artifactGraph.js"; +import { analysisErrorProjectionSchema } from "../../../src/contracts/errorSchemas.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -61,6 +67,102 @@ const productPackage = (payloadText: string, extractedSha1?: string) => }, ]); +describe("installer package checksum evidence", () => { + it("reports a stored SHA-1 mismatch independently of a valid decoded MD5", async () => { + const directory = await createTestTempDirectory("rea-pkg-checksum-reason-"); + const path = join(directory, "Installer.pkg"); + const data = Buffer.from("readable content"); + const declared = "0".repeat(40); + await writeFile( + path, + rewriteXarToc( + xarArchive([{ name: "member", data, archivedSha1: declared }]), + (xml) => + xml.replace( + /[^<]+<\/extracted-checksum>/u, + `${createHash("md5").update(data).digest("hex")}`, + ), + ), + ); + const { error, ...projection } = z + .object({ error: z.string() }) + .passthrough() + .parse(await runProviderAnalysis(path, "inventory_artifact", {})); + expect(error).toBe("Analysis failed"); + const failed = analysisErrorProjectionSchema.parse(projection); + expect(failed).toMatchObject({ + code: "artifact_integrity_mismatch", + details: { + logical_path: "member", + checksum_mismatches: [ + { + representation: "stored", + algorithm: "sha1", + declared, + observed: createHash("sha1").update(data).digest("hex"), + }, + ], + }, + }); + }); + + it.each(["raw", "zlib"] as const)( + "hashes and extracts %s content with unsupported stored and decoded checksum algorithms", + async (encoding) => { + const directory = await createTestTempDirectory( + "rea-pkg-unknown-checksum-", + ); + const path = join(directory, "Installer.pkg"); + const data = Buffer.from("readable content"); + await writeFile( + path, + rewriteXarToc(xarArchive([{ name: "member", data, encoding }]), (xml) => + xml + .replaceAll( + '', + '', + ) + .replaceAll( + '', + '', + ), + ), + ); + const inventory = artifactInventoryResultSchema.parse( + parseEvidence(await runProviderAnalysis(path, "inventory_artifact", {})) + .normalized_result, + ); + const member = inventory.occurrences.find( + ({ logical_path }) => logical_path === "member", + ); + expect(member).toMatchObject({ + hash_status: "verified", + limitations: [ + expect.stringContaining("unsupported checksum unknown-decoded"), + expect.stringContaining( + "unsupported archived checksum unknown-stored", + ), + ], + }); + expect( + inventory.nodes.find( + ({ artifact_id }) => artifact_id === member?.artifact_id, + ), + ).toMatchObject({ sha256: sha256(data.toString()), size: data.length }); + const output = join(directory, "extracted"); + const extraction = artifactExtractionResultSchema.parse( + parseEvidence( + await runProviderAnalysis(path, "extract_artifact", { + output_root: output, + }), + ).normalized_result, + ); + expect(extraction.artifacts).toHaveLength(1); + expect(await readFile(join(output, "member"))).toEqual(data); + }, + ); +}); + describe("installer package inventory", () => { it("inventories xar members and expands gzip-cpio scripts and payloads", async () => { const directory = await createTestTempDirectory("rea-pkg-inventory-"); @@ -138,7 +240,7 @@ describe("installer package inventory", () => { .digest("hex"); expect(info).toMatchObject({ hash_status: "mismatched" }); expect(info?.limitations).toContain( - `Declared sha1 ${"0".repeat(40)} disagrees with observed ${observedSha1}.`, + `Declared decoded sha1 ${"0".repeat(40)} disagrees with observed ${observedSha1}.`, ); expect(inventory.limitations).toContainEqual( expect.stringContaining(