diff --git a/src/artifacts/InesArtifactReader.ts b/src/artifacts/InesArtifactReader.ts index cfb05f5f4..caa9d8fd8 100644 --- a/src/artifacts/InesArtifactReader.ts +++ b/src/artifacts/InesArtifactReader.ts @@ -45,13 +45,14 @@ export class InesArtifactReader implements ArtifactReader { 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(); const parsed = parseInesLayout( prefix.subarray(0, bytesRead), this.source.initial.size, ); if (!parsed.ok) throw new ArtifactReaderFailure("format", parsed.error); this.#layout = parsed.value; - await this.#verifySource(); this.#entries.clear(); for (const region of parsed.value.regions) { abortIfNeeded(signal); diff --git a/tests/boundary/filesystem/inesArtifact.test.ts b/tests/boundary/filesystem/inesArtifact.test.ts index bc54a2c59..e993297c6 100644 --- a/tests/boundary/filesystem/inesArtifact.test.ts +++ b/tests/boundary/filesystem/inesArtifact.test.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { lstat, open, readFile, unlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { inesFixture } from "../../fixtures/ines.js"; @@ -233,6 +233,43 @@ it.each(["before", "during"])( }, ); +it.each(["truncated", "overwritten"])( + "reports a header %s during admission as an integrity failure", + async (change) => { + const root = await createTestTempDirectory("rea-ines-header-race-"); + const path = join(root, "source.nes"); + await writeFile(path, inesFixture()); + const handle = await open(path, "r"); + const reader = new InesArtifactReader(path, { + handle, + initial: await handle.stat(), + }); + const originalRead = handle.read.bind(handle); + // Mutate the actual file after pre-read validation, at the read boundary. + const read = vi + .spyOn(handle, "read") + .mockImplementationOnce(async (...args) => { + const changed = + change === "truncated" + ? Buffer.alloc(0) + : Buffer.alloc(inesFixture().length); + await writeFile(path, changed); + return originalRead(...args); + }); + try { + await expect( + reader.entries()[Symbol.asyncIterator]().next(), + ).rejects.toMatchObject({ + reason: "integrity", + }); + } finally { + read.mockRestore(); + await reader.close(); + await handle.close(); + } + }, +); + it("releases an extraction-owned source descriptor on repeated close", async () => { const root = await createTestTempDirectory("rea-ines-owned-source-"); const path = join(root, "source.nes");