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
This commit is contained in:
morluto authored and GitHub committed 2026-12-01 02:09:05 +00:00
1 parent aa09b21a6e
commit db9a030020
16 files changed
+244 -63

No files matched your search

@@ -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",
},
});
@@ -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(
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0">\n${body}</plist>\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(`<array>${`<${name}/>`.repeat(100_000)}</array>`),
);
const source = xmlPlist(`<array>${`<${name}/>`.repeat(100_000)}</array>`);
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(`<array><string>${"&amp;".repeat(1_000_000)}</string></array>`),
const source = xmlPlist(
`<array><string>${"&amp;".repeat(1_000_000)}</string></array>`,
);
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.
+25 -10
View File
@@ -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", () => {
+7 -1
View File
@@ -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",
},
});
});
+40 -12
View File
@@ -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<string, unknown>) =>
},
);
/** The helper's screenshot failed validation for exactly these reasons. */
const expectScreenshotRefusal = (
result: Awaited<ReturnType<typeof observeWithScreenshot>>,
...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 () => {
+12 -6
View File
@@ -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();
}
+11 -2
View File
@@ -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,
});
});
@@ -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();
}
+23 -1
View File
@@ -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);
+14 -3
View File
@@ -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([
+8 -1
View File
@@ -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", () => {
@@ -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 },
});
});
@@ -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?.();
@@ -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 () => {
@@ -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");
+27 -11
View File
@@ -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" },
});
});