fix(artifacts): revalidate iNES source before parsing header

This commit is contained in:
64579525
2026-10-12 16:11:55 +08:00
parent 574f6bb3bd
commit 5ba8b2f6bf
2 changed files with 40 additions and 2 deletions
+2 -1
View File
@@ -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);
+38 -1
View File
@@ -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");