diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index b47bf621a..e23834f63 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -259,6 +259,22 @@ const throwIfTargetResolutionCancelled = (signal?: AbortSignal): void => { throw new AnalysisCancelledError("resolve_binary_target"); }; +/** Preserve cancellation when an asynchronous identity check succeeds or rejects. */ +const verifyTargetState = async ( + path: string, + handle: FileHandle, + initial: Stats, + signal?: AbortSignal, +): Promise => { + try { + await verifyRegularFileState(path, { handle, initial }); + } catch (cause: unknown) { + throwIfTargetResolutionCancelled(signal); + throw cause; + } + throwIfTargetResolutionCancelled(signal); +}; + const detectArtifactFormat = async ( path: string, handle: FileHandle, @@ -283,8 +299,7 @@ const detectArtifactFormat = async ( const magic = Buffer.alloc(16); const observed = await handle.read(magic, 0, magic.length, 0); throwIfTargetResolutionCancelled(signal); - await verifyRegularFileState(path, { handle, initial }); - throwIfTargetResolutionCancelled(signal); + await verifyTargetState(path, handle, initial, signal); if ( observed.bytesRead >= 8 && magic.subarray(0, 8).equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])) @@ -389,7 +404,7 @@ const sha256Handle = async ( throw new BinaryTargetError(path, "target grew while being read"); } throwIfTargetResolutionCancelled(signal); - await verifyRegularFileState(path, { handle, initial }); + await verifyTargetState(path, handle, initial, signal); if (position !== initial.size) throw new BinaryTargetError(path, "target changed while being read"); return hash.digest("hex"); diff --git a/src/artifacts/InesArtifactReader.ts b/src/artifacts/InesArtifactReader.ts index df5618694..d7460aa18 100644 --- a/src/artifacts/InesArtifactReader.ts +++ b/src/artifacts/InesArtifactReader.ts @@ -41,12 +41,12 @@ export class InesArtifactReader implements ArtifactReader { async *entries(signal?: AbortSignal): AsyncIterable { abortIfNeeded(signal); - await this.#verifySource(); + await this.#verifySource(signal); const prefix = Buffer.alloc(16); const { bytesRead } = await this.source.handle.read(prefix, 0, 16, 0); abortIfNeeded(signal); // Concurrent source changes take precedence over malformed header diagnostics. - await this.#verifySource(); + await this.#verifySource(signal); const parsed = parseInesLayout( prefix.subarray(0, bytesRead), this.source.initial.size, @@ -82,7 +82,7 @@ export class InesArtifactReader implements ArtifactReader { "integrity", "iNES region does not match this reader's inventory", ); - await this.#verifySource(); + await this.#verifySource(signal); const offset = produced.byteOffset; const size = produced.declaredSize; if (offset === null || size === null || size <= 0) @@ -92,7 +92,7 @@ export class InesArtifactReader implements ArtifactReader { end: offset + size - 1, signal, }); - const verify = () => this.#verifySource(); + const verify = () => this.#verifySource(signal); return Readable.from( (async function* () { let bytes = 0; @@ -126,6 +126,7 @@ export class InesArtifactReader implements ArtifactReader { expectedSha256: string, signal?: AbortSignal, ): Promise { + abortIfNeeded(signal); const layout = this.#layout; if (layout === undefined || this.#entries.size !== layout.regions.length) throw new ArtifactReaderFailure("integrity", "Incomplete iNES inventory"); @@ -146,6 +147,7 @@ export class InesArtifactReader implements ArtifactReader { bytes += chunk.length; } } + abortIfNeeded(signal); const sha256 = hash.digest("hex"); if (bytes !== this.source.initial.size || sha256 !== expectedSha256) throw new ArtifactReaderFailure( @@ -174,12 +176,14 @@ export class InesArtifactReader implements ArtifactReader { return this.ownedSource?.close() ?? Promise.resolve(); } - async #verifySource(): Promise { + async #verifySource(signal?: AbortSignal): Promise { + abortIfNeeded(signal); if (this.#closed) throw new ArtifactReaderFailure("unavailable", "iNES reader is closed"); try { await verifyRegularFileState(this.path, this.source); } catch (cause: unknown) { + abortIfNeeded(signal); if (cause instanceof RegularFileChangedError) throw new ArtifactReaderFailure( "integrity", @@ -188,5 +192,7 @@ export class InesArtifactReader implements ArtifactReader { ); throw cause; } + // State validation is asynchronous even after the final byte was consumed. + abortIfNeeded(signal); } } diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index ed7f6e786..f4a860570 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -13,7 +13,10 @@ import { nesContainerFormat, parseInesLayout, } from "../../domain/inesContainer.js"; -import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js"; +import { + abortIfNeeded, + ARTIFACT_CLASSIFICATION_PREFIX_BYTES, +} from "../ArtifactHash.js"; import type { ArtifactOccurrence } from "../../domain/artifactGraph.js"; import { hasZipSignature, @@ -107,12 +110,18 @@ export const classifyAndHashRootForInventory = async ( | { readonly kind: "failed"; readonly cause: unknown }; try { const initial = await handle.stat(); + abortIfNeeded(options.signal); if (!sameRegularFileState(expectedMetadata, initial)) throw new ArtifactReaderFailure( "integrity", `Root artifact changed before inventory: ${path}`, ); - const format = await classifyRootFormat(path, handle, initial); + const format = await classifyRootFormat( + path, + handle, + initial, + options.signal, + ); const digest = await hashStableRootArtifactHandle( path, handle, @@ -137,13 +146,19 @@ export const classifyAndHashRootForInventory = async ( outcome = { kind: "failed", cause: - cause instanceof RegularFileChangedError + options.signal?.aborted === true ? new ArtifactReaderFailure( - "integrity", - `Root artifact changed during inventory: ${path}`, - { cause: cause.cause ?? cause }, + "cancelled", + "Artifact inventory cancelled", + { cause }, ) - : cause, + : cause instanceof RegularFileChangedError + ? new ArtifactReaderFailure( + "integrity", + `Root artifact changed during inventory: ${path}`, + { cause: cause.cause ?? cause }, + ) + : cause, }; } if (outcome.kind === "failed" || outcome.value.rootSource === undefined) { @@ -165,10 +180,14 @@ const classifyRootFormat = async ( path: string, handle: FileHandle, initial: Stats, + signal?: AbortSignal, ): Promise => { + abortIfNeeded(signal); const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES); const observed = await handle.read(magic, 0, magic.length, 0); + abortIfNeeded(signal); await verifyRegularFileState(path, { handle, initial }); + abortIfNeeded(signal); const prefix = magic.subarray(0, observed.bytesRead); if (nesContainerFormat(prefix) !== undefined) { const parsed = parseInesLayout(prefix, initial.size); diff --git a/src/artifacts/inventory/hashStableRootArtifact.ts b/src/artifacts/inventory/hashStableRootArtifact.ts index 0829412b2..bfab1a0b3 100644 --- a/src/artifacts/inventory/hashStableRootArtifact.ts +++ b/src/artifacts/inventory/hashStableRootArtifact.ts @@ -130,6 +130,7 @@ export const hashStableRootArtifactHandle = async ( try { await verifyRegularFileState(path, { handle, initial }); } catch (cause: unknown) { + abortIfNeeded(signal); if (cause instanceof RegularFileChangedError) throw new ArtifactReaderFailure( "integrity", @@ -138,6 +139,7 @@ export const hashStableRootArtifactHandle = async ( ); throw cause; } + abortIfNeeded(signal); if (digest.bytes !== initial.size) throw new ArtifactReaderFailure( "integrity", diff --git a/tests/boundary/filesystem/inesCancellation.test.ts b/tests/boundary/filesystem/inesCancellation.test.ts new file mode 100644 index 000000000..d979c7f95 --- /dev/null +++ b/tests/boundary/filesystem/inesCancellation.test.ts @@ -0,0 +1,239 @@ +import { createHash } from "node:crypto"; +import { open, writeFile, type FileHandle } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js"; +import { InesArtifactReader } from "../../../src/artifacts/InesArtifactReader.js"; +import { hashStableRootArtifactHandle } from "../../../src/artifacts/inventory/hashStableRootArtifact.js"; +import { inventoryArtifact } from "../../fixtures/artifactInventory.js"; +import { inesFixture } from "../../fixtures/ines.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +// Complete the real I/O, then cancel while its caller is still awaiting it. +const cancelAfterNextStat = ( + handle: FileHandle, + controller: AbortController, + mutate?: () => Promise, +) => { + const original = handle.stat.bind(handle); + const stat = vi + .spyOn(handle, "stat") + .mockImplementationOnce(async (...args) => { + await mutate?.(); + const observed = await original(...args); + controller.abort(); + return observed; + }); + return () => stat.mockRestore(); +}; + +const malformed = (format: string) => { + if (format === "UNIF") return Buffer.from("UNIF"); + const bytes = inesFixture(); + if (format === "NES 2.0") { + bytes[7] = 8; + return bytes; + } + return bytes.subarray(0, 20); +}; + +it.each([ + ["truncated", "read"], + ["NES 2.0", "read"], + ["UNIF", "read"], + ["truncated", "validation"], + ["NES 2.0", "validation"], + ["UNIF", "validation"], +])("honors cancellation during %s root prefix %s", async (format, phase) => { + const root = await createTestTempDirectory("rea-ines-cancel-prefix-"); + const path = join(root, "source.nes"); + await writeFile(path, malformed(format)); + const sample = await open(path, "r"); + const prototype = Object.getPrototypeOf(sample) as Pick; + await sample.close(); + const original = prototype.read; + const controller = new AbortController(); + let admitted: FileHandle | undefined; + let restoreStat = () => {}; + const read = vi + .spyOn(prototype, "read") + .mockImplementationOnce(async function (this: FileHandle, ...args) { + admitted = this; + const observed = await original.call(this, ...args); + if (phase === "read") controller.abort(); + else restoreStat = cancelAfterNextStat(this, controller); + return observed; + }); + try { + await expect( + inventoryArtifact(path, { signal: controller.signal }), + ).rejects.toMatchObject({ reason: "cancelled" }); + expect(controller.signal.aborted).toBe(true); + if (admitted === undefined) + throw new Error("Prefix descriptor was not observed"); + await expect(admitted.stat()).rejects.toMatchObject({ code: "EBADF" }); + } finally { + restoreStat(); + read.mockRestore(); + } +}); + +it("honors cancellation during malformed reader header validation", async () => { + const root = await createTestTempDirectory("rea-ines-cancel-header-"); + const path = join(root, "source.nes"); + await writeFile(path, malformed("truncated")); + const handle = await open(path, "r"); + const reader = new InesArtifactReader(path, { + handle, + initial: await handle.stat(), + }); + const controller = new AbortController(); + const original = handle.read.bind(handle); + let restoreStat = () => {}; + const read = vi + .spyOn(handle, "read") + .mockImplementationOnce(async (...args) => { + const observed = await original(...args); + restoreStat = cancelAfterNextStat(handle, controller); + return observed; + }); + try { + await expect( + reader.entries(controller.signal)[Symbol.asyncIterator]().next(), + ).rejects.toMatchObject({ reason: "cancelled" }); + expect(controller.signal.aborted).toBe(true); + } finally { + restoreStat(); + read.mockRestore(); + await reader.close(); + await handle.close(); + } +}); + +it.each(["stream", "reconstruction"])( + "does not complete %s after cancellation in the final region validation", + async (operation) => { + const root = await createTestTempDirectory("rea-ines-cancel-region-"); + const path = join(root, "source.nes"); + const bytes = inesFixture(); + await writeFile(path, bytes); + const handle = await open(path, "r"); + const reader = new InesArtifactReader(path, { + handle, + initial: await handle.stat(), + }); + const controller = new AbortController(); + let restoreStat = () => {}; + const original = handle.read.bind(handle); + const read = vi + .spyOn(handle, "read") + .mockImplementation(async (...args) => { + const observed = await original(...args); + const arguments_: readonly unknown[] = args; + const position = arguments_[3]; + if ( + (typeof position === "number" || typeof position === "bigint") && + observed.bytesRead > 0 && + Number(position) + observed.bytesRead === bytes.length + ) + restoreStat = cancelAfterNextStat(handle, controller); + return observed; + }); + try { + const entries = []; + for await (const entry of reader.entries()) entries.push(entry); + const last = entries.at(-1); + if (last === undefined) throw new Error("Missing last iNES region"); + const result = + operation === "reconstruction" + ? reader.verifyReconstruction( + createHash("sha256").update(bytes).digest("hex"), + controller.signal, + ) + : (async () => { + for await (const chunk of await reader.open( + last, + controller.signal, + )) + expect(Buffer.isBuffer(chunk)).toBe(true); + })(); + await expect(result).rejects.toMatchObject({ reason: "cancelled" }); + expect(controller.signal.aborted).toBe(true); + } finally { + restoreStat(); + read.mockRestore(); + await reader.close(); + await handle.close(); + } + }, +); + +it("does not publish a root digest cancelled during its final state check", async () => { + const root = await createTestTempDirectory("rea-ines-cancel-hash-"); + const path = join(root, "source.nes"); + await writeFile(path, inesFixture()); + const handle = await open(path, "r"); + const initial = await handle.stat(); + const controller = new AbortController(); + const restore = cancelAfterNextStat(handle, controller); + try { + await expect( + hashStableRootArtifactHandle(path, handle, initial, controller.signal), + ).rejects.toMatchObject({ reason: "cancelled" }); + expect(controller.signal.aborted).toBe(true); + } finally { + restore(); + await handle.close(); + } +}); + +it.each([ + ["prefix", false], + ["prefix", true], + ["hash", false], + ["hash", true], +] as const)( + "cancels target %s validation with concurrent change=%s", + async (phase, changed) => { + const root = await createTestTempDirectory("rea-ines-cancel-target-"); + const path = join(root, "source.nes"); + await writeFile(path, inesFixture()); + const sample = await open(path, "r"); + const prototype = Object.getPrototypeOf(sample) as Pick; + await sample.close(); + const original = prototype.read; + const controller = new AbortController(); + let admitted: FileHandle | undefined; + let restoreStat = () => {}; + const read = vi.spyOn(prototype, "read").mockImplementation(async function ( + this: FileHandle, + ...args + ) { + const observed = await original.call(this, ...args); + if ( + admitted === undefined && + (phase === "prefix" || observed.bytesRead === 0) + ) { + admitted = this; + restoreStat = cancelAfterNextStat( + this, + controller, + changed ? () => writeFile(path, "changed cartridge") : undefined, + ); + } + return observed; + }); + try { + expect( + await parseBinaryTarget(path, { signal: controller.signal }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } }); + expect(controller.signal.aborted).toBe(true); + if (admitted === undefined) + throw new Error("Hash descriptor was not observed"); + await expect(admitted.stat()).rejects.toMatchObject({ code: "EBADF" }); + } finally { + restoreStat(); + read.mockRestore(); + } + }, +);