From db9a0300208ff52cbb981a0213ff3b60fb1cd6c8 Mon Sep 17 00:00:00 2001
From: morluto <76467478+morluto@users.noreply.github.com>
Date: Mon, 30 Nov 2026 21:09:05 -0500
Subject: [PATCH] test(artifacts): assert exact refusal reasons, limits and
cleanup reports (#15379)
* test(artifacts): assert exact refusal reasons, limits and cleanup reports
Replace ok:false-only, bare toThrow, class-only, expect.any and negative-only checks in parser and artifact tests with the exact failure kind, reason, limit, cleanup report, classification and retained samples the producers report.
* test(uefi): assert the receipt issue path through the retained cause
---
.../WxapkgArtifactReader.boundaries.test.ts | 3 +-
.../apple/PropertyListDecodeBudget.test.ts | 33 +++++++++---
src/domain/binaryTarget.test.ts | 35 +++++++++----
src/native/NativeMachoSelectedSlice.test.ts | 8 ++-
src/native/NativeUiObservation.test.ts | 52 ++++++++++++++-----
src/oci/OciImageLayoutParser.test.ts | 18 ++++---
src/resources/ArtifactPaths.test.ts | 13 ++++-
.../SqliteDatabaseSnapshotLimits.test.ts | 17 ++++++
src/uefi/UefiAnalysisProvider.test.ts | 24 ++++++++-
src/vsix/VsixPackageParser.test.ts | 17 ++++--
src/yara/YaraRuleIncludes.test.ts | 9 +++-
.../artifactExtractionSummarySamples.test.ts | 4 +-
.../filesystem/desktopApplication.test.ts | 12 ++++-
.../filesystem/flutterBuildProvider.test.ts | 14 ++++-
.../javascriptIntegrityPolicy.test.ts | 10 ++--
.../boundary/filesystem/zipDetection.test.ts | 38 ++++++++++----
16 files changed, 244 insertions(+), 63 deletions(-)
diff --git a/src/artifacts/WxapkgArtifactReader.boundaries.test.ts b/src/artifacts/WxapkgArtifactReader.boundaries.test.ts
index 6c52d05b053..97e83486856 100644
--- a/src/artifacts/WxapkgArtifactReader.boundaries.test.ts
+++ b/src/artifacts/WxapkgArtifactReader.boundaries.test.ts
@@ -373,7 +373,8 @@ describe("wxapkg stream capacity and freshness", () => {
fixedAllowance: {
name: "The wxapkg directory-and-chunk I/O work allowance",
kind: "parser",
- limit: expect.any(Number),
+ // A one-member package admits the small-reader floor: 4 * 1024.
+ limit: 4096,
unit: "operations",
},
});
diff --git a/src/artifacts/apple/PropertyListDecodeBudget.test.ts b/src/artifacts/apple/PropertyListDecodeBudget.test.ts
index 53699caa74b..9e0ec94401c 100644
--- a/src/artifacts/apple/PropertyListDecodeBudget.test.ts
+++ b/src/artifacts/apple/PropertyListDecodeBudget.test.ts
@@ -4,6 +4,25 @@ import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.
import { parsePlistXmlSource } from "../../native/parsers/plist.js";
import { preflightPropertyListDecode } from "../../domain/apple/propertyListDecodeBudget.js";
+const NATIVE_DECODE_BUDGET_BYTES = 64 * 1024 * 1024;
+
+/** The preflight refusal: its resource, boundary and the budget it applied. */
+const expectDecodeBudgetRefusal = (source: Buffer, error: unknown): void => {
+ expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
+ expect(error).toMatchObject({
+ resource: "memory",
+ reason: "plist representation exceeds the native plist decode budget",
+ reportedLimits: {
+ boundary: "plist-decode-bytes",
+ maximum: NATIVE_DECODE_BUDGET_BYTES,
+ },
+ });
+ // The preflight estimate alone exceeds the budget, so no DOM is built.
+ expect(
+ preflightPropertyListDecode(source, Number.MAX_SAFE_INTEGER).estimatedBytes,
+ ).toBeGreaterThan(NATIVE_DECODE_BUDGET_BYTES);
+};
+
const xmlPlist = (body: string): Buffer =>
Buffer.from(
`\n\n${body}\n`,
@@ -24,20 +43,20 @@ it("refuses an XML plist whose DOM exceeds the native decode budget", () => {
it.each(["é", "_", ":", "雪", "\u{1d4b3}"])(
"refuses 100,000 elements whose names start with %s before building the DOM",
(name) => {
- const parsed = parsePlistXmlSource(
- xmlPlist(`${`<${name}/>`.repeat(100_000)}`),
- );
+ const source = xmlPlist(`${`<${name}/>`.repeat(100_000)}`);
+ const parsed = parsePlistXmlSource(source);
if (parsed.ok) throw new Error("Expected a decode budget refusal");
- expect(parsed.error).toBeInstanceOf(AnalysisResourceConstraintError);
+ expectDecodeBudgetRefusal(source, parsed.error);
},
);
it("refuses text whose entity references exceed the decode budget", () => {
- const parsed = parsePlistXmlSource(
- xmlPlist(`${"&".repeat(1_000_000)}`),
+ const source = xmlPlist(
+ `${"&".repeat(1_000_000)}`,
);
+ const parsed = parsePlistXmlSource(source);
if (parsed.ok) throw new Error("Expected a decode budget refusal");
- expect(parsed.error).toBeInstanceOf(AnalysisResourceConstraintError);
+ expectDecodeBudgetRefusal(source, parsed.error);
});
// Opaque sections hold literal ampersands, not references the parser expands.
diff --git a/src/domain/binaryTarget.test.ts b/src/domain/binaryTarget.test.ts
index bfe2260e454..b7454b783f4 100644
--- a/src/domain/binaryTarget.test.ts
+++ b/src/domain/binaryTarget.test.ts
@@ -106,15 +106,24 @@ describe("executable header parsing", () => {
});
it.each([
- Buffer.alloc(0),
- Buffer.from([0x7f, 0x45, 0x4c, 0x46]),
- fat([], 2),
+ [Buffer.alloc(0), "truncated or unsupported binary header"],
+ [Buffer.from([0x7f, 0x45, 0x4c, 0x46]), "ELF identification is truncated"],
+ [
+ fat([], 2),
+ "FAT table is truncated: the file has 8 bytes and the FAT table needs 48",
+ ],
// A FAT table declaring only unsupported CPU types has nothing to select.
- fat([0x00000012]),
- pe(0xffff),
- ])("rejects malformed, truncated, or unsupported metadata", (bytes) => {
- expect(parseExecutableHeader(bytes, "arm64").ok).toBe(false);
- });
+ [fat([0x00000012]), "FAT binary declares no supported Mach-O architecture"],
+ [pe(0xffff), "unsupported PE architecture (COFF machine 0xffff)"],
+ ] as const)(
+ "rejects malformed, truncated, or unsupported metadata (%#)",
+ (bytes, error) => {
+ expect(parseExecutableHeader(bytes, "arm64")).toEqual({
+ ok: false,
+ error,
+ });
+ },
+ );
it("rejects malformed PE optional-header commitments", () => {
const wrongMagic = pe(0x8664);
@@ -123,8 +132,14 @@ describe("executable header parsing", () => {
truncatedDirectories.writeUInt16LE(112, 64 + 20);
truncatedDirectories.writeUInt32LE(16, 64 + 24 + 108);
- expect(parseExecutableHeader(wrongMagic, "x64").ok).toBe(false);
- expect(parseExecutableHeader(truncatedDirectories, "x64").ok).toBe(false);
+ expect(parseExecutableHeader(wrongMagic, "x64")).toEqual({
+ ok: false,
+ error: "PE optional-header magic does not match its architecture",
+ });
+ expect(parseExecutableHeader(truncatedDirectories, "x64")).toEqual({
+ ok: false,
+ error: "truncated PE data-directory table",
+ });
});
it("admits PE images with short, oversized, or DOS-overlapping headers when fixed fields fit", () => {
diff --git a/src/native/NativeMachoSelectedSlice.test.ts b/src/native/NativeMachoSelectedSlice.test.ts
index 2030f5e3f89..91a6cbb424d 100644
--- a/src/native/NativeMachoSelectedSlice.test.ts
+++ b/src/native/NativeMachoSelectedSlice.test.ts
@@ -101,5 +101,11 @@ it("binds the lipo row to one FAT entry and its selected thin header", async ()
bytes.writeUInt32BE(128, 16);
await expect(
resolveSelectedMachoSlice(source, selected, 2),
- ).rejects.toThrow();
+ ).rejects.toMatchObject({
+ failure: {
+ kind: "malformed",
+ format: "macho",
+ detail: "Selected Mach-O slice overlaps another FAT entry",
+ },
+ });
});
diff --git a/src/native/NativeUiObservation.test.ts b/src/native/NativeUiObservation.test.ts
index 2b5883fd448..28f47bc0cd8 100644
--- a/src/native/NativeUiObservation.test.ts
+++ b/src/native/NativeUiObservation.test.ts
@@ -1,3 +1,4 @@
+import { z } from "zod";
import { createHash } from "node:crypto";
import { malformedInput } from "../domain/parseFailure.js";
import { crc32 } from "node:zlib";
@@ -78,6 +79,22 @@ const observeWithScreenshot = (screenshot: Record) =>
},
);
+/** The helper's screenshot failed validation for exactly these reasons. */
+const expectScreenshotRefusal = (
+ result: Awaited>,
+ ...messages: readonly string[]
+): void => {
+ expect(result).toMatchObject({
+ ok: false,
+ error: { _tag: "ProviderAdapterError" },
+ });
+ if (result.ok) return;
+ const reason = z.string().parse(result.error.diagnostics?.reason);
+ expect(
+ z.array(z.object({ message: z.string() })).parse(JSON.parse(reason)),
+ ).toEqual(messages.map((message) => expect.objectContaining({ message })));
+};
+
it.each([
{ offset: 8, value: 12 },
{ offset: 16, value: 0x8000_0000 },
@@ -88,8 +105,10 @@ it.each([
const bytes = Buffer.from(validPng);
bytes.writeUInt32BE(value, offset);
bytes.writeUInt32BE(crc32(bytes.subarray(12, 29)), 29);
- const result = await observeWithScreenshot(screenshotOf(bytes));
- expect(result.ok).toBe(false);
+ expectScreenshotRefusal(
+ await observeWithScreenshot(screenshotOf(bytes)),
+ "Screenshot bytes are not a PNG image",
+ );
},
);
describe("native UI screenshot validation", () => {
@@ -104,8 +123,9 @@ describe("native UI screenshot validation", () => {
}
const payload =
typeof kind === "number" ? bytes.subarray(0, kind) : bytes;
- expect((await observeWithScreenshot(screenshotOf(payload))).ok).toBe(
- false,
+ expectScreenshotRefusal(
+ await observeWithScreenshot(screenshotOf(payload)),
+ "Screenshot bytes are not a PNG image",
);
},
);
@@ -114,21 +134,27 @@ describe("native UI screenshot validation", () => {
...screenshotOf(validPng),
sha256: "0".repeat(64),
});
- expect(result.ok).toBe(false);
+ expectScreenshotRefusal(result, "PNG screenshot digest mismatch");
});
it.each([
- { base64: "%%%=" },
- { base64: Buffer.from("not a PNG").toString("base64") },
- { width: 2 },
+ { change: { base64: "%%%=" }, reasons: ["Invalid canonical PNG base64"] },
+ {
+ change: { base64: Buffer.from("not a PNG").toString("base64") },
+ reasons: [
+ "PNG screenshot digest mismatch",
+ "Screenshot bytes are not a PNG image",
+ ],
+ },
+ { change: { width: 2 }, reasons: ["PNG screenshot dimensions mismatch"] },
])(
"rejects invalid screenshot field variants from the helper",
- async (change) => {
+ async ({ change, reasons }) => {
const result = await observeWithScreenshot({
...screenshotOf(validPng),
...change,
});
- expect(result.ok).toBe(false);
+ expectScreenshotRefusal(result, ...reasons);
},
);
@@ -137,8 +163,10 @@ describe("native UI screenshot validation", () => {
const type = bytes.subarray(12, 16);
type[0] = (type[0] ?? 0) | 0x80;
expect(type.toString("ascii")).toBe("IHDR");
- const result = await observeWithScreenshot(screenshotOf(bytes));
- expect(result.ok).toBe(false);
+ expectScreenshotRefusal(
+ await observeWithScreenshot(screenshotOf(bytes)),
+ "Screenshot bytes are not a PNG image",
+ );
});
it("accepts a self-consistent PNG screenshot from the helper", async () => {
diff --git a/src/oci/OciImageLayoutParser.test.ts b/src/oci/OciImageLayoutParser.test.ts
index f6082eb4234..2728809b916 100644
--- a/src/oci/OciImageLayoutParser.test.ts
+++ b/src/oci/OciImageLayoutParser.test.ts
@@ -2009,12 +2009,18 @@ it("refuses a missing oci-layout as malformed input", async () => {
await mkdir(root, { recursive: true });
const reader = new DirectoryArtifactReader(root);
try {
- await expect(
- parseOciImageLayout(
- reader,
- inspectOciImageLayoutInputSchema.parse({ path: root }),
- ),
- ).rejects.toBeInstanceOf(ParseFailureError);
+ const parsed = parseOciImageLayout(
+ reader,
+ inspectOciImageLayoutInputSchema.parse({ path: root }),
+ );
+ await expect(parsed).rejects.toBeInstanceOf(ParseFailureError);
+ await expect(parsed).rejects.toMatchObject({
+ failure: {
+ kind: "malformed",
+ format: "oci-image-layout",
+ detail: "Selected directory has no oci-layout file.",
+ },
+ });
} finally {
await reader.close();
}
diff --git a/src/resources/ArtifactPaths.test.ts b/src/resources/ArtifactPaths.test.ts
index e6360c6c529..ffb7031a069 100644
--- a/src/resources/ArtifactPaths.test.ts
+++ b/src/resources/ArtifactPaths.test.ts
@@ -235,7 +235,10 @@ it("reserves prefix capacity atomically without declaring destination kinds", ()
expect(() => registry.reservePath("z")).not.toThrow();
expect(() => registry.reservePath("a/b")).not.toThrow();
registry.add("a/b", "file");
- expect(() => registry.add("a/b", "directory")).toThrow();
+ const collision = pathFailure(() => registry.add("a/b", "directory"));
+ expect(collision).toMatchObject({ reason: "path" });
+ expect(collision.message).toBe('Artifact path collision: "a/b"');
+ expect(collision.readerLimit).toBeUndefined();
});
it("reports a file prefix conflict without inserting the candidate", () => {
@@ -250,5 +253,11 @@ it("reports a file prefix conflict without inserting the candidate", () => {
expect(registry.conflicts("a/b/c")).toBe(true);
expect(registry.conflicts("a/c")).toBe(false);
expect(registry.conflicts("z")).toBe(false);
- expect(() => registry.reservePath("z")).toThrow();
+ // The refusal is the node budget, not a path collision.
+ const refused = pathFailure(() => registry.reservePath("z"));
+ expect(refused.reason).toBe("limit");
+ expect(refused.readerLimit).toMatchObject({
+ parameter: "artifact_limits.deno.path_nodes",
+ effective_value: 2,
+ });
});
diff --git a/src/sqlite/SqliteDatabaseSnapshotLimits.test.ts b/src/sqlite/SqliteDatabaseSnapshotLimits.test.ts
index 222100c422a..3f7c28330cf 100644
--- a/src/sqlite/SqliteDatabaseSnapshotLimits.test.ts
+++ b/src/sqlite/SqliteDatabaseSnapshotLimits.test.ts
@@ -273,6 +273,8 @@ it.each([
cleanup,
cause: expect.any(ArtifactReaderFailure),
});
+ // Without cleanup, the changed evidence wraps the exact read failure.
+ else expect((failure as ArtifactReaderFailure).cause).toBe(primary);
expect(failure).toMatchObject({ partialObservation, details });
const projectedFailure = classifyProviderFailure(
failure,
@@ -284,7 +286,22 @@ it.each([
cleanupIncomplete: true,
cleanupResources: cleanup.resources,
});
+ } else {
+ expect(projectedFailure).toMatchObject({
+ _tag: "AnalysisArtifactChangedError",
+ cleanupIncomplete: false,
+ cleanupResources: [],
+ });
}
+ expect(projectAnalysisError(projectedFailure)).toMatchObject({
+ code: retainCleanup ? "cleanup_incomplete" : "artifact_changed",
+ category: "integrity_mismatch",
+ details: {
+ operation: "inspect_sqlite_database",
+ path: databasePath,
+ integrity_check: "container-identity",
+ },
+ });
} finally {
await resourceScope.close();
}
diff --git a/src/uefi/UefiAnalysisProvider.test.ts b/src/uefi/UefiAnalysisProvider.test.ts
index 57f0eea04ea..23bc524a899 100644
--- a/src/uefi/UefiAnalysisProvider.test.ts
+++ b/src/uefi/UefiAnalysisProvider.test.ts
@@ -672,7 +672,20 @@ it("rolls back staged files if the receipts cannot form a valid extraction resul
});
try {
const result = await provider.execute(extractRequest(imagePath, output));
- expect(result.ok).toBe(false);
+ // The invalid receipt fails result validation, not cleanup.
+ expect(result).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "ProviderAdapterError",
+ cleanupIncomplete: false,
+ diagnostics: { path: output },
+ },
+ });
+ // The retained schema failure names the invalid receipt field.
+ if (result.ok) return;
+ expect(result.error.cause).toMatchObject({
+ issues: [expect.objectContaining({ path: ["files", 0, "sha256"] })],
+ });
expect(existsSync(output)).toBe(false);
} finally {
writing.mockRestore();
@@ -992,6 +1005,15 @@ it("preserves caller cancellation and cleans up the runtime root when worker sta
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.secondaryFailures).toEqual([]);
+ // The caller's reason stays in the cancellation's cause chain.
+ const causes: unknown[] = [];
+ for (
+ let cause: unknown = result.error.cause;
+ cause !== undefined;
+ cause = cause instanceof Error ? cause.cause : undefined
+ )
+ causes.push(cause);
+ expect(causes.at(-1)).toBe("caller cancelled during startup");
}
expect(createdRootPath).toBeDefined();
expect(existsSync(createdRootPath!)).toBe(false);
diff --git a/src/vsix/VsixPackageParser.test.ts b/src/vsix/VsixPackageParser.test.ts
index 28b79c33716..b2514d626a5 100644
--- a/src/vsix/VsixPackageParser.test.ts
+++ b/src/vsix/VsixPackageParser.test.ts
@@ -652,9 +652,20 @@ it("rejects a vsixmanifest document type without decoding identity", async () =>
it("refuses a non-ZIP file without claiming a package inventory", async () => {
const bytes = Buffer.from("not a zip");
- await expect(
- parseVsixPackage(bytes, artifactOf(bytes), defaults),
- ).rejects.toBeInstanceOf(ParseFailureError);
+ const parsed = parseVsixPackage(bytes, artifactOf(bytes), defaults);
+ await expect(parsed).rejects.toBeInstanceOf(ParseFailureError);
+ // The refusal carries only the malformed-format fact, no partial inventory.
+ await expect(parsed).rejects.toSatisfy(
+ (error: ParseFailureError) =>
+ Object.keys(error).sort().join(",") === "_tag,failure,name",
+ );
+ await expect(parsed).rejects.toMatchObject({
+ failure: {
+ kind: "malformed",
+ format: "vsix-package",
+ detail: "Selected file is not a ZIP archive (VS Code .vsix).",
+ },
+ });
});
it.each([
diff --git a/src/yara/YaraRuleIncludes.test.ts b/src/yara/YaraRuleIncludes.test.ts
index 81edc8d23cd..c4924e5c138 100644
--- a/src/yara/YaraRuleIncludes.test.ts
+++ b/src/yara/YaraRuleIncludes.test.ts
@@ -125,7 +125,14 @@ describe("createYaraIncludeScanner", () => {
).join("\n");
const result = scan(text);
expect(result.total).toBe(MAX_RETAINED_DIRECTIVES + 3);
- expect(result.directives).toHaveLength(MAX_RETAINED_DIRECTIVES);
+ // The retained list keeps the first directives, in source order.
+ expect(result.directives).toEqual(
+ Array.from({ length: MAX_RETAINED_DIRECTIVES }, (_, index) => ({
+ line: index + 1,
+ column: 1,
+ path: `r${String(index)}.yar`,
+ })),
+ );
});
it("gives the same result however the bytes are chunked", () => {
diff --git a/tests/boundary/filesystem/artifactExtractionSummarySamples.test.ts b/tests/boundary/filesystem/artifactExtractionSummarySamples.test.ts
index 499a8f13362..c136b98e92b 100644
--- a/tests/boundary/filesystem/artifactExtractionSummarySamples.test.ts
+++ b/tests/boundary/filesystem/artifactExtractionSummarySamples.test.ts
@@ -54,6 +54,7 @@ const parent = createEvidence(
);
it("bounds each summary sample by bytes and pages the rest", async () => {
+ const residualPaths = extraction(16).cleanup.residual_paths;
const summary = await inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
@@ -64,7 +65,7 @@ it("bounds each summary sample by bytes and pages the rest", async () => {
summary: {
cleanup: {
verified: false,
- residual_paths: { items: expect.any(Array), omitted: 12 },
+ residual_paths: { items: residualPaths.slice(0, 4), omitted: 12 },
},
},
});
@@ -78,6 +79,7 @@ it("bounds each summary sample by bytes and pages the rest", async () => {
});
if (!paged.ok) throw paged.error;
expect(paged.value.normalized_result).toMatchObject({
+ items: residualPaths,
coverage: { total: 16, exhausted: true },
});
});
diff --git a/tests/boundary/filesystem/desktopApplication.test.ts b/tests/boundary/filesystem/desktopApplication.test.ts
index e32bbc498db..7d0fbcf310d 100644
--- a/tests/boundary/filesystem/desktopApplication.test.ts
+++ b/tests/boundary/filesystem/desktopApplication.test.ts
@@ -444,8 +444,12 @@ it("retains an entry whose close failed and observes cancellation after final cl
return "observed";
}),
).rejects.toBeInstanceOf(ArtifactReaderFailure);
+ const entryPath = join(root, "entry");
await expect(reader.close()).rejects.toMatchObject({
- cleanup: expect.any(Object),
+ cleanup: {
+ reason: `Could not close opened entry at ${entryPath}: close denied`,
+ resources: [entryPath],
+ },
});
restore?.();
await reader.close();
@@ -1380,8 +1384,12 @@ it.each([false, true])(
expect(report.candidates.map((candidate) => candidate.family)).toEqual([
"godot",
]);
+ const pckPath = join(root, "game.pck");
await expect(service.close()).rejects.toMatchObject({
- cleanup: expect.any(Object),
+ cleanup: {
+ reason: `Could not close opened entry at ${pckPath}: descriptor close denied`,
+ resources: [pckPath],
+ },
});
expect(result.error.cleanupIncomplete).toBe(true);
restore?.();
diff --git a/tests/boundary/filesystem/flutterBuildProvider.test.ts b/tests/boundary/filesystem/flutterBuildProvider.test.ts
index ecfef6642a8..80260fc291d 100644
--- a/tests/boundary/filesystem/flutterBuildProvider.test.ts
+++ b/tests/boundary/filesystem/flutterBuildProvider.test.ts
@@ -768,6 +768,11 @@ it("cancels before creating any snapshot root", async () => {
bytes: libapp(REFERENCE_HASH),
},
]);
+ const removed: string[] = [];
+ interceptFlutterRootRemoval(async (path) => {
+ removed.push(path);
+ await realRm(path, { recursive: true, force: true });
+ });
const controller = new AbortController();
controller.abort();
const provider = new FlutterBuildProvider();
@@ -775,8 +780,15 @@ it("cancels before creating any snapshot root", async () => {
{ operation: "identify_flutter_build", input: { path: apk } },
{ signal: controller.signal },
);
- expect(result.ok).toBe(false);
+ expect(result).toMatchObject({
+ ok: false,
+ error: { _tag: "AnalysisCancelledError", cleanupIncomplete: false },
+ });
+ if (result.ok) throw new Error("cancelled analysis succeeded");
+ expect(result.error.cause).toBe(controller.signal.reason);
await provider.close();
+ // No snapshot root was created, so neither the failure nor close removes one.
+ expect(removed).toEqual([]);
});
it("identifies an ELF header split across the library stream", async () => {
diff --git a/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
index 410748f095b..699345baf31 100644
--- a/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
+++ b/tests/boundary/filesystem/javascriptIntegrityPolicy.test.ts
@@ -23,14 +23,16 @@ 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 declaredSha256 = createHash("sha256").update(original).digest("hex");
+ const observedSha256 = createHash("sha256").update(stripped).digest("hex");
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),
+ declared_sha256: declaredSha256,
+ calculated_sha256: observedSha256,
unpacked: true,
},
remediation: {
@@ -51,8 +53,8 @@ it("records an explicitly continued Electron addon mismatch as untrusted evidenc
);
expect(contradiction).toMatchObject({
logical_path: addon,
- declared_sha256: createHash("sha256").update(original).digest("hex"),
- observed_sha256: createHash("sha256").update(stripped).digest("hex"),
+ declared_sha256: declaredSha256,
+ observed_sha256: observedSha256,
trust: "observed-untrusted",
});
expect(result.graph.coverage.status).toBe("partial");
diff --git a/tests/boundary/filesystem/zipDetection.test.ts b/tests/boundary/filesystem/zipDetection.test.ts
index 2173fdbe307..5d9a40bb2e6 100644
--- a/tests/boundary/filesystem/zipDetection.test.ts
+++ b/tests/boundary/filesystem/zipDetection.test.ts
@@ -294,29 +294,45 @@ describe("ZIP archives after leading bytes", () => {
});
});
+ // Each leading family owns the file: its own parser opens or refuses it.
it.each([
- { family: "ELF", leading: Buffer.from([0x7f, 0x45, 0x4c, 0x46, 1, 1, 1]) },
+ {
+ family: "ELF",
+ leading: Buffer.from([0x7f, 0x45, 0x4c, 0x46, 1, 1, 1]),
+ target: {
+ ok: false,
+ error: {
+ message: "Cannot open artifact: unsupported ELF header version",
+ },
+ },
+ },
{
family: "MZ",
leading: Buffer.concat([Buffer.from("MZ"), Buffer.alloc(62)]),
+ target: { ok: true, value: { kind: "executable", format: "dos-mz" } },
},
{
family: "Mach-O",
leading: Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]),
+ target: {
+ ok: false,
+ error: {
+ message: expect.stringContaining(
+ "Cannot open artifact: truncated Mach-O load commands",
+ ),
+ },
+ },
},
])(
"keeps a $family-led file with an appended ZIP out of the ZIP route",
- async ({ leading }) => {
+ async ({ leading, target }) => {
const root = await createTestTempDirectory("rea-zip-claimed-lead-");
const path = join(root, "program");
await writeFile(path, withLeadingBytes(await memberZip(), leading, true));
expect(
(await classifyAndHashRoot(path, false, await lstat(path))).format,
- ).not.toBe("zip");
- expect(await parseBinaryTarget(path)).not.toMatchObject({
- ok: true,
- value: { format: "zip" },
- });
+ ).toBe("unknown");
+ expect(await parseBinaryTarget(path)).toMatchObject(target);
},
);
@@ -615,10 +631,10 @@ describe("raw disk image signatures", () => {
await writeFile(renamed, bytes);
expect(
(await classifyAndHashRoot(renamed, false, await lstat(renamed))).format,
- ).not.toBe("dmg");
- expect(await parseBinaryTarget(renamed)).not.toMatchObject({
- ok: true,
- value: { format: "dmg" },
+ ).toBe("file");
+ expect(await parseBinaryTarget(renamed)).toMatchObject({
+ ok: false,
+ error: { message: "Cannot open artifact: unsupported binary format" },
});
});