fix(artifacts): forward archived failures, align CRC recovery, fatal TOC decoding

This commit is contained in:
morluto
2026-10-08 16:19:24 +08:00
parent b196c5ac8f
commit da18453d4d
3 changed files with 154 additions and 88 deletions
+7 -9
View File
@@ -1,9 +1,4 @@
import {
PassThrough,
Readable,
Transform,
type TransformCallback,
} from "node:stream";
import { Readable, Transform, type TransformCallback } from "node:stream";
import { createGunzip } from "node:zlib";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
@@ -533,14 +528,17 @@ export class CpioArtifactReader implements ArtifactReader {
for (const byte of chunk) sum = (sum + byte) >>> 0;
yield chunk;
}
// Consume padding before reporting a mismatch: under record-and-continue
// iteration resumes after this error, and leftover padding would be read
// as the next header's magic.
await drain(
source.take(padding(header.format, header.fileSize), "data padding"),
);
if (header.format === "crc" && sum !== header.check)
throw new ArtifactReaderFailure(
"integrity",
`cpio CRC disagrees with content: ${path}`,
);
await drain(
source.take(padding(header.format, header.fileSize), "data padding"),
);
}
async #collect(
+106 -79
View File
@@ -134,6 +134,48 @@ const parseData = (file: Element): XarData | undefined => {
};
};
/**
* Raw members must describe their stored bytes exactly; otherwise the source
* range would extend into adjacent heap entries.
*/
const assertRawSize = (member: XarMember, data: XarData | undefined): void => {
if (
data !== undefined &&
data.encoding === "application/octet-stream" &&
data.size !== data.length
)
throw new ArtifactReaderFailure(
"format",
`xar member ${member.path} declares size ${data.size} with length ${data.length}`,
);
};
/** Entry limitations from the TOC record and nested-archive classification. */
const memberLimitations = (
member: XarMember,
unsupportedChecksum: XarData["unsupportedChecksum"],
classified: { readonly limitations: readonly string[] },
): string[] => [
...(member.kind === "symlink" && member.link !== undefined
? [`Symlink target recorded in the TOC: ${member.link}`]
: []),
...(unsupportedChecksum === undefined
? []
: [
`Member declares unsupported checksum ${unsupportedChecksum.style}; integrity not verified.`,
]),
...classified.limitations,
];
/** File, directory, symlink, or an explicitly unsupported TOC type. */
const classifyMemberType = (
type: string | undefined,
): { readonly kind: XarMember["kind"]; readonly unsupportedType?: string } => {
if (type === "directory" || type === "symlink") return { kind: type };
if (type === undefined || type === "file") return { kind: "file" };
return { kind: "file", unsupportedType: type };
};
/** Walk nested `<file>` elements in document order. */
const collectMembers = (toc: Element): XarMember[] => {
const members: XarMember[] = [];
@@ -158,21 +200,7 @@ const collectMembers = (toc: Element): XarMember[] => {
const modeText = textOf(next.element, "mode");
const mode =
modeText === undefined ? Number.NaN : Number.parseInt(modeText.trim(), 8);
const kind =
type === "directory"
? "directory"
: type === "symlink"
? "symlink"
: type === undefined || type === "file"
? "file"
: "file";
const unsupportedType =
type !== undefined &&
type !== "file" &&
type !== "directory" &&
type !== "symlink"
? type
: undefined;
const { kind, unsupportedType } = classifyMemberType(type);
members.push({
path,
kind,
@@ -348,10 +376,20 @@ export class XarArtifactReader implements ArtifactReader {
this.#heap = headerSize + compressed.length;
let xml: string;
try {
xml = inflateSync(compressed, {
const inflated = inflateSync(compressed, {
maxOutputLength: MAX_TOC_BYTES,
}).toString("utf8");
});
try {
xml = new TextDecoder("utf-8", { fatal: true }).decode(inflated);
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
"xar TOC is not valid UTF-8",
{ cause },
);
}
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) throw cause;
throw new ArtifactReaderFailure("format", "xar TOC is not zlib data", {
cause,
});
@@ -486,75 +524,58 @@ export class XarArtifactReader implements ArtifactReader {
await this.#load(signal);
for (const member of this.#members) {
cancelled(signal);
if (member.unsupportedType !== undefined) {
yield {
path: member.path,
kind: "file",
declaredSize: null,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations: [
`Unsupported xar member type ${member.unsupportedType}; content not expanded.`,
],
adapterKey: member.path,
contentUnavailable: true,
};
continue;
}
const data = member.data;
// Raw members must describe their stored bytes exactly; otherwise the
// source range would extend into adjacent heap entries.
if (
data !== undefined &&
data.encoding === "application/octet-stream" &&
data.size !== data.length
)
throw new ArtifactReaderFailure(
"format",
`xar member ${member.path} declares size ${data.size} with length ${data.length}`,
);
const unsupportedChecksum = data?.unsupportedChecksum;
const classified =
member.kind === "file" && unsupportedChecksum === undefined
? await this.#nestedArchive(member)
: {
nested: undefined as XarNestedArchive | undefined,
limitations: [] as readonly string[],
};
yield {
yield await this.#memberEntry(member);
}
}
/** Project one TOC member as an archive-neutral entry. */
async #memberEntry(member: XarMember): Promise<ArtifactEntry> {
if (member.unsupportedType !== undefined)
return {
path: member.path,
kind: member.kind,
declaredSize: member.data?.size ?? (member.kind === "file" ? 0 : null),
compressedSize: member.data?.length ?? null,
executable: member.mode !== null && (member.mode & 0o111) !== 0,
kind: "file",
declaredSize: null,
compressedSize: null,
executable: false,
encrypted: false,
byteOffset:
member.data?.encoding === "application/octet-stream"
? this.#heap + member.data.offset
: null,
...declaredDigest(member.data?.extractedChecksum),
byteOffset: null,
declaredSha256: null,
unpacked: false,
limitations: [
...(member.kind === "symlink" && member.link !== undefined
? [`Symlink target recorded in the TOC: ${member.link}`]
: []),
...(unsupportedChecksum === undefined
? []
: [
`Member declares unsupported checksum ${unsupportedChecksum.style}; integrity not verified.`,
]),
...classified.limitations,
`Unsupported xar member type ${member.unsupportedType}; content not expanded.`,
],
adapterKey: member.path,
...(classified.nested === undefined
? {}
: { nestedArchive: classified.nested }),
contentUnavailable: true,
};
}
const data = member.data;
assertRawSize(member, data);
const unsupportedChecksum = data?.unsupportedChecksum;
const classified =
member.kind === "file" && unsupportedChecksum === undefined
? await this.#nestedArchive(member)
: {
nested: undefined as XarNestedArchive | undefined,
limitations: [] as readonly string[],
};
return {
path: member.path,
kind: member.kind,
declaredSize: member.data?.size ?? (member.kind === "file" ? 0 : null),
compressedSize: member.data?.length ?? null,
executable: member.mode !== null && (member.mode & 0o111) !== 0,
encrypted: false,
byteOffset:
member.data?.encoding === "application/octet-stream"
? this.#heap + member.data.offset
: null,
...declaredDigest(member.data?.extractedChecksum),
unpacked: false,
limitations: memberLimitations(member, unsupportedChecksum, classified),
adapterKey: member.path,
...(classified.nested === undefined
? {}
: { nestedArchive: classified.nested }),
};
}
async open(entry: ArtifactEntry, signal?: AbortSignal): Promise<Readable> {
@@ -614,6 +635,12 @@ export class XarArtifactReader implements ArtifactReader {
raw.on("error", (cause: unknown) =>
inflate.destroy(memberFailure(entry.path, cause)),
);
// Checksum failures emit on archivedChecked, which pipe() does not
// forward; without this the integrity error becomes unhandled instead
// of rolling back extraction with the tagged failure.
archivedChecked.on("error", (cause: unknown) =>
inflate.destroy(memberFailure(entry.path, cause)),
);
const inflated = archivedChecked.pipe(inflate);
const bounded = new SizeBound(entry.path, data.size);
inflated.on("error", (cause: unknown) =>
@@ -184,3 +184,44 @@ describe("installer package inventory", () => {
});
});
});
describe("installer package CRC recovery", () => {
it("recovers later siblings after a misaligned CRC mismatch", async () => {
const directory = await createTestTempDirectory("rea-pkg-crc-align-");
const path = join(directory, "Installer.pkg");
await writeFile(
path,
xarArchive([
{
name: "Payload",
// "abc" is 3 bytes (1 padding byte): a CRC failure here must not
// desynchronize the following member.
data: gzipCpio(
[
{ name: "./bad", mode: MODE.file, data: "abc", check: 1 },
{ name: "./good", mode: MODE.file, data: "ok" },
],
"crc",
),
},
]),
);
const inventory = artifactInventoryResultSchema.parse(
parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {
integrity_policy: "record-and-continue",
}),
).normalized_result,
);
expect(
inventory.occurrences.find(
({ logical_path: logical }) => logical === "Payload/bad",
),
).toMatchObject({ hash_status: "unavailable" });
expect(
inventory.occurrences.find(
({ logical_path: logical }) => logical === "Payload/good",
),
).toMatchObject({ hash_status: "verified" });
});
});