test(firmware): consolidate parsing and process-limit checks (#12844)

* test(firmware): consolidate process limit and recovery checks

* test(uefi): consolidate binary framing coverage
This commit is contained in:
morluto authored and GitHub committed 2026-11-20 14:14:58 +00:00
1 parent 4edb900bdd
commit 67a55ea8e1
8 files changed
+162 -262

No files matched your search

+70 -34
View File
@@ -11,7 +11,11 @@ import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
import { firmwareSignalLimitError } from "./FirmwareFailures.js";
import {
firmwareLimitRecovery,
firmwareProcessLimitRecovery,
firmwareSignalLimitError,
} from "./FirmwareFailures.js";
import { FirmwareFileAccess } from "./FirmwareFiles.js";
import {
resolveFirmwareCommand,
@@ -333,12 +337,13 @@ const signalledLauncher = (
};
stdout.once("end", close);
stderr.once("end", close);
setTimeout(() => {
stdout.end(output.stdout);
stderr.end(output.stderr);
}, 15);
return () =>
Promise.resolve({
return async () => {
// Queue output after runFirmwareCommand attaches the supervisor.
setImmediate(() => {
stdout.end(output.stdout);
stderr.end(output.stderr);
});
return {
process: child,
ownership: {
runId: "rea-firmware-signal",
@@ -346,7 +351,8 @@ const signalledLauncher = (
processGroupId: 4242,
},
cleanup: () => Promise.resolve({ cleaned: true, signaled: false }),
});
};
};
};
const analysisDeadline = (signal: AbortSignal) => ({
@@ -356,7 +362,7 @@ const analysisDeadline = (signal: AbortSignal) => ({
expiresAtMs: performance.now() + 30_000,
});
it("keeps captured tool output when firmware stops on SIGXCPU", async () => {
test("projects the fixed CPU limit and captured output when firmware stops on SIGXCPU", async () => {
const analysis = new AbortController();
const failure: unknown = await runFirmwareCommand({
resources: createTestArtifactResourceScope(),
@@ -371,33 +377,38 @@ it("keeps captured tool output when firmware stops on SIGXCPU", async () => {
signal: analysis.signal,
deadline: analysisDeadline(analysis.signal),
launcher: signalledLauncher("SIGXCPU", {
stdout: "partial scan\n",
stdout: "scan ✓\n",
stderr: "cpu limit\n",
}),
retainCleanup: vi.fn(),
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "cpu",
capturedOutput: {
stdout: "partial scan\n",
stderr: "cpu limit\n",
signal: "SIGXCPU",
exit_code: null,
truncated: false,
if (!(failure instanceof AnalysisError)) throw failure;
expect(failure).toMatchObject({ retryable: false });
expect(projectAnalysisError(failure)).toMatchObject({
code: "resource_constraint",
details: {
resource: "cpu",
reported_limits: { cpu_seconds: FIRMWARE_LIMITS.cpuSeconds },
captured_output: {
stdout: "scan ✓\n",
stderr: "cpu limit\n",
stdout_bytes: 9,
stderr_bytes: 10,
signal: "SIGXCPU",
exit_code: null,
truncated: false,
},
},
remediation: {
action: firmwareLimitRecovery(
`cpuSeconds is ${String(FIRMWARE_LIMITS.cpuSeconds)}`,
),
},
});
if (!(failure instanceof AnalysisError))
throw new Error("Expected a firmware resource constraint");
expect(projectAnalysisError(failure).details?.captured_output).toMatchObject({
stdout: "partial scan\n",
stderr: "cpu limit\n",
signal: "SIGXCPU",
});
});
const sixteenMiB = 16 * 1024 * 1024;
it.each([
test.each([
{
inherited: Number.MAX_SAFE_INTEGER,
limit: sixteenMiB + 1,
@@ -421,15 +432,30 @@ it.each([
environment: process.env,
signal: analysis.signal,
deadline: analysisDeadline(analysis.signal),
launcher: signalledLauncher("SIGXFSZ", { stdout: "", stderr: "" }),
launcher: signalledLauncher("SIGXFSZ", {
stdout: "staging\n",
stderr: "file limit\n",
}),
outputBudget: { root, bytes: sixteenMiB, entries: 10 },
retainCleanup: vi.fn(),
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "file-size",
reportedLimits: { file_size_bytes: limit },
retryable: false,
if (!(failure instanceof AnalysisError)) throw failure;
expect(failure).toMatchObject({ retryable: false });
expect(projectAnalysisError(failure)).toMatchObject({
code: "resource_constraint",
details: {
resource: "file-size",
reported_limits: { file_size_bytes: limit },
captured_output: {
stdout: "staging\n",
stderr: "file limit\n",
stdout_bytes: 8,
stderr_bytes: 11,
signal: "SIGXFSZ",
exit_code: null,
truncated: false,
},
},
});
// Compare with the recovery owner instead of its wording; the two branches
// must differ for the comparison to pin the selected one.
@@ -608,7 +634,17 @@ test.each([
stderr: "producer diagnostics\n",
},
});
expect(projectAnalysisError(failure).code).toBe("execution_failure");
const projected = projectAnalysisError(failure);
expect(projected.code).toBe("execution_failure");
expect(projected.remediation.action).toContain(
firmwareProcessLimitRecovery(FIRMWARE_LIMITS.reportBytes + 1, false),
);
expect(projected.remediation.action).toContain(
String(FIRMWARE_LIMITS.addressSpaceBytes),
);
expect(projected.remediation.action).toContain(
String(FIRMWARE_LIMITS.cpuSeconds),
);
}
},
);
-67
View File
@@ -9,12 +9,8 @@ import { ArtifactReaderFailure } from "../resources/ArtifactReader.js";
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
import {
firmwareFailureDialect,
firmwareLimitRecovery,
firmwarePhaseInterruption,
firmwareProcessLimitRecovery,
firmwareSignalLimitError,
} from "./FirmwareFailures.js";
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
import { startFirmwareDeadline } from "./FirmwareDeadline.js";
import { inventoryFirmwareOutput } from "./FirmwareFiles.js";
@@ -191,69 +187,6 @@ it.each([1234, 2_147_483_647])(
},
);
it("says a CPU signal is fixed and analysis_timeout_ms does not raise it", () => {
const error = firmwareSignalLimitError(
"inspect_firmware_regions",
"SIGXCPU",
FIRMWARE_LIMITS.reportBytes,
false,
);
const projected = projectAnalysisError(error!);
expect(projected).toMatchObject({
code: "resource_constraint",
details: {
resource: "cpu",
reported_limits: { cpu_seconds: FIRMWARE_LIMITS.cpuSeconds },
},
});
expect(projected.message).toContain(String(FIRMWARE_LIMITS.cpuSeconds));
expect(projected.remediation.action).toBe(
firmwareLimitRecovery(
`cpuSeconds is ${String(FIRMWARE_LIMITS.cpuSeconds)}`,
),
);
expect(projected.remediation.action).toContain("no runtime override");
expect(projected.remediation.action).toContain(
"analysis_timeout_ms (--analysis-timeout-ms in the CLI) does not raise it",
);
});
it("retains captured tool output on a CPU or file-size signal", () => {
const captured = {
stdout: "partial scan\n",
stderr: "stopped by prlimit\n",
stdout_bytes: 13,
stderr_bytes: 19,
exit_code: null,
signal: "SIGXCPU",
truncated: false,
};
for (const signal of ["SIGXCPU", "SIGXFSZ"] as const) {
const error = firmwareSignalLimitError(
"inspect_firmware_regions",
signal,
FIRMWARE_LIMITS.reportBytes,
false,
{ ...captured, signal },
);
expect(projectAnalysisError(error!).details?.captured_output).toEqual({
...captured,
signal,
});
}
});
it("names the fixed address-space allowance on an unclassified tool failure", () => {
const recovery = firmwareProcessLimitRecovery(
FIRMWARE_LIMITS.reportBytes,
false,
);
expect(recovery).toContain(String(FIRMWARE_LIMITS.addressSpaceBytes));
expect(recovery).toContain(String(FIRMWARE_LIMITS.cpuSeconds));
expect(recovery).toContain("no runtime override");
expect(recovery).toContain("analysis_timeout_ms does not raise");
});
it("reports the inventory's own deadline expiry as the phase timeout", async () => {
const reason = new DOMException("analysis deadline", "TimeoutError");
const signal = AbortSignal.abort(reason);
+21 -35
View File
@@ -9,51 +9,37 @@ import {
checkFfsFileIntegrity,
} from "./FfsFile.js";
it("parses a valid FFS2 driver file header", () => {
it("observes the FFS2 driver header under either erase polarity and detects checksum corruption", () => {
const file = buildFfsFile({
guid: "17111111-2222-3333-4444-555555555555",
typeCode: 0x07,
payload: Buffer.from("payload-bytes"),
});
const region = imageRegion(file, 0, file.length);
const header = parseFfsFileHeader(region, 0, true);
expect(header).not.toBeNull();
expect(header?.nameGuid).toBe("17111111-2222-3333-4444-555555555555");
expect(header?.typeCode).toBe(0x07);
expect(header?.headerLength).toBe(24);
expect(header?.declaredLength).toBe(24 + 13);
expect(header?.headerChecksumValid).toBe(true);
expect(header?.fileChecksumRequired).toBe(false);
expect(header?.rawState).toBe(0x38);
expect(header?.stateFlags).toEqual([
"header-construction",
"header-valid",
"data-valid",
]);
});
it("flags a deliberately broken header checksum", () => {
const file = buildFfsFile({
guid: "18111111-2222-3333-4444-555555555555",
const stateFlags = ["header-construction", "header-valid", "data-valid"];
expect(parseFfsFileHeader(region, 0, true)).toMatchObject({
nameGuid: "17111111-2222-3333-4444-555555555555",
typeCode: 0x07,
payload: Buffer.from("x"),
breakHeaderChecksum: true,
headerLength: 24,
declaredLength: 37,
headerChecksumValid: true,
fileChecksumRequired: false,
rawState: 0x38,
stateFlags,
});
const region = imageRegion(file, 0, file.length);
expect(parseFfsFileHeader(region, 0, true)?.headerChecksumValid).toBe(false);
});
it("normalizes state bits under both erase polarities", () => {
const file = buildFfsFile({
guid: "19111111-2222-3333-4444-555555555555",
typeCode: 0x07,
payload: Buffer.from("y"),
erasePolarity: false,
file[23] = 0x07; // The state byte is independent of the header checksum.
expect(parseFfsFileHeader(region, 0, false)).toMatchObject({
rawState: 0x07,
stateFlags,
headerChecksumValid: true,
});
file[16] = file.readUInt8(16) ^ 1;
expect(parseFfsFileHeader(region, 0, false)).toMatchObject({
rawState: 0x07,
headerChecksumValid: false,
});
const region = imageRegion(file, 0, file.length);
const header = parseFfsFileHeader(region, 0, false);
expect(header?.rawState).toBe(0x07);
expect(header?.stateFlags).toContain("data-valid");
});
it("verifies the optional file-data checksum", () => {
+26 -29
View File
@@ -13,21 +13,35 @@ import {
walkSections,
} from "./FfsSections.js";
it("walks a two-section chain with clean payload windows", () => {
it("retains aligned payload windows when the final section is truncated", () => {
const ui = buildSection(0x15, Buffer.from("Module"));
const pe = buildSection(0x10, Buffer.from([0x4d, 0x5a, 0x90]));
const chain = Buffer.concat([ui, pe]);
const region = imageRegion(chain, 0, chain.length);
const walked = walkSections(region);
expect(walked.remainder).toBeNull();
expect(walked.sections).toHaveLength(2);
const [uiDraft, peDraft] = walked.sections;
expect(uiDraft?.typeCode).toBe(0x15);
expect(uiDraft?.headerLength).toBe(4);
expect(uiDraft?.payload).toEqual({ start: 4, end: 4 + 6 });
// The PE section starts after the first section's 4-byte chain alignment.
expect(peDraft?.payload).toEqual({ start: 16, end: 19 });
expect(peDraft?.typeCode).toBe(0x10);
const uiDraft = {
typeCode: 0x15,
headerLength: 4,
payload: { start: 4, end: 10 },
};
const peDraft = { typeCode: 0x10, declaredLength: 7 };
expect(walkSections(imageRegion(chain, 0, chain.length))).toMatchObject({
remainder: null,
sections: [
uiDraft,
{ ...peDraft, truncated: false, payload: { start: 16, end: 19 } },
],
});
expect(walkSections(imageRegion(chain, 0, 18))).toMatchObject({
remainder: null,
sections: [
uiDraft,
{
...peDraft,
truncated: true,
observedLength: 6,
payload: { start: 16, end: 18 },
},
],
});
});
it("classifies a guided LZMA section through its definition GUID", () => {
@@ -91,23 +105,6 @@ it("marks unknown definition GUIDs instead of guessing", () => {
expect(draft?.payload).toEqual({ start: 24, end: 24 + 12 });
});
it("records a truncated final section instead of inventing one", () => {
const ui = buildSection(0x15, Buffer.from("Module"));
const truncatedBody = Buffer.alloc(10, 0x77);
truncatedBody.writeUInt32LE(0xfff, 0); // declared far beyond the region
const truncated = Buffer.concat([
Buffer.from([0xff, 0x0f, 0x00, 0x10]), // declared length 0xfff at size field
truncatedBody,
]);
const chain = Buffer.concat([ui, truncated]);
const region = imageRegion(chain, 0, chain.length);
const walked = walkSections(region);
expect(walked.sections).toHaveLength(2);
const last = walked.sections[1];
expect(last?.typeCode).toBe(0x10);
expect(last?.truncated).toBe(true);
});
it("returns no sections when the area is shorter than one header", () => {
const region = imageRegion(Buffer.from([2, 0, 0]), 0, 3);
expect(walkSections(region).sections).toHaveLength(0);
+39 -65
View File
@@ -1,11 +1,7 @@
import { Buffer } from "node:buffer";
import { expect, it } from "vitest";
import {
buildFv,
buildImage,
buildFfsFile,
} from "../../tests/fixtures/uefiImage.js";
import { buildFv } from "../../tests/fixtures/uefiImage.js";
import { imageRegion } from "./UefiBytes.js";
import {
inspectFirmwareVolumeExtension,
@@ -13,37 +9,25 @@ import {
scanFirmwareVolumes,
} from "./FirmwareVolume.js";
const driverFile = (guid: string): Buffer =>
buildFfsFile({ guid, typeCode: 0x07, payload: Buffer.from("body") });
it("parses a valid built volume header with verified checksum", () => {
const fv = buildFv({
files: [driverFile("11111111-2222-3333-4444-555555555555")],
it("observes valid volume geometry and retains the header after checksum corruption", () => {
const { buffer } = buildFv({ files: [] });
const region = imageRegion(buffer, 0, buffer.length);
expect(parseFirmwareVolumeHeader(region, 0)).toMatchObject({
declaredLength: 0x1000,
headerLength: 72,
attributes: 0x800,
erasePolarity: true,
revision: 2,
checksumValid: true,
fileSystemGuid: "8c8ce578-8a3d-4f1c-9935-896185c32dd3",
blockMap: [{ numBlocks: 1, blockLength: 0x1000 }],
});
const region = imageRegion(fv.buffer, 0, fv.buffer.length);
const header = parseFirmwareVolumeHeader(region, 0);
expect(header).not.toBeNull();
expect(header?.declaredLength).toBe(fv.declaredLength);
expect(header?.headerLength).toBe(72);
expect(header?.attributes).toBe(0x800);
expect(header?.erasePolarity).toBe(true);
expect(header?.revision).toBe(2);
expect(header?.checksumValid).toBe(true);
expect(header?.fileSystemGuid).toBe("8c8ce578-8a3d-4f1c-9935-896185c32dd3");
expect(header?.blockMap).toEqual([
{ numBlocks: expect.any(Number), blockLength: 0x1000 },
]);
});
it("flags a corrupted header byte as checksum mismatch but keeps the header", () => {
const fv = buildFv({
files: [driverFile("12111111-2222-3333-4444-555555555555")],
buffer[55] = 3; // revision byte is covered by the header checksum
expect(parseFirmwareVolumeHeader(region, 0)).toMatchObject({
revision: 3,
checksumValid: false,
});
fv.buffer[55] = 3; // revision byte carries the corrupted word checksum
const region = imageRegion(fv.buffer, 0, fv.buffer.length);
const header = parseFirmwareVolumeHeader(region, 0);
expect(header?.revision).toBe(3);
expect(header?.checksumValid).toBe(false);
});
it("returns null when the signature is absent", () => {
@@ -51,42 +35,32 @@ it("returns null when the signature is absent", () => {
expect(parseFirmwareVolumeHeader(region, 0)).toBeNull();
});
it("discovers every volume in an image and rejects implausible _FVH hits", () => {
const fvA = buildFv({
files: [driverFile("13111111-2222-3333-4444-555555555555")],
});
const fvB = buildFv({
files: [driverFile("14111111-2222-3333-4444-555555555555")],
});
// Garbage _FVH text inside a payload: the preceding "header" has zero length,
// so the hit must be rejected, never silently mapped.
const garbage = Buffer.concat([
Buffer.alloc(40, 0x41),
Buffer.from("_FVH", "ascii"),
Buffer.alloc(16, 0x42),
]);
const image = buildImage({ volumes: [fvA.buffer, garbage, fvB.buffer] });
it("counts both accepted and rejected volume candidates toward the scan cap", () => {
const { buffer } = buildFv({ files: [] });
const garbage = Buffer.alloc(0x1000, 0x41);
garbage.write("_FVH", 40, "ascii");
const image = Buffer.concat([buffer, garbage, buffer]);
const region = imageRegion(image, 0, image.length);
const scan = scanFirmwareVolumes(region, 16);
expect(scan.volumes).toHaveLength(2);
expect(scan.rejected).toHaveLength(1);
const firstOffset = scan.volumes[0]?.header.absoluteBase ?? -1;
const secondOffset = scan.volumes[1]?.header.absoluteBase ?? -1;
expect(secondOffset - firstOffset).toBeGreaterThan(0);
expect(scan.rejected[0]?.reason).not.toBe("");
});
const first = { header: { absoluteBase: 0 } };
const second = { header: { absoluteBase: 0x2000 } };
const rejected = [
{
absoluteBase: 0x1000,
signatureLocal: 0x1028,
reason: "header-unparseable",
},
];
it("respects the maxVolumes budget while scanning", () => {
const fvA = buildFv({
files: [driverFile("15111111-2222-3333-4444-555555555555")],
expect(scanFirmwareVolumes(region, 16)).toMatchObject({
volumes: [first, second],
rejected,
limit: null,
});
const fvB = buildFv({
files: [driverFile("16111111-2222-3333-4444-555555555555")],
expect(scanFirmwareVolumes(region, 2)).toMatchObject({
volumes: [first],
rejected,
limit: "candidates",
});
const image = buildImage({ volumes: [fvA.buffer, fvB.buffer] });
const region = imageRegion(image, 0, image.length);
const scan = scanFirmwareVolumes(region, 1);
expect(scan.volumes).toHaveLength(1);
});
it("admits a supported aligned volume after an earlier foreign and unaligned volume", async () => {
+6 -22
View File
@@ -1,11 +1,6 @@
import { Buffer } from "node:buffer";
import { expect, it } from "vitest";
import {
FFS2_FILE_SYSTEM_GUID,
FFS3_FILE_SYSTEM_GUID,
formatGuidLittleEndian,
guidEquals,
} from "./UefiGuid.js";
import { formatGuidLittleEndian } from "./UefiGuid.js";
const ffs2RawBytes = Buffer.from([
0x78, 0xe5, 0x8c, 0x8c, 0x3d, 0x8a, 0x1c, 0x4f, 0x99, 0x35, 0x89, 0x61, 0x85,
@@ -28,8 +23,8 @@ const lzmaf86RawBytes = Buffer.from([
0xea, 0xe8, 0x89,
]);
it("formats the FFS2 container GUID from raw little-endian bytes", () => {
const header = Buffer.alloc(48, 0xff);
it("formats the FFS2 GUID at a nonzero offset ending at the buffer boundary", () => {
const header = Buffer.alloc(32, 0xff);
ffs2RawBytes.copy(header, 16);
expect(formatGuidLittleEndian(header, 16)).toBe(
"8c8ce578-8a3d-4f1c-9935-896185c32dd3",
@@ -37,7 +32,9 @@ it("formats the FFS2 container GUID from raw little-endian bytes", () => {
});
it("names the published FFS3 container GUID for its raw bytes", () => {
expect(formatGuidLittleEndian(ffs3RawBytes, 0)).toBe(FFS3_FILE_SYSTEM_GUID);
expect(formatGuidLittleEndian(ffs3RawBytes, 0)).toBe(
"5473c07a-3dcb-4dca-bd6f-1e9689e7349a",
);
});
it("formats the LZMA custom compression GUID", () => {
@@ -58,16 +55,3 @@ it("returns null for out-of-bounds and truncated reads", () => {
expect(formatGuidLittleEndian(Buffer.alloc(0), -1)).toBeNull();
expect(formatGuidLittleEndian(ffs2RawBytes, 1)).toBeNull();
});
it("accepts a read exactly at the buffer end", () => {
expect(formatGuidLittleEndian(ffs2RawBytes, 0)).toBe(FFS2_FILE_SYSTEM_GUID);
});
it("compares GUIDs case-insensitively without accepting mixed values", () => {
expect(
guidEquals(FFS2_FILE_SYSTEM_GUID, "8C8CE578-8A3D-4F1C-9935-896185C32DD3"),
).toBe(true);
expect(
guidEquals(FFS2_FILE_SYSTEM_GUID, "ee4e5898-3914-4259-9d6e-dc7bd79403cf"),
).toBe(false);
});
-5
View File
@@ -34,11 +34,6 @@ export function formatGuidLittleEndian(
].join("-");
}
/** Case-insensitive canonical GUID comparison. */
export function guidEquals(left: string, right: string): boolean {
return left.toLowerCase() === right.toLowerCase();
}
/**
* FFS2 container GUID (PI Specification, firmware file system 2).
* Raw bytes: 78 E5 8C 8C 3D 8A 1C 4F 99 35 89 61 85 C3 2D D3.
-5
View File
@@ -31,8 +31,6 @@ export interface FfsFileSpec {
/** File-integrity mode; "correct"/"wrong" set the 0x40 attribute bit. */
fileChecksum?: "none" | "correct" | "wrong";
erasePolarity?: boolean;
/** Deliberately corrupt the header checksum byte. */
breakHeaderChecksum?: boolean;
}
const NORMALIZED_COMPLETE_STATE = 0x07;
@@ -70,9 +68,6 @@ export function buildFfsFile(spec: FfsFileSpec): Buffer {
} else {
header[17] = 0xaa;
}
if (spec.breakHeaderChecksum === true) {
header[16] = ((header[16] ?? 0) + 1) & 0xff;
}
return Buffer.concat([header, spec.payload]);
}