diff --git a/src/firmware/FirmwareFiles.ts b/src/firmware/FirmwareFiles.ts index 2e408517b2..52d55677b3 100644 --- a/src/firmware/FirmwareFiles.ts +++ b/src/firmware/FirmwareFiles.ts @@ -1,6 +1,6 @@ import { safeParseUtf8Json } from "../domain/safeJson.js"; import { createHash } from "node:crypto"; -import { createWriteStream } from "node:fs"; +import { createWriteStream, type Stats } from "node:fs"; import { chmod, lstat, opendir, readlink } from "node:fs/promises"; import { isAbsolute, join, relative, sep } from "node:path"; import { Readable, Transform } from "node:stream"; @@ -209,7 +209,7 @@ export class FirmwareFileAccess { /** Own the exact source descriptor consumed by publication through its final close. */ publish( entry: FirmwareEntry, - sha256: string, + sha256: string | null | undefined, tree: SafeOutputTree, signal: AbortSignal, ) { @@ -229,7 +229,10 @@ export class FirmwareFileAccess { yield* readArtifactFileChunks(handle, { signal }); })(), ), - { sha256, bytes: entry.size }, + { + bytes: entry.size, + ...(sha256 === undefined || sha256 === null ? {} : { sha256 }), + }, signal, ), ), @@ -422,18 +425,58 @@ export const inventoryFirmwareOutput = async ( ); names.push(decoded.name); } - for (const name of names.sort()) { - const path = join(directory, name); - const stat = await lstat(path).catch((cause: unknown) => { - if ( - cause instanceof Error && - "code" in cause && - cause.code === "ENOENT" - ) - return undefined; - throw cause; - }); - if (stat === undefined) continue; + const sortedNames = names.sort(); + const inspected = new Array< + | { + readonly path: string; + readonly stat: Stats; + readonly linkTarget: + | ReturnType + | undefined; + } + | undefined + >(sortedNames.length); + let cursor = 0; + let firstFailure: unknown; + const inspectWorker = async (): Promise => { + while (firstFailure === undefined) { + const index = cursor++; + const name = sortedNames[index]; + if (name === undefined) return; + try { + throwIfFirmwareInventoryCancelled(signal, operation, deadline); + const path = join(directory, name); + const stat = await lstat(path).catch((cause: unknown) => { + if ( + cause instanceof Error && + "code" in cause && + cause.code === "ENOENT" + ) + return undefined; + throw cause; + }); + if (stat === undefined) continue; + const linkTarget = stat.isSymbolicLink() + ? observedSymlinkTarget( + await readlink(path, { encoding: "buffer" }), + ) + : undefined; + inspected[index] = { path, stat, linkTarget }; + } catch (cause: unknown) { + firstFailure ??= cause; + return; + } + } + }; + const workerCount = Math.min(16, sortedNames.length); + await Promise.allSettled( + Array.from({ length: workerCount }, () => inspectWorker()), + ); + if (firstFailure !== undefined) throw firstFailure; + + for (const item of inspected) { + if (item === undefined) continue; + const { path, stat, linkTarget } = item; if (stat.isDirectory()) { pending.push(path); continue; @@ -443,9 +486,6 @@ export const inventoryFirmwareOutput = async ( throw firmwareStagingLimit(operation, "max_output_bytes", maxBytes); if (stat.isFile() && stat.size >= fileSizeBytes) throw firmwareFileSizeLimitReached(operation, fileSizeBytes); - const linkTarget = stat.isSymbolicLink() - ? observedSymlinkTarget(await readlink(path, { encoding: "buffer" })) - : undefined; entries.push({ path, relativePath: relative(root, path).split(sep).join("/"), diff --git a/src/firmware/FirmwarePublication.ts b/src/firmware/FirmwarePublication.ts index 67d689f9e0..fe3ee2746a 100644 --- a/src/firmware/FirmwarePublication.ts +++ b/src/firmware/FirmwarePublication.ts @@ -118,29 +118,23 @@ export const publishFirmwareExtraction = async (context: { | undefined; const files: z.infer["files"] = []; + const workerFailures: unknown[] = []; let totalFiles = 0; + let verifiedFiles = 0; const progress = () => ({ output_directory: context.outputDirectory, - verified_files: files.length, + verified_files: verifiedFiles, total_files: totalFiles, }); try { const materialized = new Set(); - for (const entry of context.entries) - if (entry.kind === "file") - materialized.add(`$output/${entry.relativePath}`); - totalFiles = materialized.size; - for (const path of context.normalized.files.keys()) { - if (path !== "$input" && !materialized.has(path)) - throw new AnalysisOutputError( - "extract_firmware", - `Reported regular file is absent from materialized output: ${path}`, - ); - } + const regularEntries: FirmwareEntry[] = []; const unpublished = []; - tree = await SafeOutputTree.create(context.outputDirectory); for (const entry of context.entries) { - if (entry.kind !== "file") { + if (entry.kind === "file") { + materialized.add(`$output/${entry.relativePath}`); + regularEntries.push(entry); + } else { unpublished.push({ relative_path: entry.relativePath, kind: entry.kind, @@ -149,39 +143,80 @@ export const publishFirmwareExtraction = async (context: { ? {} : { link_target_hex: entry.linkTargetHex }), }); - continue; } - const logicalPath = `$output/${entry.relativePath}`; - const reported = context.normalized.files.get(logicalPath); - const sha256 = await context.files.hash(entry.path, context.signal); - if ( - (reported?.sha256 !== null && - reported?.sha256 !== undefined && - reported.sha256 !== sha256) || - (context.normalized.sizes.has(logicalPath) && - context.normalized.sizes.get(logicalPath) !== entry.size) - ) + } + totalFiles = materialized.size; + for (const path of context.normalized.files.keys()) { + if (path !== "$input" && !materialized.has(path)) throw new AnalysisOutputError( "extract_firmware", - `Extracted bytes disagree with provider report: ${entry.relativePath}`, + `Reported regular file is absent from materialized output: ${path}`, ); - const written = await context.files.publish( - entry, - sha256, - tree, - context.signal, - ); - files.push({ - relative_path: entry.relativePath, - path: join(tree.outputRoot, written.relativePath), - size: entry.size, - sha256, - reported_sha256: reported?.sha256 ?? null, - mime_type: reported?.mimeType ?? null, - analysis_depth: reported?.depth ?? null, - runtime_address: null, - original_file_range: null, - }); + } + tree = await SafeOutputTree.create(context.outputDirectory); + const activeTree = tree; + const publishedSlots = new Array<(typeof files)[number] | undefined>( + regularEntries.length, + ); + let cursor = 0; + const publishWorker = async (): Promise => { + while (workerFailures.length === 0) { + const index = cursor++; + const entry = regularEntries[index]; + if (entry === undefined) return; + try { + const logicalPath = `$output/${entry.relativePath}`; + const reported = context.normalized.files.get(logicalPath); + if ( + context.normalized.sizes.has(logicalPath) && + context.normalized.sizes.get(logicalPath) !== entry.size + ) { + throw new AnalysisOutputError( + "extract_firmware", + `Extracted bytes disagree with provider report: ${entry.relativePath}`, + ); + } + const written = await context.files.publish( + entry, + undefined, + activeTree, + context.signal, + ); + if ( + reported?.sha256 !== null && + reported?.sha256 !== undefined && + reported.sha256 !== written.sha256 + ) { + throw new AnalysisOutputError( + "extract_firmware", + `Extracted bytes disagree with provider report: ${entry.relativePath}`, + ); + } + publishedSlots[index] = { + relative_path: entry.relativePath, + path: join(activeTree.outputRoot, written.relativePath), + size: entry.size, + sha256: written.sha256, + reported_sha256: reported?.sha256 ?? null, + mime_type: reported?.mimeType ?? null, + analysis_depth: reported?.depth ?? null, + runtime_address: null, + original_file_range: null, + }; + verifiedFiles += 1; + } catch (cause: unknown) { + workerFailures.push(cause); + return; + } + } + }; + const workerCount = Math.min(8, regularEntries.length); + await Promise.allSettled( + Array.from({ length: workerCount }, () => publishWorker()), + ); + if (workerFailures.length > 0) throw workerFailures[0]; + for (const item of publishedSlots) { + if (item !== undefined) files.push(item); } result = firmwareResultSchemas.extract_firmware.parse({ analysis_timeout_ms: context.analysisTimeoutMs, @@ -227,23 +262,45 @@ export const publishFirmwareExtraction = async (context: { : new AnalysisCleanupLease(async () => { await ownedTree.rollback(); }); - const primary = classifyProviderFailure( + const dialect = firmwareFailureDialect({ + engine: "unblob", + operation: "extract_firmware", + phase: { + signal: context.signal, + deadline: context.deadline, + publication: progress(), + }, + treeCleanupLease: treeLease, + }); + let primary = classifyProviderFailure( outputDirectoryAdmissionRefusal( "extract_firmware", "output_directory", cause, ), - firmwareFailureDialect({ - engine: "unblob", - operation: "extract_firmware", - phase: { - signal: context.signal, - deadline: context.deadline, - publication: progress(), - }, - treeCleanupLease: treeLease, - }), + dialect, ); + if (workerFailures.length > 1 && Object.is(cause, workerFailures[0])) { + for (const extraCause of workerFailures.slice(1)) { + const extra = classifyProviderFailure( + outputDirectoryAdmissionRefusal( + "extract_firmware", + "output_directory", + extraCause, + ), + dialect, + ); + if (extra.cleanupIncomplete) { + primary = analysisErrorWithCleanupDependencies( + primary, + extra, + "extract_firmware", + ); + } else { + primary.retainSecondaryFailure(extra); + } + } + } try { await treeLease?.release(); } catch (cleanupCause: unknown) { diff --git a/src/process/OwnedCommand.ts b/src/process/OwnedCommand.ts index 78d56aa555..f27dedd4a8 100644 --- a/src/process/OwnedCommand.ts +++ b/src/process/OwnedCommand.ts @@ -151,7 +151,7 @@ export const prepareOwnedCommand = async ( }; /** Both preparation stages preserve physical failures, opaque cancellation and exact owners. */ -function throwCommandPreparationFailure( +export function throwCommandPreparationFailure( cause: unknown, interruption: "cancelled" | "timeout" | undefined, ): never { diff --git a/src/resources/SafeOutputTree.ts b/src/resources/SafeOutputTree.ts index 3dd93a796a..b4439e1c5a 100644 --- a/src/resources/SafeOutputTree.ts +++ b/src/resources/SafeOutputTree.ts @@ -108,6 +108,7 @@ export class SafeOutputTree { readonly #outputRoot: string; #rootIdentity: DirectoryIdentity | undefined; readonly #nestedDirectories = new Map(); + readonly #creatingDirectories = new Map>(); readonly #unknownDirectories = new Set(); readonly #ownedFiles = new Map(); /** Exclusive files awaiting identity admission; admitted identity and handles have separate owners. */ @@ -278,7 +279,7 @@ export class SafeOutputTree { async write( relativePath: string, source: Readable, - expected: { readonly sha256: string; readonly bytes: number }, + expected: { readonly sha256?: string | null; readonly bytes: number }, signal?: AbortSignal, ): Promise { try { @@ -353,7 +354,11 @@ export class SafeOutputTree { { integrityCheck: "declared-size" }, ); const sha256 = hash.digest("hex"); - if (sha256 !== expected.sha256) + if ( + expected.sha256 !== undefined && + expected.sha256 !== null && + sha256 !== expected.sha256 + ) throw new ArtifactReaderFailure( "integrity", `Extracted content disagrees with inventory: ${path}`, @@ -609,35 +614,54 @@ export class SafeOutputTree { logicalParent.length === 0 ? part : `${logicalParent}/${part}`; current = join(current, part); await assertPathIdentity(parent.path, parent.identity); - const creation = await mkdir(current, { mode: 0o700 }).then( - () => ({ kind: "created" }) as const, - (cause: unknown) => { - if (hasUnrepresentableName(cause)) - throw new DestinationPathUnrepresentableFailure(logicalPath, { - cause, - }); - if (!isAlreadyExists(cause)) throw cause; - return { kind: "existing", cause } as const; - }, - ); - if (creation.kind === "existing") { - await throwIfDestinationCaseCollision( - parent.path, - logicalPath, - creation.cause, - ); - const identity = this.#nestedDirectories.get(current); - if (identity === undefined) throw replacedDirectory(current); - await assertPathIdentity(current, identity); + const inflight = this.#creatingDirectories.get(current); + if (inflight !== undefined) { + await inflight; + await throwIfDestinationCaseCollision(parent.path, logicalPath); + const existingIdentity = this.#nestedDirectories.get(current); + if (existingIdentity === undefined) throw replacedDirectory(current); + await assertPathIdentity(current, existingIdentity); } else { - const identity = await readDirectoryIdentity(current).catch( - (cause: unknown) => { - this.#unknownDirectories.add(current); - throw cause; - }, - ); - this.#nestedDirectories.set(current, identity); - await this.#secureCreatedDirectory(current, identity); + const ensureDir = async (): Promise => { + const creation = await mkdir(current, { mode: 0o700 }).then( + () => ({ kind: "created" }) as const, + (cause: unknown) => { + if (hasUnrepresentableName(cause)) + throw new DestinationPathUnrepresentableFailure(logicalPath, { + cause, + }); + if (!isAlreadyExists(cause)) throw cause; + return { kind: "existing", cause } as const; + }, + ); + if (creation.kind === "existing") { + await throwIfDestinationCaseCollision( + parent.path, + logicalPath, + creation.cause, + ); + const known = this.#nestedDirectories.get(current); + if (known === undefined) throw replacedDirectory(current); + await assertPathIdentity(current, known); + return known; + } + const createdIdentity = await readDirectoryIdentity(current).catch( + (cause: unknown) => { + this.#unknownDirectories.add(current); + throw cause; + }, + ); + this.#nestedDirectories.set(current, createdIdentity); + await this.#secureCreatedDirectory(current, createdIdentity); + return createdIdentity; + }; + const pending = ensureDir(); + this.#creatingDirectories.set(current, pending); + try { + await pending; + } finally { + this.#creatingDirectories.delete(current); + } } await assertPathIdentity(parent.path, parent.identity); const identity = this.#nestedDirectories.get(current); diff --git a/src/uefi/UefiAnalysisProvider.test.ts b/src/uefi/UefiAnalysisProvider.test.ts index 7188d1fa81..64f933db0f 100644 --- a/src/uefi/UefiAnalysisProvider.test.ts +++ b/src/uefi/UefiAnalysisProvider.test.ts @@ -1,6 +1,6 @@ import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; -import { readFile, stat, writeFile } from "node:fs/promises"; +import { readFile, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -8,7 +8,7 @@ import { deflateSync } from "node:zlib"; import { expect, it, vi } from "vitest"; import { SafeOutputTree } from "../resources/SafeOutputTree.js"; import { SafeOutputTreeCreationFailure } from "../resources/SafeOutputTreeCreationFailure.js"; -import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import { ProviderProcessSupervisor } from "../process/ProviderProcess.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; import { createDeferred } from "../../tests/fixtures/binarySession.js"; @@ -663,7 +663,7 @@ it("rolls back staged files if the receipts cannot form a valid extraction resul }); it.skipIf(!lzmaWorkerAvailable)( - "retains the worker root across a failed descriptor retry and releases its child before root removal", + "retains the worker root across a failed child stop retry and stops its child before root removal", async () => { const driver = buildFfsFile({ guid: GUID_DRIVER, @@ -677,11 +677,11 @@ it.skipIf(!lzmaWorkerAvailable)( await writeFile(imagePath, buildFv({ files: [driver] }).buffer); const provider = new UefiAnalysisProvider(distUefiLzmaWorker); const create = PrivateRuntimeRoot.create; - const closeHandle = OwnedFileHandle.prototype.close; + const stopProcess = ProviderProcessSupervisor.prototype.stop; const closeRoot = PrivateRuntimeRoot.prototype.close; let root: PrivateRuntimeRoot | undefined; - let outputHandle: OwnedFileHandle | undefined; - let denyDescriptor = true; + let workerPid: number | undefined; + let denyStop = true; let denyRoot = true; const creating = vi .spyOn(PrivateRuntimeRoot, "create") @@ -690,24 +690,14 @@ it.skipIf(!lzmaWorkerAvailable)( if (options?.prefix === "rea-uefi-lzma-") root = created; return created; }); - const closingHandle = vi - .spyOn(OwnedFileHandle.prototype, "close") - .mockImplementation(async function (this: OwnedFileHandle) { - const outputPath = - root === undefined ? undefined : join(root.path, "output.bin"); - if (outputPath !== undefined && this.handle.fd >= 0) { - const output = await stat(outputPath).catch(() => undefined); - const fd = await this.handle.stat(); - if ( - output !== undefined && - fd.dev === output.dev && - fd.ino === output.ino - ) { - outputHandle = this; - if (denyDescriptor) throw new Error("worker output close denied"); - } + const stopping = vi + .spyOn(ProviderProcessSupervisor.prototype, "stop") + .mockImplementation(async function (this: ProviderProcessSupervisor) { + workerPid = this.launch.process.pid; + if (denyStop) { + return { status: "incomplete", reason: "worker stop denied" }; } - return closeHandle.call(this); + return stopProcess.call(this); }); const closingRoot = vi .spyOn(PrivateRuntimeRoot.prototype, "close") @@ -719,23 +709,35 @@ it.skipIf(!lzmaWorkerAvailable)( try { const result = await provider.execute(inspectRequest(imagePath)); - if (result.ok || root === undefined || outputHandle === undefined) { - throw new Error("worker output descriptor failure was not exercised"); + if (result.ok || root === undefined || workerPid === undefined) { + throw new Error("worker stop failure was not exercised"); } expect(result.error.cleanupResources).toEqual( - expect.arrayContaining([root.path, join(root.path, "output.bin")]), + expect.arrayContaining([root.path, `pid:${String(workerPid)}`]), ); + expect(result.error.partialObservation).toMatchObject({ + kind: "uefi", + result: { + firmware_volumes: [ + expect.objectContaining({ + ffs_files: [expect.objectContaining({ guid: GUID_DRIVER })], + }), + ], + }, + provenance: { + path: imagePath, + }, + }); await expect(provider.close()).rejects.toThrow( /cleanup remains incomplete/i, ); expect(closingRoot.mock.contexts).not.toContain(root); expect(existsSync(root.path)).toBe(true); - denyDescriptor = false; + denyStop = false; await expect(provider.close()).rejects.toThrow( /cleanup remains incomplete/i, ); - expect(outputHandle.handle.fd).toBe(-1); expect(result.error.cleanupResources).toEqual([root.path]); expect(existsSync(root.path)).toBe(true); @@ -744,8 +746,10 @@ it.skipIf(!lzmaWorkerAvailable)( expect(existsSync(root.path)).toBe(false); expect(result.error.cleanupIncomplete).toBe(false); } finally { + denyStop = false; + denyRoot = false; creating.mockRestore(); - closingHandle.mockRestore(); + stopping.mockRestore(); closingRoot.mockRestore(); await provider.close(); } @@ -753,6 +757,276 @@ it.skipIf(!lzmaWorkerAvailable)( 45_000, ); +it.skipIf(!lzmaWorkerAvailable)( + "retains the completed inspection when cancellation arrives during pooled worker shutdown", + async () => { + const driver = buildFfsFile({ + guid: GUID_DRIVER, + typeCode: 7, + payload: buildLzmaGuidedSection( + Buffer.from(lzmaPurescript.compressFile(Buffer.from("worker output"))), + ), + }); + const directory = await createTestTempDirectory( + "rea-uefi-late-worker-close-", + ); + const imagePath = join(directory, "image.fi"); + await writeFile(imagePath, buildFv({ files: [driver] }).buffer); + const controller = new AbortController(); + const stopProcess = ProviderProcessSupervisor.prototype.stop; + const stopping = vi + .spyOn(ProviderProcessSupervisor.prototype, "stop") + .mockImplementationOnce(async function (this: ProviderProcessSupervisor) { + controller.abort("cancelled during worker close"); + return stopProcess.call(this); + }); + const provider = new UefiAnalysisProvider(distUefiLzmaWorker); + try { + const result = await provider.execute(inspectRequest(imagePath), { + signal: controller.signal, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.partialObservation).toMatchObject({ + kind: "uefi", + result: { + firmware_volumes: [ + expect.objectContaining({ + ffs_files: [expect.objectContaining({ guid: GUID_DRIVER })], + }), + ], + }, + provenance: { + path: imagePath, + }, + }); + } + } finally { + stopping.mockRestore(); + await provider.close(); + } + }, + 45_000, +); + +it.skipIf(!lzmaWorkerAvailable)( + "reuses one persistent LZMA worker across multiple sections and reuses the validated scan for extraction", + async () => { + const mod1 = buildSection(0x10, Buffer.from("DXE-DRIVER-ONE-PAYLOAD")); + const mod2 = buildSection(0x10, Buffer.from("DXE-DRIVER-TWO-PAYLOAD")); + const corrupt = Buffer.from([0x5d, 0x00, 0x00, 0x80, 0x00, 0xaa, 0xbb]); + const f1 = buildFfsFile({ + guid: GUID_DRIVER, + typeCode: 7, + payload: buildLzmaGuidedSection( + Buffer.from(lzmaPurescript.compressFile(mod1)), + ), + }); + const fBad = buildFfsFile({ + guid: "55555555-6666-4777-8888-999999999999", + typeCode: 7, + payload: buildLzmaGuidedSection(corrupt), + }); + const f2 = buildFfsFile({ + guid: GUID_RAW, + typeCode: 7, + payload: buildLzmaGuidedSection( + Buffer.from(lzmaPurescript.compressFile(mod2)), + ), + }); + const directory = await createTestTempDirectory("rea-uefi-worker-pool-"); + const imagePath = join(directory, "multi-lzma.fd"); + await writeFile(imagePath, buildFv({ files: [f1, fBad, f2] }).buffer); + + let lzmaRootsCreated = 0; + const create = PrivateRuntimeRoot.create; + const creating = vi + .spyOn(PrivateRuntimeRoot, "create") + .mockImplementation(async (options) => { + if (options?.prefix === "rea-uefi-lzma-") lzmaRootsCreated += 1; + return create(options); + }); + const provider = new UefiAnalysisProvider(distUefiLzmaWorker); + try { + const inspected = expectOk( + await provider.execute(inspectRequest(imagePath)), + ).value.result as UefiInspectResult; + expect(lzmaRootsCreated).toBe(1); + expect(inspected.coverage).toBe("partial"); + + const extracted = expectOk( + await provider.execute( + extractRequest(imagePath, join(directory, "out"), { + include_compressed: false, + }), + ), + ).value.result as UefiExtractResult; + // Validated scan summary is reused across inspect -> extract without spawning another worker. + expect(lzmaRootsCreated).toBe(1); + expect( + extracted.files + .filter((entry) => entry.source === "raw-section") + .map((entry) => entry.sha256), + ).toEqual([ + sha256(Buffer.from("DXE-DRIVER-ONE-PAYLOAD")), + sha256(Buffer.from("DXE-DRIVER-TWO-PAYLOAD")), + ]); + } finally { + creating.mockRestore(); + await provider.close(); + } + }, + 45_000, +); + +it("keeps worker stdin errors owned across cancellation of an in-flight frame write", async () => { + const directory = await createTestTempDirectory("rea-uefi-stdin-cancel-"); + const blockedWorker = join(directory, "blocked-worker.mjs"); + await writeFile(blockedWorker, "setInterval(() => {}, 1000);\n", "utf8"); + const largeCompressed = Buffer.alloc(512 * 1024, 0x5d); + const ffs = buildFfsFile({ + guid: GUID_DRIVER, + typeCode: 7, + payload: buildLzmaGuidedSection(largeCompressed), + }); + const imagePath = join(directory, "large-lzma.fd"); + await writeFile(imagePath, buildFv({ files: [ffs] }).buffer); + + const uncaught: unknown[] = []; + const onUncaught = (err: unknown) => { + uncaught.push(err); + }; + process.on("uncaughtException", onUncaught); + + const controller = new AbortController(); + let capturedStdin: NodeJS.WritableStream | undefined; + const stop = ProviderProcessSupervisor.prototype.stop; + const stopping = vi + .spyOn(ProviderProcessSupervisor.prototype, "stop") + .mockImplementation(async function (this: ProviderProcessSupervisor) { + capturedStdin = this.launch.process.stdin ?? undefined; + capturedStdin?.emit( + "error", + Object.assign(new Error("write EPIPE during stop"), { code: "EPIPE" }), + ); + return stop.call(this); + }); + + const provider = new UefiAnalysisProvider(blockedWorker); + try { + const timer = setTimeout(() => { + controller.abort(new Error("caller cancelled write")); + }, 120); + const result = await provider.execute(inspectRequest(imagePath), { + signal: controller.signal, + }); + clearTimeout(timer); + if (capturedStdin !== undefined) { + capturedStdin.emit( + "error", + Object.assign(new Error("write EPIPE"), { code: "EPIPE" }), + ); + } + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error._tag).toBe("AnalysisCancelledError"); + } + expect(uncaught).toEqual([]); + } finally { + stopping.mockRestore(); + process.off("uncaughtException", onUncaught); + await provider.close(); + } +}); + +it("preserves caller cancellation and cleans up the runtime root when worker startup aborts before launch", async () => { + const directory = await createTestTempDirectory("rea-uefi-startup-cancel-"); + const ffs = buildFfsFile({ + guid: GUID_DRIVER, + typeCode: 7, + payload: buildLzmaGuidedSection( + Buffer.from([0x5d, 0x00, 0x00, 0x80, 0x00]), + ), + }); + const imagePath = join(directory, "startup-cancel.fd"); + await writeFile(imagePath, buildFv({ files: [ffs] }).buffer); + + const controller = new AbortController(); + const createRoot = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot); + let createdRootPath: string | undefined; + const creating = vi + .spyOn(PrivateRuntimeRoot, "create") + .mockImplementationOnce(async (options) => { + const root = await createRoot(options); + createdRootPath = root.path; + controller.abort("caller cancelled during startup"); + return root; + }); + const provider = new UefiAnalysisProvider(); + try { + const result = await provider.execute(inspectRequest(imagePath), { + signal: controller.signal, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.secondaryFailures).toEqual([]); + } + expect(createdRootPath).toBeDefined(); + expect(existsSync(createdRootPath!)).toBe(false); + } finally { + creating.mockRestore(); + await provider.close(); + } +}); + +it("preserves provider_timeout and cleans up the runtime root when the deadline expires during worker startup", async () => { + const directory = await createTestTempDirectory("rea-uefi-startup-timeout-"); + const ffs = buildFfsFile({ + guid: GUID_DRIVER, + typeCode: 7, + payload: buildLzmaGuidedSection( + Buffer.from([0x5d, 0x00, 0x00, 0x80, 0x00]), + ), + }); + const imagePath = join(directory, "startup-timeout.fd"); + await writeFile(imagePath, buildFv({ files: [ffs] }).buffer); + + const createRoot = PrivateRuntimeRoot.create.bind(PrivateRuntimeRoot); + let createdRootPath: string | undefined; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const creating = vi + .spyOn(PrivateRuntimeRoot, "create") + .mockImplementationOnce(async (options) => { + const root = await createRoot(options); + createdRootPath = root.path; + vi.advanceTimersByTime(UEFI_FIRMWARE_LIMITS.timeoutMs); + return root; + }); + const provider = new UefiAnalysisProvider(); + try { + const result = await provider.execute(inspectRequest(imagePath)); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toMatchObject({ + _tag: "AnalysisTimeoutError", + timeoutMs: UEFI_FIRMWARE_LIMITS.timeoutMs, + }); + expect(result.error.cleanupIncomplete).toBe(false); + expect(result.error.secondaryFailures).toEqual([]); + } + expect(createdRootPath).toBeDefined(); + expect(existsSync(createdRootPath!)).toBe(false); + } finally { + creating.mockRestore(); + vi.useRealTimers(); + await provider.close(); + } +}); + it("rolls back a tree acquired during failed publication setup without publishing", async () => { const { imagePath, directory } = await writeTestImage(); const provider = new UefiAnalysisProvider(); diff --git a/src/uefi/UefiAnalysisProvider.ts b/src/uefi/UefiAnalysisProvider.ts index c91758d910..9fc40fd8ce 100644 --- a/src/uefi/UefiAnalysisProvider.ts +++ b/src/uefi/UefiAnalysisProvider.ts @@ -3,17 +3,12 @@ import type { UefiDecodeFormat } from "./FfsSections.js"; import { sha256Hex } from "../kernel/sha256Hex.js"; import { hostRangeErrorKind } from "../domain/parseFailure.js"; import { errorMessage } from "../kernel/errorMessage.js"; -import { randomUUID } from "node:crypto"; -import { writeFile } from "node:fs/promises"; import { inflate } from "node:zlib"; import { promisify } from "node:util"; -import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { ArtifactResourceScope, readStableArtifact, - AnalysisCleanupLease, - AnalysisCleanupLeaseGroup, } from "../resources/index.js"; import { createAnalysisExecution, @@ -29,7 +24,6 @@ import { AnalysisTimeoutError, } from "../domain/analysisErrorCore.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; -import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { Result } from "../domain/result.js"; @@ -41,15 +35,6 @@ import { type UefiNvramInspectResult, type UefiRequest, } from "../domain/uefi/uefiFirmwareAnalysis.js"; -import { - OwnedCommandFailure, - runOwnedCommand, -} from "../process/OwnedCommand.js"; -import { - processInspectionFailure, - retainProcessInspectionCleanup, -} from "../providers/OwnedCommandCleanup.js"; -import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import type { UefiImageScanSummary, UefiDecodeResult, @@ -63,8 +48,7 @@ import { publishUefiFiles, type UefiPublicationEntry, } from "./UefiPublication.js"; - -import { lzmaReplySchema } from "./UefiLzmaProtocol.js"; +import { UefiLzmaSession } from "./UefiLzmaSession.js"; import { UEFI_PROVIDER_IDENTITY } from "./UefiProviderIdentity.js"; const inflateBounded = promisify(inflate); @@ -137,6 +121,9 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { #tail: Promise = Promise.resolve(); readonly #resources = new ArtifactResourceScope(); readonly #workerModulePath: string; + #lastScan: + | { readonly key: string; readonly summary: UefiImageScanSummary } + | undefined; constructor( workerModulePath: string = fileURLToPath( @@ -161,6 +148,7 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { async close(): Promise { this.#closing = true; await this.#tail.catch(() => undefined); + this.#lastScan = undefined; await this.#resources.close(); } @@ -305,19 +293,27 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { signal: AbortSignal, checkpoint: () => void, ): Promise { + const retainObservation = ( + failure: AnalysisError, + value: AnalysisExecution, + ): AnalysisError => + failure.retainPartialObservation({ + kind: "uefi", + result: value.result, + provenance: jsonValueSchema.parse(value.subject), + }); const finishObservation = (value: AnalysisExecution): AnalysisExecution => { try { checkpoint(); return value; } catch (cause: unknown) { - throw classifyProviderFailure( - cause, - uefiFailureDialect(request.operation, request.input.path), - ).retainPartialObservation({ - kind: "uefi", - result: value.result, - provenance: jsonValueSchema.parse(value.subject), - }); + throw retainObservation( + classifyProviderFailure( + cause, + uefiFailureDialect(request.operation, request.input.path), + ), + value, + ); } }; return this.#resources.run(async () => { @@ -339,25 +335,83 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { ); return finishObservation(value); } - const scan = await scanUefiImage( - snapshot.bytes, - { - maxDepth: request.input.max_depth, - maxVolumes: request.input.max_volumes, - maxFiles: request.input.max_files, - }, - ({ payload, format, maxOutputBytes }) => - this.#decodeStream( - request.operation, - payload, - format, - maxOutputBytes, - signal, - ), - checkpoint, - ); - checkpoint(); + const scanKey = `${snapshot.sha256}:${String(request.input.max_depth)}:${String(request.input.max_volumes)}:${String(request.input.max_files)}`; + let scan: UefiImageScanSummary; + let completedInspection: AnalysisExecution | undefined; + if (this.#lastScan?.key === scanKey) { + scan = this.#lastScan.summary; + } else { + const lzmaSession = new UefiLzmaSession( + this.#workerModulePath, + request.operation, + this.#resources, + ); + try { + scan = await scanUefiImage( + snapshot.bytes, + { + maxDepth: request.input.max_depth, + maxVolumes: request.input.max_volumes, + maxFiles: request.input.max_files, + }, + ({ payload, format, maxOutputBytes }) => + this.#decodeStream( + lzmaSession, + payload, + format, + maxOutputBytes, + signal, + ), + checkpoint, + ); + } catch (cause: unknown) { + const primary = classifyProviderFailure( + cause, + uefiFailureDialect(request.operation, request.input.path), + ); + await lzmaSession.close(primary); + throw primary; + } + this.#lastScan = { key: scanKey, summary: scan }; + if (request.operation === "inspect_uefi_firmware") { + completedInspection = this.#inspect(request, snapshot.sha256, scan); + } + try { + await lzmaSession.close(); + } catch (cause: unknown) { + let cleanupFailure = classifyProviderFailure( + cause, + uefiFailureDialect(request.operation, request.input.path), + ); + let interruption: AnalysisError | undefined; + try { + checkpoint(); + } catch (abortCause: unknown) { + interruption = classifyProviderFailure( + abortCause, + uefiFailureDialect(request.operation, request.input.path), + ); + } + if (interruption !== undefined) { + if (completedInspection !== undefined) { + interruption = retainObservation( + interruption, + completedInspection, + ); + } + cleanupFailure = analysisErrorWithCleanupDependencies( + interruption, + cleanupFailure, + request.operation, + ); + } + throw completedInspection === undefined + ? cleanupFailure + : retainObservation(cleanupFailure, completedInspection); + } + } if (request.operation === "extract_uefi_firmware") { + checkpoint(); return this.#extract( request, snapshot.sha256, @@ -366,7 +420,9 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { checkpoint, ); } - return finishObservation(this.#inspect(request, snapshot.sha256, scan)); + return finishObservation( + completedInspection ?? this.#inspect(request, snapshot.sha256, scan), + ); }); } @@ -715,7 +771,7 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { } async #decodeStream( - operation: UefiRequest["operation"], + lzmaSession: UefiLzmaSession, payload: Buffer, format: UefiDecodeFormat, maxOutputBytes: number, @@ -755,177 +811,6 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { }; } } - const root = await PrivateRuntimeRoot.create({ prefix: "rea-uefi-lzma-" }); - const files = new ArtifactResourceScope(); - let worker: OwnedCommandFailure | undefined; - const rootLease = AnalysisCleanupLease.forCloseOwner( - { - async close() { - if (worker?.cleanupOwner !== undefined) { - const stopped = await worker.cleanupOwner.stop(); - if (stopped.status === "incomplete") - throw new Error(stopped.reason); - worker = undefined; - } - await files.close(); - await root.close(); - }, - get cleanupResources() { - return [ - ...new Set([ - ...(worker?.resources ?? []), - ...files.cleanupResources, - root.path, - ]), - ]; - }, - }, - root.path, - ); - const workspace = { - kind: "lease", - resource: root.path, - lease: rootLease, - } as const; - const decode = async (): Promise => { - const payloadPath = join(root.path, "payload.bin"); - const outputPath = join(root.path, "output.bin"); - const replyPath = join(root.path, "reply.json"); - const requestPath = join(root.path, "request.json"); - await writeFile(payloadPath, payload, { flag: "wx", mode: 0o600 }); - await writeFile( - requestPath, - JSON.stringify({ - format, - payload_path: payloadPath, - output_path: outputPath, - reply_path: replyPath, - max_output_bytes: maxOutputBytes, - }), - { flag: "wx", mode: 0o600 }, - ); - const { NODE_OPTIONS: _ambientNodeOptions, ...environment } = process.env; - await runOwnedCommand( - { - command: process.execPath, - arguments: [ - "--max-old-space-size=256", - "--disable-wasm-trap-handler", - this.#workerModulePath, - requestPath, - ], - cwd: root.path, - expectedCommand: null, - runId: `rea-uefi-lzma-${randomUUID()}`, - hostEnvironment: environment, - }, - { - timeoutMs: UEFI_FIRMWARE_LIMITS.timeoutMs, - diagnosticBytes: UEFI_FIRMWARE_LIMITS.diagnosticBytes, - }, - { signal }, - ); - const replyFile = await readStableArtifact( - replyPath, - UEFI_FIRMWARE_LIMITS.diagnosticBytes, - signal, - undefined, - files, - ); - const reply = lzmaReplySchema.parse( - JSON.parse(replyFile.bytes.toString("utf8")), - ); - if (!reply.ok) { - return reply; - } - const consumedBytes = reply.input_bytes_consumed; - if (consumedBytes > payload.length) { - return { - ok: false, - reason: "decoder", - message: `LZMA worker reported consuming ${consumedBytes} bytes from a ${payload.length}-byte input.`, - }; - } - signal.throwIfAborted(); - const decoded = await readStableArtifact( - outputPath, - maxOutputBytes, - signal, - undefined, - files, - ); - if ( - decoded.sha256 !== reply.output.sha256 || - decoded.bytes.length !== reply.output.bytes - ) { - return { - ok: false, - reason: "decoder", - message: `LZMA worker output digest mismatch (${reply.output.sha256}).`, - }; - } - return { - ok: true, - outcome: { - bytes: decoded.bytes, - decoderVersion: reply.lzma_version, - consumedBytes, - }, - }; - }; - - let outcome: UefiDecodeResult | undefined; - let primary: AnalysisError | undefined; - try { - outcome = await decode(); - } catch (cause: unknown) { - primary = classifyProviderFailure( - cause, - uefiFailureDialect(operation, root.path), - ); - const preparation = processInspectionFailure(cause); - if (preparation !== undefined) { - primary = retainProcessInspectionCleanup( - preparation, - primary, - this.#resources, - operation, - ); - } - if ( - cause instanceof OwnedCommandFailure && - cause.cleanupOwner !== undefined - ) { - worker = cause; - this.#resources.retain(workspace); - new AnalysisCleanupLeaseGroup(primary, [rootLease]); - throw primary; - } - } - const cleanup = (reason: string, cause?: unknown) => { - const failure = new ProviderCleanupError( - UEFI_PROVIDER_IDENTITY.id, - rootLease.cleanupResources ?? [root.path], - { reason }, - { cause, operation }, - ); - new AnalysisCleanupLeaseGroup(failure, [rootLease]); - return primary === undefined - ? failure - : analysisErrorWithCleanupDependencies(primary, failure, operation); - }; - if (files.hasPending) { - this.#resources.retain(workspace); - throw cleanup( - "Worker output descriptors must close before the temporary root can be removed.", - ); - } - const released = await this.#resources.release(workspace); - if (released.kind === "failed") - throw cleanup(errorMessage(released.cause), released.cause); - if (primary !== undefined) throw primary; - signal.throwIfAborted(); - if (outcome === undefined) throw new Error("UEFI decoder did not settle."); - return outcome; + return lzmaSession.decode(payload, format, maxOutputBytes, signal); } } diff --git a/src/uefi/UefiLzmaProtocol.ts b/src/uefi/UefiLzmaProtocol.ts index 4cab6d99e2..63b45e1584 100644 --- a/src/uefi/UefiLzmaProtocol.ts +++ b/src/uefi/UefiLzmaProtocol.ts @@ -1,3 +1,4 @@ +import { Buffer } from "node:buffer"; import { z } from "zod"; import { digestSchema } from "../domain/digests.js"; @@ -6,6 +7,19 @@ import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; const decodeFailureReasonSchema = z.enum(["format", "decoder", "output-limit"]); export type UefiDecodeFailureReason = z.infer; +export const LZMA_FRAME_HEADER_BYTES = 8; + +export const lzmaStreamRequestSchema = z.strictObject({ + format: z.enum(["lzma", "lzmaf86"]), + max_output_bytes: z + .number() + .int() + .min(1) + .max(UEFI_FIRMWARE_LIMITS.lzmaOutputBytes), +}); + +export type UefiLzmaStreamRequest = z.infer; + export const lzmaRequestSchema = z.strictObject({ format: z.enum(["lzma", "lzmaf86"]), payload_path: z.string(), @@ -40,3 +54,21 @@ export const lzmaReplySchema = z.discriminatedUnion("ok", [ ]); export type UefiLzmaReply = z.infer; + +/** Encode `[u32BE jsonBytes][u32BE bodyBytes][jsonUtf8][body]` for framed stdio IPC. */ +export const encodeLzmaFrame = ( + headerJson: string, + body: Buffer = Buffer.alloc(0), +): Buffer => { + const jsonBuf = Buffer.from(headerJson, "utf8"); + const frame = Buffer.allocUnsafe( + LZMA_FRAME_HEADER_BYTES + jsonBuf.length + body.length, + ); + frame.writeUInt32BE(jsonBuf.length, 0); + frame.writeUInt32BE(body.length, 4); + jsonBuf.copy(frame, LZMA_FRAME_HEADER_BYTES); + if (body.length > 0) { + body.copy(frame, LZMA_FRAME_HEADER_BYTES + jsonBuf.length); + } + return frame; +}; diff --git a/src/uefi/UefiLzmaSession.ts b/src/uefi/UefiLzmaSession.ts new file mode 100644 index 0000000000..7688206aff --- /dev/null +++ b/src/uefi/UefiLzmaSession.ts @@ -0,0 +1,585 @@ +import { Buffer } from "node:buffer"; +import { randomUUID } from "node:crypto"; +import type { Readable, Writable } from "node:stream"; +import { BinaryReader } from "../domain/binaryContainer.js"; +import { AnalysisError } from "../domain/analysisErrorBase.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; +import { AnalysisTimeoutError } from "../domain/analysisErrorCore.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; +import type { UefiOperation } from "../domain/uefi/uefiFirmwareAnalysis.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; +import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js"; +import { + OwnedCommandFailure, + ownedCommandResources, + prepareOwnedCommand, + throwCommandPreparationFailure, +} from "../process/OwnedCommand.js"; +import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; +import { + type ProviderProcessSnapshot, + ProviderProcessSupervisor, + spawnOwnedProviderProcess, +} from "../process/ProviderProcess.js"; +import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; +import { + processInspectionFailure, + retainArtifactCommandCleanup, + retainProcessInspectionCleanup, +} from "../providers/OwnedCommandCleanup.js"; +import type { ProcessInspectionFailure } from "../process/ProcessInspectionCleanup.js"; +import { + AnalysisCleanupLease, + AnalysisCleanupLeaseGroup, + type ArtifactResourceScope, +} from "../resources/index.js"; +import type { UefiDecodeFormat } from "./FfsSections.js"; +import { uefiFailureDialect } from "./UefiFailures.js"; +import type { UefiDecodeResult } from "./UefiImageScan.js"; +import { + encodeLzmaFrame, + LZMA_FRAME_HEADER_BYTES, + lzmaReplySchema, +} from "./UefiLzmaProtocol.js"; +import { UEFI_PROVIDER_IDENTITY } from "./UefiProviderIdentity.js"; + +const workerAbortFailure = ( + signal: AbortSignal, + snapshot: ProviderProcessSnapshot | null = null, +): unknown => + signal.reason instanceof AnalysisError + ? signal.reason + : new OwnedCommandFailure( + "cancelled", + "Command cancelled.", + snapshot, + null, + { + cancellation: { reason: signal.reason }, + }, + ); + +const throwIfWorkerAborted = ( + signal: AbortSignal, + snapshot: ProviderProcessSnapshot | null = null, +): void => { + if (signal.aborted) { + throw workerAbortFailure(signal, snapshot); + } +}; + +class ActiveWorkerReader { + #chunks: Buffer[] = []; + #buffered = 0; + #ended = false; + #error: Error | undefined; + #waiter: (() => void) | undefined; + + constructor( + private readonly stdout: Readable, + private readonly supervisor: ProviderProcessSupervisor, + ) { + stdout.on("data", this.#onData); + stdout.once("end", this.#onEnd); + stdout.once("error", this.#onError); + } + + readonly #onData = (chunk: Buffer): void => { + if (chunk.length === 0) return; + this.#chunks.push(chunk); + this.#buffered += chunk.length; + this.#wake(); + }; + + readonly #onEnd = (): void => { + this.#ended = true; + this.#wake(); + }; + + readonly #onError = (cause: Error): void => { + this.#error = cause; + this.#wake(); + }; + + #wake(): void { + const wake = this.#waiter; + this.#waiter = undefined; + wake?.(); + } + + dispose(): void { + this.stdout.off("data", this.#onData); + this.stdout.off("end", this.#onEnd); + this.stdout.off("error", this.#onError); + this.#wake(); + } + + async readExact(length: number, signal: AbortSignal): Promise { + if (length === 0) return Buffer.alloc(0); + while (this.#buffered < length) { + throwIfWorkerAborted(signal, this.supervisor.snapshot()); + if (this.#error !== undefined) { + throw new OwnedCommandFailure( + "process", + `LZMA worker stdout failed: ${this.#error.message}`, + this.supervisor.snapshot(), + null, + { processError: this.#error }, + ); + } + if (this.#ended || this.supervisor.observedExit() !== undefined) { + const snap = this.supervisor.snapshot(); + const detail = snap.stderr.text.trim(); + throw new OwnedCommandFailure( + "process", + detail.length > 0 + ? `LZMA worker exited before completing reply: ${detail}` + : "LZMA worker exited before completing reply.", + snap, + ); + } + await new Promise((resolve, reject) => { + const onAbort = () => { + this.#waiter = undefined; + reject(workerAbortFailure(signal, this.supervisor.snapshot())); + }; + if (signal.aborted) { + onAbort(); + return; + } + signal.addEventListener("abort", onAbort, { once: true }); + this.#waiter = () => { + signal.removeEventListener("abort", onAbort); + resolve(); + }; + }); + } + const out = Buffer.allocUnsafe(length); + let copied = 0; + while (copied < length) { + const head = this.#chunks[0]!; + const take = Math.min(head.length, length - copied); + head.copy(out, copied, 0, take); + copied += take; + this.#buffered -= take; + if (take === head.length) { + this.#chunks.shift(); + } else { + this.#chunks[0] = head.subarray(take); + } + } + return out; + } +} + +class ActiveWorkerStdin { + #error: Error | undefined; + + constructor( + private readonly stdin: Writable, + private readonly supervisor: ProviderProcessSupervisor, + ) { + stdin.on("error", this.#onError); + } + + readonly #onError = (cause: Error): void => { + this.#error ??= cause; + }; + + end(): void { + if (!this.stdin.destroyed && !this.stdin.writableEnded) { + try { + this.stdin.end(); + } catch { + // Closing stdin is a cooperative EOF hint before supervisor.stop() enforces exit. + } + } + } + + async writeFrame(frame: Buffer, signal: AbortSignal): Promise { + throwIfWorkerAborted(signal, this.supervisor.snapshot()); + if (this.#error !== undefined) { + throw this.#processFailure(this.#error); + } + await new Promise((resolve, reject) => { + let settled = false; + const finish = (outcome: () => void): void => { + if (settled) return; + settled = true; + signal.removeEventListener("abort", onAbort); + this.stdin.off("error", onStreamError); + this.stdin.off("close", onStreamClose); + outcome(); + }; + const onAbort = (): void => { + finish(() => + reject(workerAbortFailure(signal, this.supervisor.snapshot())), + ); + }; + const onStreamError = (cause: Error): void => { + finish(() => reject(this.#processFailure(cause))); + }; + const onStreamClose = (): void => { + const cause = this.#error; + finish(() => + reject( + cause !== undefined + ? this.#processFailure(cause) + : new OwnedCommandFailure( + "process", + "LZMA worker closed stdin before completing request write.", + this.supervisor.snapshot(), + ), + ), + ); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.stdin.once("error", onStreamError); + this.stdin.once("close", onStreamClose); + this.stdin.write(frame, (err) => { + if (err != null) { + finish(() => reject(this.#processFailure(err))); + return; + } + finish(() => resolve()); + }); + }); + } + + #processFailure(cause: Error): OwnedCommandFailure { + return new OwnedCommandFailure( + "process", + `LZMA worker stdin failed: ${cause.message}`, + this.supervisor.snapshot(), + null, + { processError: cause }, + ); + } +} + +interface ActiveLzmaWorker { + readonly root: PrivateRuntimeRoot; + readonly rootLease: AnalysisCleanupLease; + readonly workspace: { + readonly kind: "lease"; + readonly resource: string; + readonly lease: AnalysisCleanupLease; + }; + supervisor: ProviderProcessSupervisor | undefined; + readonly stdinWriter: ActiveWorkerStdin; + readonly reader: ActiveWorkerReader; + readonly resources: readonly string[]; +} + +/** + * Per-scan bounded LZMA worker session. Spawns at most one isolated Node child + * inside one `PrivateRuntimeRoot`, streams multiple compressed UEFI sections + * over length-prefixed stdio frames, and stops the child before removing its + * workspace root. + */ +export class UefiLzmaSession { + #active: ActiveLzmaWorker | undefined; + + constructor( + private readonly workerModulePath: string, + private readonly operation: UefiOperation, + private readonly resources: ArtifactResourceScope, + ) {} + + async decode( + payload: Buffer, + format: Exclude, + maxOutputBytes: number, + signal: AbortSignal, + ): Promise { + throwIfWorkerAborted(signal); + let active: ActiveLzmaWorker; + try { + active = await this.#ensureWorker(signal); + } catch (cause: unknown) { + const primary = classifyProviderFailure( + cause, + uefiFailureDialect(this.operation, this.workerModulePath), + ); + const preparation = processInspectionFailure(cause); + throw preparation === undefined + ? primary + : this.#retainInspectionCleanup(preparation, primary); + } + + try { + const requestHeader = JSON.stringify({ + format, + max_output_bytes: maxOutputBytes, + }); + await active.stdinWriter.writeFrame( + encodeLzmaFrame(requestHeader, payload), + signal, + ); + const header = await active.reader.readExact( + LZMA_FRAME_HEADER_BYTES, + signal, + ); + const headerReader = new BinaryReader(header, false, "LZMA-Frame"); + const replyBytes = headerReader.u32(0); + const outputBytes = headerReader.u32(4); + if ( + replyBytes === 0 || + replyBytes > UEFI_FIRMWARE_LIMITS.diagnosticBytes + ) { + await this.close(); + return { + ok: false, + reason: "decoder", + message: "LZMA reply exceeds the diagnostic budget.", + }; + } + if (outputBytes > maxOutputBytes) { + await this.close(); + return { + ok: false, + reason: "output-limit", + message: `LZMA worker output (${outputBytes} bytes) exceeds ${maxOutputBytes} byte budget.`, + }; + } + const replyJsonBuf = await active.reader.readExact(replyBytes, signal); + const decodedBytes = await active.reader.readExact(outputBytes, signal); + const reply = lzmaReplySchema.parse( + JSON.parse(replyJsonBuf.toString("utf8")), + ); + if (!reply.ok) { + return reply; + } + if (reply.input_bytes_consumed > payload.length) { + return { + ok: false, + reason: "decoder", + message: `LZMA worker reported consuming ${reply.input_bytes_consumed} bytes from a ${payload.length}-byte input.`, + }; + } + if ( + decodedBytes.length !== reply.output.bytes || + sha256Hex(decodedBytes) !== reply.output.sha256 + ) { + return { + ok: false, + reason: "decoder", + message: `LZMA worker output digest mismatch (${reply.output.sha256}).`, + }; + } + throwIfWorkerAborted(signal, active.supervisor?.snapshot() ?? null); + return { + ok: true, + outcome: { + bytes: decodedBytes, + decoderVersion: reply.lzma_version, + consumedBytes: reply.input_bytes_consumed, + }, + }; + } catch (cause: unknown) { + let primary = classifyProviderFailure( + cause, + uefiFailureDialect(this.operation, active.root.path), + ); + const preparation = processInspectionFailure(cause); + if (preparation !== undefined) { + primary = this.#retainInspectionCleanup(preparation, primary); + } + await this.close(primary); + throw primary; + } + } + + async close(primary?: AnalysisError): Promise { + const active = this.#active; + if (active === undefined) return; + this.#active = undefined; + active.reader.dispose(); + active.stdinWriter.end(); + const released = await this.resources.release(active.workspace); + if (released.kind === "failed") { + const failure = new ProviderCleanupError( + UEFI_PROVIDER_IDENTITY.id, + active.rootLease.cleanupResources ?? [active.root.path], + { reason: errorMessage(released.cause) }, + { cause: released.cause, operation: this.operation }, + ); + new AnalysisCleanupLeaseGroup(failure, [active.rootLease]); + throw primary === undefined + ? failure + : analysisErrorWithCleanupDependencies( + primary, + failure, + this.operation, + ); + } + } + + async #ensureWorker(signal: AbortSignal): Promise { + if ( + this.#active !== undefined && + this.#active.supervisor?.observedExit() === undefined + ) { + return this.#active; + } + if (this.#active !== undefined) { + await this.close(); + } + await prepareOwnedCommand(signal); + const root = await PrivateRuntimeRoot.create({ prefix: "rea-uefi-lzma-" }); + let supervisor: ProviderProcessSupervisor | undefined; + let processResources: readonly string[] = []; + const rootLease = AnalysisCleanupLease.forCloseOwner( + { + async close() { + if (supervisor !== undefined) { + const stopped = await supervisor.stop(); + if (stopped.status === "incomplete") { + throw new Error(stopped.reason); + } + supervisor.dispose(); + supervisor = undefined; + processResources = []; + } + await root.close(); + }, + get cleanupResources() { + return [...new Set([...processResources, root.path])]; + }, + }, + root.path, + ); + const workspace = { + kind: "lease", + resource: root.path, + lease: rootLease, + } as const; + + try { + const { NODE_OPTIONS: _ambientNodeOptions, ...environment } = process.env; + let spawned: Awaited>; + try { + spawned = await spawnOwnedProviderProcess({ + command: process.execPath, + arguments: [ + "--max-old-space-size=256", + "--disable-wasm-trap-handler", + this.workerModulePath, + "--stdio", + ], + cwd: root.path, + expectedCommand: null, + runId: `rea-uefi-lzma-${randomUUID()}`, + hostEnvironment: environment, + stdin: "pipe", + signal, + }); + } catch (cause: unknown) { + throwCommandPreparationFailure( + cause, + signal.aborted + ? signal.reason instanceof AnalysisTimeoutError + ? "timeout" + : "cancelled" + : undefined, + ); + } + processResources = ownedCommandResources(spawned.ownership, root.path); + supervisor = new ProviderProcessSupervisor( + { + process: spawned.process, + ownsProcessLifetime: true, + ownership: spawned.ownership, + ...(spawned.cleanup === undefined + ? {} + : { cleanup: spawned.cleanup }), + ...(spawned.requestStop === undefined + ? {} + : { requestStop: spawned.requestStop }), + }, + { + captureStdout: false, + maxDiagnosticBytes: UEFI_FIRMWARE_LIMITS.diagnosticBytes, + runtime: "v8", + }, + ); + const stdin = spawned.process.stdin; + const stdout = spawned.process.stdout; + if (stdin == null || stdout == null) { + throw new Error("LZMA worker stdio pipes were not established."); + } + const stdinWriter = new ActiveWorkerStdin(stdin, supervisor); + const reader = new ActiveWorkerReader(stdout, supervisor); + const active: ActiveLzmaWorker = { + root, + rootLease, + workspace, + supervisor, + stdinWriter, + reader, + resources: processResources, + }; + this.#active = active; + return active; + } catch (cause: unknown) { + let primary = classifyProviderFailure( + cause, + uefiFailureDialect(this.operation, root.path), + ); + const preparation = processInspectionFailure(cause); + if (preparation !== undefined) { + primary = this.#retainInspectionCleanup(preparation, primary); + } + const released = await this.resources.release(workspace); + if (released.kind === "failed") { + const cleanup = new ProviderCleanupError( + UEFI_PROVIDER_IDENTITY.id, + rootLease.cleanupResources ?? [root.path], + { reason: errorMessage(released.cause) }, + { cause: released.cause, operation: this.operation }, + ); + new AnalysisCleanupLeaseGroup(cleanup, [rootLease]); + throw analysisErrorWithCleanupDependencies( + primary, + cleanup, + this.operation, + ); + } + throw primary; + } + } + + #retainInspectionCleanup( + preparation: ProcessInspectionFailure, + primary: AnalysisError, + ): AnalysisError { + if (primary instanceof AnalysisTimeoutError) { + if ( + preparation instanceof DarwinProcessOwnershipInspectionError && + preparation.capturedOutput !== undefined + ) { + primary.retainCapturedOutput(preparation.capturedOutput); + } + for (const failure of retainArtifactCommandCleanup( + preparation, + this.resources, + this.operation, + )) { + primary = analysisErrorWithCleanupDependencies( + primary, + failure, + this.operation, + ); + } + return primary; + } + return retainProcessInspectionCleanup( + preparation, + primary, + this.resources, + this.operation, + ); + } +} diff --git a/src/uefi/UefiLzmaWorker.ts b/src/uefi/UefiLzmaWorker.ts index 4ce9411dbe..0adb9fc581 100644 --- a/src/uefi/UefiLzmaWorker.ts +++ b/src/uefi/UefiLzmaWorker.ts @@ -1,26 +1,44 @@ +import { Buffer } from "node:buffer"; +import { once } from "node:events"; +import { readFile, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { join } from "node:path"; +import type { Readable, Writable } from "node:stream"; +import { z } from "zod"; import { BinaryReader } from "../domain/binaryContainer.js"; -import { sha256Hex } from "../kernel/sha256Hex.js"; -import { Budget } from "../domain/budget.js"; import { decodeLimit, malformedInput, parseFailureFromCause, truncatedInput, } from "../domain/parseFailure.js"; -import { errorMessage } from "../kernel/errorMessage.js"; -import { readFile, writeFile } from "node:fs/promises"; -import { createRequire } from "node:module"; -import { join } from "node:path"; -import { z } from "zod"; -import { undoUefiX86BranchFilter } from "./UefiX86BranchFilter.js"; -import { lzmaRequestSchema, type UefiLzmaReply } from "./UefiLzmaProtocol.js"; import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; +import { + encodeLzmaFrame, + LZMA_FRAME_HEADER_BYTES, + lzmaRequestSchema, + lzmaStreamRequestSchema, + type UefiLzmaReply, +} from "./UefiLzmaProtocol.js"; +import { undoUefiX86BranchFilter } from "./UefiX86BranchFilter.js"; const LZMA_ALONE_HEADER_BYTES = 13; const LZMA_DICTIONARY_OFFSET = 1; const LZMA_MIN_DICTIONARY_BYTES = 0x1000; const LZMA_RANGE_CODER_INIT_BYTES = 5; +interface LzmaCodec { + readonly lzma: { + decompressFile( + input: { readByte(): number }, + output: { writeByte(byte: number): void }, + ): void; + }; + readonly version: string; +} + /** * Output sink that enforces the byte budget while the decoder writes, instead * of after the whole stream has expanded in memory. It grows on demand up to @@ -28,33 +46,34 @@ const LZMA_RANGE_CODER_INIT_BYTES = 5; */ class BoundedLzmaOutput { #buffer: Buffer; - readonly #budget: Budget; + #used = 0; constructor(readonly limit: number) { - this.#budget = new Budget(limit); this.#buffer = Buffer.allocUnsafe(Math.min(limit, 0x10000)); } writeByte(byte: number): void { - const position = this.#budget.used; - if (!this.#budget.tryCharge(1)) + const position = this.#used; + if (position >= this.limit) { throw decodeLimit( "LZMA", `Decompressed output exceeds the ${this.limit} byte budget.`, { name: "output_bytes", maximum: this.limit, required: position + 1 }, ); + } if (position >= this.#buffer.length) { const next = Buffer.allocUnsafe( - Math.min(this.limit, this.#buffer.length * 2), + Math.min(this.limit, Math.max(0x10000, this.#buffer.length * 2)), ); this.#buffer.copy(next, 0, 0, position); this.#buffer = next; } this.#buffer[position] = byte; + this.#used = position + 1; } getBuffer(): Buffer { - return this.#buffer.subarray(0, this.#budget.used); + return this.#buffer.subarray(0, this.#used); } } @@ -103,45 +122,44 @@ const prepareLzmaInput = (payload: Buffer, maxOutputBytes: number) => { // Normalize the worker's private input buffer before passing it to the codec. if (dictionaryBytes < LZMA_MIN_DICTIONARY_BYTES) payload.writeUInt32LE(LZMA_MIN_DICTIONARY_BYTES, LZMA_DICTIONARY_OFFSET); - return { reader, declaredOutput }; + return { declaredOutput }; }; -const main = async (): Promise => { - const requestPath = process.argv[2]; - if (requestPath === undefined) { - throw new Error("Owned worker request path missing."); - } - const request = lzmaRequestSchema.parse( - JSON.parse(await readFile(requestPath, "utf8")), +const loadLzmaCodec = async (): Promise => { + const require = createRequire(import.meta.url); + const lzma = require("lzma-purejs") as LzmaCodec["lzma"]; + const workerModulePath = require.resolve("lzma-purejs"); + const upstreamMetadata = JSON.parse( + await readFile(join(workerModulePath, "..", "package.json"), "utf8"), ); - let reply: UefiLzmaReply; - try { - const require = createRequire(import.meta.url); - const lzma = require("lzma-purejs"); - const workerModulePath = require.resolve("lzma-purejs"); - const upstreamMetadata = JSON.parse( - await readFile(join(workerModulePath, "..", "package.json"), "utf8"), - ); - const decoderVersion = z - .object({ version: z.string() }) - .parse(upstreamMetadata).version; + const version = z + .object({ version: z.string() }) + .parse(upstreamMetadata).version; + return { lzma, version }; +}; - const payload = await readFile(request.payload_path); - const { reader, declaredOutput } = prepareLzmaInput( - payload, - request.max_output_bytes, - ); - const output = new BoundedLzmaOutput(request.max_output_bytes); +const decodeStreamPayload = ( + codec: LzmaCodec, + payload: Buffer, + format: "lzma" | "lzmaf86", + maxOutputBytes: number, +): { readonly reply: UefiLzmaReply; readonly decoded?: Buffer } => { + try { + const { declaredOutput } = prepareLzmaInput(payload, maxOutputBytes); + const output = new BoundedLzmaOutput(maxOutputBytes); let position = 0; - lzma.decompressFile( + const totalLength = payload.length; + codec.lzma.decompressFile( { readByte() { - if (position === payload.length) + if (position === totalLength) throw truncatedInput( "LZMA-Alone", "Compressed stream ends before the decoder can finish.", ); - return reader.u8(position++); + const byte = payload[position]!; + position += 1; + return byte; }, }, output, @@ -153,17 +171,177 @@ const main = async (): Promise => { `LZMA decoded ${decoded.length} bytes; stream declared ${declaredOutput} bytes.`, ); } - if (request.format === "lzmaf86") undoUefiX86BranchFilter(decoded); - await writeFile(request.output_path, decoded, { flag: "wx", mode: 0o600 }); - reply = { - ok: true, - lzma_version: decoderVersion, - input_bytes_consumed: position, - output: { - sha256: sha256Hex(decoded), - bytes: decoded.length, + if (format === "lzmaf86") undoUefiX86BranchFilter(decoded); + return { + decoded, + reply: { + ok: true, + lzma_version: codec.version, + input_bytes_consumed: position, + output: { + sha256: sha256Hex(decoded), + bytes: decoded.length, + }, }, }; + } catch (cause: unknown) { + const failure = parseFailureFromCause(cause); + return { + reply: { + ok: false, + reason: + failure === undefined + ? "decoder" + : failure.kind === "limit" + ? "output-limit" + : "format", + message: errorMessage(cause), + }, + }; + } +}; + +const serializeReply = (reply: UefiLzmaReply): string => { + const encoded = JSON.stringify(reply); + if (Buffer.byteLength(encoded) <= UEFI_FIRMWARE_LIMITS.diagnosticBytes) { + return encoded; + } + const bounded: UefiLzmaReply = { + ok: false, + reason: reply.ok ? "decoder" : reply.reason, + message: "LZMA reply exceeds the diagnostic budget.", + }; + return JSON.stringify(bounded); +}; + +class FramedByteReader { + #chunks: Buffer[] = []; + #buffered = 0; + #ended = false; + #error: unknown; + #waiter: (() => void) | undefined; + + constructor(stream: Readable) { + stream.on("data", (chunk: Buffer) => { + if (chunk.length === 0) return; + this.#chunks.push(chunk); + this.#buffered += chunk.length; + const wake = this.#waiter; + this.#waiter = undefined; + wake?.(); + }); + stream.once("end", () => { + this.#ended = true; + const wake = this.#waiter; + this.#waiter = undefined; + wake?.(); + }); + stream.once("error", (cause: unknown) => { + this.#error = cause; + const wake = this.#waiter; + this.#waiter = undefined; + wake?.(); + }); + } + + async readExact( + length: number, + allowCleanEof = false, + ): Promise { + if (length === 0) return Buffer.alloc(0); + while (this.#buffered < length) { + if (this.#error !== undefined) throw this.#error; + if (this.#ended) { + if (allowCleanEof && this.#buffered === 0) return null; + throw new Error("Truncated LZMA worker frame."); + } + await new Promise((resolve) => { + this.#waiter = resolve; + }); + } + const result = Buffer.allocUnsafe(length); + let copied = 0; + while (copied < length) { + const head = this.#chunks[0]!; + const take = Math.min(head.length, length - copied); + head.copy(result, copied, 0, take); + copied += take; + this.#buffered -= take; + if (take === head.length) { + this.#chunks.shift(); + } else { + this.#chunks[0] = head.subarray(take); + } + } + return result; + } +} + +const writeFramed = async (stream: Writable, frame: Buffer): Promise => { + if (!stream.write(frame)) { + await once(stream, "drain"); + } +}; + +const runStdioWorker = async (): Promise => { + const codec = await loadLzmaCodec(); + const reader = new FramedByteReader(process.stdin); + for (;;) { + const header = await reader.readExact(LZMA_FRAME_HEADER_BYTES, true); + if (header === null) break; + const headerReader = new BinaryReader(header, false, "LZMA-Frame"); + const jsonBytes = headerReader.u32(0); + const payloadBytes = headerReader.u32(4); + if ( + jsonBytes === 0 || + jsonBytes > UEFI_FIRMWARE_LIMITS.diagnosticBytes || + payloadBytes > UEFI_FIRMWARE_LIMITS.inputBytes + ) { + throw new Error("LZMA worker request frame exceeds protocol bounds."); + } + const jsonBuf = await reader.readExact(jsonBytes); + const payload = await reader.readExact(payloadBytes); + if (jsonBuf === null || payload === null) { + throw new Error("Truncated LZMA worker request body."); + } + const request = lzmaStreamRequestSchema.parse( + JSON.parse(jsonBuf.toString("utf8")), + ); + const { reply, decoded } = decodeStreamPayload( + codec, + payload, + request.format, + request.max_output_bytes, + ); + const replyText = serializeReply(reply); + const parsedReply = JSON.parse(replyText) as UefiLzmaReply; + const body = + parsedReply.ok && decoded !== undefined ? decoded : Buffer.alloc(0); + await writeFramed(process.stdout, encodeLzmaFrame(replyText, body)); + } +}; + +const runSingleFileWorker = async (requestPath: string): Promise => { + const request = lzmaRequestSchema.parse( + JSON.parse(await readFile(requestPath, "utf8")), + ); + let reply: UefiLzmaReply; + try { + const codec = await loadLzmaCodec(); + const payload = await readFile(request.payload_path); + const outcome = decodeStreamPayload( + codec, + payload, + request.format, + request.max_output_bytes, + ); + reply = outcome.reply; + if (reply.ok && outcome.decoded !== undefined) { + await writeFile(request.output_path, outcome.decoded, { + flag: "wx", + mode: 0o600, + }); + } } catch (cause: unknown) { const failure = parseFailureFromCause(cause); reply = { @@ -177,16 +355,22 @@ const main = async (): Promise => { message: errorMessage(cause), }; } - let encoded = JSON.stringify(reply); - if (Buffer.byteLength(encoded) > UEFI_FIRMWARE_LIMITS.diagnosticBytes) { - const bounded: UefiLzmaReply = { - ok: false, - reason: reply.ok ? "decoder" : reply.reason, - message: "LZMA reply exceeds the diagnostic budget.", - }; - encoded = JSON.stringify(bounded); + await writeFile(request.reply_path, serializeReply(reply), { + flag: "wx", + mode: 0o600, + }); +}; + +const main = async (): Promise => { + const arg = process.argv[2]; + if (arg === "--stdio") { + await runStdioWorker(); + return; } - await writeFile(request.reply_path, encoded, { flag: "wx", mode: 0o600 }); + if (arg === undefined) { + throw new Error("Owned worker request path missing."); + } + await runSingleFileWorker(arg); }; await main(); diff --git a/src/uefi/UefiPublication.ts b/src/uefi/UefiPublication.ts index 974b062927..da9d4fc662 100644 --- a/src/uefi/UefiPublication.ts +++ b/src/uefi/UefiPublication.ts @@ -1,4 +1,3 @@ -import { sha256Hex } from "../kernel/sha256Hex.js"; import { join } from "node:path"; import { Readable } from "node:stream"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; @@ -61,22 +60,45 @@ export const publishUefiFiles = async (context: { try { context.checkpoint(); tree = await SafeOutputTree.create(context.outputDirectory); - for (const entry of context.entries) { - context.checkpoint(); - const sha256 = sha256Hex(entry.bytes); - const written = await tree.write( - entry.relativePath, - Readable.from([entry.bytes]), - { sha256, bytes: entry.bytes.length }, - context.signal, - ); - files.push({ - ...entry.facts, - relative_path: written.relativePath, - path: join(tree.outputRoot, written.relativePath), - size: written.bytesWritten, - sha256: written.sha256, - }); + const activeTree = tree; + const slots = new Array( + context.entries.length, + ); + let cursor = 0; + let firstFailure: unknown; + const publishWorker = async (): Promise => { + while (firstFailure === undefined) { + const index = cursor++; + const entry = context.entries[index]; + if (entry === undefined) return; + try { + context.checkpoint(); + const written = await activeTree.write( + entry.relativePath, + Readable.from([entry.bytes]), + { bytes: entry.bytes.length }, + context.signal, + ); + slots[index] = { + ...entry.facts, + relative_path: written.relativePath, + path: join(activeTree.outputRoot, written.relativePath), + size: written.bytesWritten, + sha256: written.sha256, + }; + } catch (cause: unknown) { + firstFailure ??= cause; + return; + } + } + }; + const workerCount = Math.min(8, context.entries.length); + await Promise.allSettled( + Array.from({ length: workerCount }, () => publishWorker()), + ); + if (firstFailure !== undefined) throw firstFailure; + for (const item of slots) { + if (item !== undefined) files.push(item); } result = context.buildResult(tree.outputRoot, files); context.checkpoint(); diff --git a/tests/boundary/firmware/firmwarePublicationPaths.test.ts b/tests/boundary/firmware/firmwarePublicationPaths.test.ts index 3d5573f6c8..0ae5b34035 100644 --- a/tests/boundary/firmware/firmwarePublicationPaths.test.ts +++ b/tests/boundary/firmware/firmwarePublicationPaths.test.ts @@ -27,7 +27,13 @@ import { import { publishFirmwareExtraction } from "../../../src/firmware/FirmwarePublication.js"; import { normalizeUnblobReport } from "../../../src/firmware/FirmwareReports.js"; import { startFirmwareDeadline } from "../../../src/firmware/FirmwareDeadline.js"; -import { SafeOutputTree } from "../../../src/resources/SafeOutputTree.js"; +import { AnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; +import { + AnalysisCleanupLease, + AnalysisCleanupLeaseGroup, + SafeOutputTree, +} from "../../../src/resources/index.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; @@ -266,3 +272,292 @@ it("publishes the writer's normalized path while retaining source spelling and u await files.close(); } }); + +const buildConcurrentUnblobReport = ( + inputPath: string, + staging: string, + inputHash: string, + childSpecs: readonly { + readonly relativePath: string; + readonly payload: Buffer; + readonly sha256: string; + }[], + corruptIndex?: number, +) => + normalizeUnblobReport( + [ + { + task: { + path: inputPath, + depth: 0, + blob_id: "", + is_multi_file: false, + }, + reports: [ + { + __typename__: "StatReport", + path: inputPath, + size: 16, + is_file: true, + is_dir: false, + is_link: false, + link_target: null, + }, + { __typename__: "HashReport", sha256: inputHash }, + ], + subtasks: childSpecs.map((spec, idx) => ({ + path: join(staging, spec.relativePath), + depth: 1, + blob_id: `child-${idx}`, + is_multi_file: false, + })), + }, + ...childSpecs.map((spec, idx) => ({ + task: { + path: join(staging, spec.relativePath), + depth: 1, + blob_id: `child-${idx}`, + is_multi_file: false, + }, + reports: [ + { + __typename__: "StatReport", + path: join(staging, spec.relativePath), + size: spec.payload.length, + is_file: true, + is_dir: false, + is_link: false, + link_target: null, + }, + { + __typename__: "HashReport", + sha256: idx === corruptIndex ? "0".repeat(64) : spec.sha256, + }, + ], + subtasks: [], + })), + ], + { + inputPath, + outputRoot: staging, + sha256: inputHash, + length: 16, + offset: 0, + maxDepth: 3, + }, + ); + +const SYNTHETIC_UNBLOB_ENGINE = (executableSha256: string) => ({ + name: "unblob" as const, + version: "26.6.4", + executable_path: "/synthetic/unblob", + executable_sha256: executableSha256, + source_revision: null, + worker_count: 1 as const, +}); + +it("publishes nested regular files concurrently in deterministic order without double-hashing and rolls back reported digest mismatches", async () => { + const root = await createTestTempDirectory("rea-firmware-concurrent-pub-"); + const staging = join(root, "staging"); + await mkdir(join(staging, "rootfs", "bin"), { recursive: true }); + await mkdir(join(staging, "rootfs", "etc", "conf.d"), { recursive: true }); + + const inputPath = join(root, "input.img"); + const inputHash = "b".repeat(64); + const childSpecs = Array.from({ length: 24 }, (_, idx) => { + const subdir = idx % 2 === 0 ? "rootfs/bin" : "rootfs/etc/conf.d"; + const relativePath = `${subdir}/item-${String(idx).padStart(2, "0")}.bin`; + const payload = Buffer.from(`payload-${idx}-${"x".repeat(64)}`); + const sha256 = createHash("sha256").update(payload).digest("hex"); + return { relativePath, payload, sha256 }; + }); + for (const spec of childSpecs) { + await writeFile(join(staging, spec.relativePath), spec.payload); + } + + const entries = await inventoryFirmwareOutput( + staging, + 65_536, + 256, + Number.MAX_SAFE_INTEGER, + "extract_firmware", + ); + const files = new FirmwareFileAccess(); + const hashSpy = vi.spyOn(files, "hash"); + const outputOk = join(root, "published-ok"); + const outputBad = join(root, "published-bad"); + try { + const published = await publishFirmwareExtraction({ + files, + workspacePath: root, + deadline: startFirmwareDeadline("publication", 120_000), + analysisTimeoutMs: 120_000, + outputDirectory: outputOk, + entries, + normalized: buildConcurrentUnblobReport( + inputPath, + staging, + inputHash, + childSpecs, + ), + selection: { offset: 0, length: 16, sha256: inputHash }, + maxDepth: 3, + engine: SYNTHETIC_UNBLOB_ENGINE(inputHash), + signal: new AbortController().signal, + retainCleanup: vi.fn(), + }); + expect(hashSpy).not.toHaveBeenCalled(); + const expectedSorted = [...childSpecs].sort((a, b) => + a.relativePath < b.relativePath + ? -1 + : a.relativePath > b.relativePath + ? 1 + : 0, + ); + expect(published.files.map((file) => file.relative_path)).toEqual( + expectedSorted.map((spec) => spec.relativePath), + ); + expect(published.files.map((file) => file.sha256)).toEqual( + expectedSorted.map((spec) => spec.sha256), + ); + + await expect( + publishFirmwareExtraction({ + files, + workspacePath: root, + deadline: startFirmwareDeadline("publication", 120_000), + analysisTimeoutMs: 120_000, + outputDirectory: outputBad, + entries, + normalized: buildConcurrentUnblobReport( + inputPath, + staging, + inputHash, + childSpecs, + 11, + ), + selection: { offset: 0, length: 16, sha256: inputHash }, + maxDepth: 3, + engine: SYNTHETIC_UNBLOB_ENGINE(inputHash), + signal: new AbortController().signal, + retainCleanup: vi.fn(), + }), + ).rejects.toMatchObject({ + _tag: "AnalysisOutputError", + message: expect.stringContaining( + "Extracted bytes disagree with provider report", + ), + }); + await expect(access(outputBad)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + await files.close(); + } +}); + +it("retains incomplete cleanup leases from every concurrent publication worker", async () => { + const root = await createTestTempDirectory("rea-firmware-concurrent-leases-"); + const staging = join(root, "staging"); + await mkdir(staging); + const inputPath = join(root, "input.img"); + const inputHash = "d".repeat(64); + const childSpecs = [0, 1, 2].map((idx) => { + const relativePath = `item-${idx}.bin`; + const payload = Buffer.from(`payload-${idx}`); + const sha256 = createHash("sha256").update(payload).digest("hex"); + return { relativePath, payload, sha256 }; + }); + for (const spec of childSpecs) { + await writeFile(join(staging, spec.relativePath), spec.payload); + } + + const entries = await inventoryFirmwareOutput( + staging, + 65_536, + 256, + Number.MAX_SAFE_INTEGER, + "extract_firmware", + ); + let canCloseFirst = false; + let canCloseSecond = false; + const leaseFirst = new AnalysisCleanupLease(async () => { + if (!canCloseFirst) throw new Error("first descriptor still busy"); + }, [join(staging, "item-0.bin")]); + const leaseSecond = new AnalysisCleanupLease(async () => { + if (!canCloseSecond) throw new Error("second descriptor still busy"); + }, [join(staging, "item-1.bin")]); + const files = new FirmwareFileAccess(); + let started = 0; + let releaseBarrier: (() => void) | undefined; + const barrier = new Promise((resolve) => { + releaseBarrier = resolve; + }); + vi.spyOn(files, "publish").mockImplementation(async (entry) => { + started += 1; + if (started >= 3) releaseBarrier?.(); + await barrier; + if (entry.relativePath === "item-0.bin") { + const err = new ProviderCleanupError( + "unblob", + [join(staging, "item-0.bin")], + { reason: "first source close failed" }, + { operation: "extract_firmware" }, + ); + new AnalysisCleanupLeaseGroup(err, [leaseFirst]); + throw err; + } + if (entry.relativePath === "item-1.bin") { + const err = new ProviderCleanupError( + "unblob", + [join(staging, "item-1.bin")], + { reason: "second source close failed" }, + { operation: "extract_firmware" }, + ); + new AnalysisCleanupLeaseGroup(err, [leaseSecond]); + throw err; + } + throw new Error("ordinary sibling failure"); + }); + + try { + const caught = await publishFirmwareExtraction({ + files, + workspacePath: root, + deadline: startFirmwareDeadline("publication", 120_000), + analysisTimeoutMs: 120_000, + outputDirectory: join(root, "out"), + entries, + normalized: buildConcurrentUnblobReport( + inputPath, + staging, + inputHash, + childSpecs, + ), + selection: { offset: 0, length: 16, sha256: inputHash }, + maxDepth: 3, + engine: SYNTHETIC_UNBLOB_ENGINE(inputHash), + signal: new AbortController().signal, + retainCleanup: vi.fn(), + }).catch((cause: unknown) => cause); + + expect(caught).toBeInstanceOf(AnalysisError); + if (!(caught instanceof AnalysisError)) return; + expect(caught.cleanupIncomplete).toBe(true); + expect(caught.cleanupResources).toEqual( + expect.arrayContaining([ + join(staging, "item-0.bin"), + join(staging, "item-1.bin"), + ]), + ); + + canCloseFirst = true; + await leaseFirst.release(); + expect(caught.cleanupIncomplete).toBe(true); + expect(caught.cleanupResources).toContain(join(staging, "item-1.bin")); + + canCloseSecond = true; + await leaseSecond.release(); + expect(caught.cleanupIncomplete).toBe(false); + } finally { + await files.close(); + } +}); diff --git a/tests/process-global/firmwareFileLifetime.test.ts b/tests/process-global/firmwareFileLifetime.test.ts index 10cc70018e..fca69809a9 100644 --- a/tests/process-global/firmwareFileLifetime.test.ts +++ b/tests/process-global/firmwareFileLifetime.test.ts @@ -997,14 +997,7 @@ it.each(["source-first", "tree-first"])( const path = join(fixture.context.workspacePath, "payload.bin"); const bytes = Buffer.from("published bytes"); await writeFile(path, bytes); - const hash = fixture.context.files.hash.bind(fixture.context.files); - vi.spyOn(fixture.context.files, "hash").mockImplementation( - async (...args) => { - const digest = await hash(...args); - fault.selected = "payload.bin"; - return digest; - }, - ); + fault.selected = "payload.bin"; const error = await publishFirmwareExtraction({ ...fixture.context, entries: [ diff --git a/tests/support/providerLifecycleCoverage.ts b/tests/support/providerLifecycleCoverage.ts index 7a89fc32bb..033b2db98d 100644 --- a/tests/support/providerLifecycleCoverage.ts +++ b/tests/support/providerLifecycleCoverage.ts @@ -2028,7 +2028,9 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< "decodes an LZMA-custom section through the owned worker and derives it", ), ), - handshake: ONE_SHOT, + handshake: notApplicable( + "The decoder child writes one framed reply per request; there is no handshake.", + ), operation: covered( test( "tests/acceptance/uefiFirmware.test.ts", @@ -2044,13 +2046,13 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< cleanup: covered( test( UEFI_PROVIDER, - "retains the worker root across a failed descriptor retry and releases its child before root removal", + "retains the worker root across a failed child stop retry and stops its child before root removal", ), ), retry: covered( test( UEFI_PROVIDER, - "retains the worker root across a failed descriptor retry and releases its child before root removal", + "retains the worker root across a failed child stop retry and stops its child before root removal", ), ), },