fix(artifacts): complete prefix reads and share ZIP format admission
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js";
|
||||
import { constants, type Stats } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
@@ -297,12 +298,13 @@ const detectArtifactFormat = async (
|
||||
> => {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const lower = path.toLowerCase();
|
||||
const magic = Buffer.alloc(16);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
const magic = await readFileHandlePrefix(handle, 16, () =>
|
||||
throwIfTargetResolutionCancelled(signal),
|
||||
);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
await verifyTargetState(path, handle, initial, signal);
|
||||
if (
|
||||
observed.bytesRead >= 8 &&
|
||||
magic.length >= 8 &&
|
||||
magic.subarray(0, 8).equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]))
|
||||
)
|
||||
throw new BinaryTargetError(
|
||||
@@ -310,7 +312,7 @@ const detectArtifactFormat = async (
|
||||
"WebAssembly v1 artifacts are not supported by the native opening route",
|
||||
{ constraint: "wasm_requires_static_inspection" },
|
||||
);
|
||||
const prefix = magic.subarray(0, observed.bytesRead);
|
||||
const prefix = magic;
|
||||
const nesFormat = nesContainerFormat(prefix);
|
||||
if (nesFormat !== undefined) {
|
||||
const parsed = parseInesLayout(prefix, initial.size);
|
||||
@@ -328,16 +330,13 @@ const detectArtifactFormat = async (
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
// Binary plists, including keyed archives, often use other extensions.
|
||||
if (
|
||||
observed.bytesRead >= 8 &&
|
||||
magic.subarray(0, 8).equals(Buffer.from("bplist00"))
|
||||
)
|
||||
if (magic.length >= 8 && magic.subarray(0, 8).equals(Buffer.from("bplist00")))
|
||||
return "plist";
|
||||
const named = namedArtifactFormat(lower);
|
||||
if (named !== undefined) return named;
|
||||
if (
|
||||
lower.endsWith(".pkg") &&
|
||||
observed.bytesRead >= 4 &&
|
||||
magic.length >= 4 &&
|
||||
magic.subarray(0, 4).equals(Buffer.from("xar!"))
|
||||
)
|
||||
return "pkg";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { Readable } from "node:stream";
|
||||
import {
|
||||
@@ -42,15 +43,13 @@ export class InesArtifactReader implements ArtifactReader {
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
abortIfNeeded(signal);
|
||||
await this.#verifySource(signal);
|
||||
const prefix = Buffer.alloc(16);
|
||||
const { bytesRead } = await this.source.handle.read(prefix, 0, 16, 0);
|
||||
const prefix = await readFileHandlePrefix(this.source.handle, 16, () =>
|
||||
abortIfNeeded(signal),
|
||||
);
|
||||
abortIfNeeded(signal);
|
||||
// Concurrent source changes take precedence over malformed header diagnostics.
|
||||
await this.#verifySource(signal);
|
||||
const parsed = parseInesLayout(
|
||||
prefix.subarray(0, bytesRead),
|
||||
this.source.initial.size,
|
||||
);
|
||||
const parsed = parseInesLayout(prefix, this.source.initial.size);
|
||||
if (!parsed.ok) throw new ArtifactReaderFailure("format", parsed.error);
|
||||
this.#layout = parsed.value;
|
||||
this.#entries.clear();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
|
||||
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
|
||||
@@ -410,13 +411,6 @@ interface ExtractionInventory {
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
}
|
||||
|
||||
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
|
||||
|
||||
const isZipFormat = (
|
||||
format: BinaryTarget["format"] | ArtifactGraphManifest["root_format"],
|
||||
): format is (typeof ZIP_FORMATS)[number] =>
|
||||
(ZIP_FORMATS as readonly string[]).includes(format);
|
||||
|
||||
/**
|
||||
* Refuse a format without an extraction reader before inventory work starts.
|
||||
* The target kind, not the host, is unsupported by extraction. The error keeps
|
||||
@@ -433,7 +427,7 @@ const requireExtractableFormat = async (
|
||||
format !== "asar" &&
|
||||
format !== "ines" &&
|
||||
!isMachOFormat(format) &&
|
||||
!isZipFormat(format)
|
||||
!isZipPackageFormat(format)
|
||||
)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
"extract_artifact",
|
||||
@@ -498,7 +492,7 @@ const createReader = async (
|
||||
}
|
||||
if (format === "directory") return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
|
||||
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
|
||||
if (format === "mach-o" || format === "mach-o-universal")
|
||||
return new MachOSliceArtifactReader(path, input.environment);
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFileHandlePrefix } from "../../filesystem/readFileHandlePrefix.js";
|
||||
import {
|
||||
sameRegularFileState,
|
||||
verifyRegularFileState,
|
||||
@@ -183,12 +184,14 @@ const classifyRootFormat = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactOccurrence["artifact_format"]> => {
|
||||
abortIfNeeded(signal);
|
||||
const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
const prefix = await readFileHandlePrefix(
|
||||
handle,
|
||||
ARTIFACT_CLASSIFICATION_PREFIX_BYTES,
|
||||
() => abortIfNeeded(signal),
|
||||
);
|
||||
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);
|
||||
if (!parsed.ok) throw new ArtifactReaderFailure("format", parsed.error);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
|
||||
/** Fill a positional prefix until its bound or true EOF, preserving caller cancellation errors. */
|
||||
export const readFileHandlePrefix = async (
|
||||
handle: Pick<FileHandle, "read">,
|
||||
length: number,
|
||||
checkCancellation: () => void,
|
||||
): Promise<Buffer> => {
|
||||
const prefix = Buffer.alloc(length);
|
||||
let offset = 0;
|
||||
while (offset < length) {
|
||||
checkCancellation();
|
||||
let bytesRead: number;
|
||||
try {
|
||||
({ bytesRead } = await handle.read(
|
||||
prefix,
|
||||
offset,
|
||||
length - offset,
|
||||
offset,
|
||||
));
|
||||
} catch (cause: unknown) {
|
||||
checkCancellation();
|
||||
throw cause;
|
||||
}
|
||||
checkCancellation();
|
||||
if (bytesRead === 0) break;
|
||||
offset += bytesRead;
|
||||
}
|
||||
return prefix.subarray(0, offset);
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readFileHandlePrefix } from "../../../src/filesystem/readFileHandlePrefix.js";
|
||||
import { abortIfNeeded } from "../../../src/artifacts/ArtifactHash.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
lstat,
|
||||
@@ -543,3 +545,126 @@ it("releases an extraction-owned source descriptor on repeated close", async ()
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["target", "inventory", "reader"])(
|
||||
"fills short iNES prefix reads at the %s boundary",
|
||||
async (route) => {
|
||||
const root = await createTestTempDirectory("rea-ines-short-read-");
|
||||
const path = join(root, "source.nes");
|
||||
await writeFile(path, inesFixture());
|
||||
const sample = await open(path, "r");
|
||||
const initial = await sample.stat();
|
||||
const prototype = Object.getPrototypeOf(sample) as {
|
||||
read(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
position: number | bigint,
|
||||
): Promise<{ bytesRead: number; buffer: Buffer }>;
|
||||
};
|
||||
const originalRead = prototype.read;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof sample,
|
||||
...args
|
||||
) {
|
||||
const [buffer, offset, length, position] = args;
|
||||
return originalRead.call(
|
||||
this,
|
||||
buffer,
|
||||
offset,
|
||||
typeof position === "number" && position < 16
|
||||
? Math.min(length, 3)
|
||||
: length,
|
||||
position,
|
||||
);
|
||||
});
|
||||
try {
|
||||
if (route === "target") {
|
||||
expect(await parseBinaryTarget(path)).toMatchObject({
|
||||
ok: true,
|
||||
value: { format: "ines" },
|
||||
});
|
||||
} else if (route === "inventory") {
|
||||
expect(
|
||||
(await inventoryArtifact(path)).ines?.reconstruction.verified,
|
||||
).toBe(true);
|
||||
} else {
|
||||
const reader = new InesArtifactReader(path, {
|
||||
handle: sample,
|
||||
initial,
|
||||
});
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry.path);
|
||||
expect(entries).toContain("prg/000.bin");
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
await sample.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["eof", "cancelled", "failed-and-cancelled"])(
|
||||
"preserves %s while filling a short prefix",
|
||||
async (mode) => {
|
||||
const root = await createTestTempDirectory("rea-prefix-boundary-");
|
||||
const path = join(root, "source");
|
||||
const bytes = Buffer.from(
|
||||
mode === "eof" ? "NES\x1a" : "NES\x1a123456789012",
|
||||
);
|
||||
await writeFile(path, bytes);
|
||||
const handle = await open(path, "r");
|
||||
const prototype = Object.getPrototypeOf(handle) as {
|
||||
read(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
position: number,
|
||||
): Promise<{ bytesRead: number; buffer: Buffer }>;
|
||||
};
|
||||
const original = prototype.read;
|
||||
const controller = new AbortController();
|
||||
let reads = 0;
|
||||
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
|
||||
this: typeof handle,
|
||||
buffer,
|
||||
offset,
|
||||
length,
|
||||
position,
|
||||
) {
|
||||
reads++;
|
||||
if (reads === 2 && mode === "failed-and-cancelled") {
|
||||
controller.abort();
|
||||
throw new Error("injected read failure");
|
||||
}
|
||||
const observed = await original.call(
|
||||
this,
|
||||
buffer,
|
||||
offset,
|
||||
Math.min(length, 3),
|
||||
position,
|
||||
);
|
||||
if (reads === 2 && mode === "cancelled") controller.abort();
|
||||
return observed;
|
||||
});
|
||||
try {
|
||||
const result = readFileHandlePrefix(handle, 16, () =>
|
||||
abortIfNeeded(controller.signal),
|
||||
);
|
||||
if (mode === "eof") {
|
||||
expect(await result).toEqual(bytes);
|
||||
expect(reads).toBe(3);
|
||||
} else {
|
||||
await expect(result).rejects.toMatchObject({ reason: "cancelled" });
|
||||
expect(reads).toBe(2);
|
||||
}
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
await handle.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -15,7 +15,7 @@ import { artifactExtractionExecutionSchema } from "../../../../src/contracts/art
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||
|
||||
describe("artifact extraction format support", () => {
|
||||
it.each(["zip", "asar"] as const)(
|
||||
it.each(["zip", "asar", "hap", "hsp", "app"] as const)(
|
||||
"extracts the scanned %s after an active iNES path is replaced",
|
||||
async (format) => {
|
||||
const root = await createTestTempDirectory("rea-extract-replaced-");
|
||||
@@ -27,7 +27,7 @@ describe("artifact extraction format support", () => {
|
||||
const client = new ArtifactProvider(process.env).createClient(
|
||||
target.value,
|
||||
);
|
||||
if (format === "zip") {
|
||||
if (format !== "asar") {
|
||||
await writeOrderedZip(path, ["payload.txt"]);
|
||||
} else {
|
||||
const source = join(root, "source");
|
||||
@@ -44,7 +44,9 @@ describe("artifact extraction format support", () => {
|
||||
const extracted = artifactExtractionResultSchema.parse(
|
||||
result.value.result,
|
||||
);
|
||||
expect(extracted.manifest.root_format).toBe(format);
|
||||
expect(extracted.manifest.root_format).toBe(
|
||||
format === "app" ? "app-pack" : format,
|
||||
);
|
||||
expect(
|
||||
extracted.artifacts.map(({ relative_path }) => relative_path),
|
||||
).toEqual(["payload.txt"]);
|
||||
|
||||
Reference in New Issue
Block a user