fix(artifacts): keep cpio checksum evidence and bound xar TOC elements (#1082)

Record-and-continue used to catch integrity exceptions and keep only the
message, so directory, symlink, special-node, and zero-size link CRC
failures dropped the declared and observed sums. One checksum check now
returns that observation for every member kind.

A TOC within the byte cap can still contain millions of elements. Count
elements before building the DOM and fail with a tagged limit.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
morluto
2026-10-08 22:41:42 +08:00
committed by GitHub
co-authored by Cursor Agent
parent 23578197cc
commit 6dda47c98c
5 changed files with 183 additions and 87 deletions
+132 -83
View File
@@ -223,6 +223,20 @@ const drain = async (chunks: AsyncIterable<Buffer>): Promise<void> => {
for await (const chunk of chunks) void chunk;
};
const crcObservation = (
declared: number,
observed: number,
): ArtifactChecksumObservation => ({
representation: "decoded",
algorithm: "cpio-byte-sum",
declared: declared.toString(16).padStart(8, "0"),
observed: observed.toString(16).padStart(8, "0"),
});
/** Same sentence the scanner uses for a streamed regular-file CRC contradiction. */
const crcMismatchDetail = (observation: ArtifactChecksumObservation): string =>
`Declared ${observation.representation} ${observation.algorithm} ${observation.declared} disagrees with observed ${observation.observed}.`;
/** Human-readable limitation for a collected (or skipped) symlink target. */
const symlinkTargetLimitation = (
header: CpioHeader,
@@ -274,10 +288,10 @@ export class CpioArtifactReader implements ArtifactReader {
signal?: AbortSignal,
) => Promise<Readable>,
/**
* Integrity mode for iteration-time CRC failures. Streamed data CRCs are
* always checked; under record-and-continue a zero-size hard-link header
* whose CRC disagrees is yielded as an unavailable occurrence so later
* siblings are still inventoried, instead of aborting the archive.
* Integrity mode for member CRC failures. Every member representation is
* checked before the next header is read. `fail` throws. Under
* record-and-continue the disagreement is returned as checksum evidence
* so the occurrence and later siblings are still inventoried.
*/
private readonly integrity: "fail" | "record-and-continue" = "fail",
readonly decodedBudget: ArtifactDecodedBudget = new ArtifactDecodedBudget(),
@@ -347,7 +361,7 @@ export class CpioArtifactReader implements ArtifactReader {
"format",
"cpio trailer declares member data",
);
await drain(this.#verified(source, header, raw));
await drain(this.#verified(source, header, raw, undefined, "fail"));
await source.finish();
yield* this.#unresolvedLinks();
return;
@@ -365,17 +379,18 @@ export class CpioArtifactReader implements ArtifactReader {
const type = header.mode & S_IFMT;
const path = memberPath(raw);
if (type === S_IFDIR) {
const verified = await this.#recoverIntegrity(() =>
drain(this.#verified(source, header, raw)),
);
const consumed = await this.#consume(source, header, raw, false);
if (path !== undefined)
yield entryOf({
path,
kind: "directory",
key,
header,
limitations: "mismatch" in verified ? [verified.mismatch] : [],
integrityMismatched: "mismatch" in verified,
limitations:
consumed.mismatch === undefined
? []
: [crcMismatchDetail(consumed.mismatch)],
integrityMismatched: consumed.mismatch !== undefined,
});
return;
}
@@ -392,17 +407,15 @@ export class CpioArtifactReader implements ArtifactReader {
// Zero-size headers carry no bytes, so a CRC archive must declare zero.
// Under record-and-continue this is the occurrence's own forgotten
// bytes: yield it unavailable so later siblings still inventory.
const verified = await this.#recoverIntegrity(() =>
drain(this.#verified(source, header, raw)),
);
if ("mismatch" in verified) {
const consumed = await this.#consume(source, header, raw, false);
if (consumed.mismatch !== undefined) {
yield entryOf({
path,
kind: "file",
key,
header,
size: null,
limitations: [verified.mismatch],
limitations: [crcMismatchDetail(consumed.mismatch)],
contentUnavailable: true,
});
return;
@@ -425,9 +438,7 @@ export class CpioArtifactReader implements ArtifactReader {
if (type !== S_IFREG) {
// FIFOs, device nodes, sockets and other types are not expanded; keep
// an explicit unavailable occurrence instead of dropping the path.
const verified = await this.#recoverIntegrity(() =>
drain(this.#verified(source, header, raw)),
);
const consumed = await this.#consume(source, header, raw, false);
this.#current = undefined;
yield entryOf({
path,
@@ -437,7 +448,9 @@ export class CpioArtifactReader implements ArtifactReader {
size: null,
limitations: [
`Unsupported cpio member type ${type.toString(8)}; content not expanded.`,
...("mismatch" in verified ? [verified.mismatch] : []),
...(consumed.mismatch === undefined
? []
: [crcMismatchDetail(consumed.mismatch)]),
],
contentUnavailable: true,
});
@@ -454,10 +467,9 @@ export class CpioArtifactReader implements ArtifactReader {
/**
* One symlink member. A hostile header can declare a multi-gigabyte target,
* so oversized targets stream past. CRC failures surface before the entry
* is yielded, outside the scanner's per-entry recovery: under
* record-and-continue the symlink becomes an unavailable occurrence so
* later siblings still inventory.
* so oversized targets stream past. The CRC is resolved before the entry is
* yielded; under record-and-continue a disagreement stays on the occurrence
* so later siblings are still inventoried.
*/
async *#symlink(
source: ByteSource,
@@ -469,21 +481,20 @@ export class CpioArtifactReader implements ArtifactReader {
path: string | undefined,
): AsyncGenerator<ArtifactEntry> {
const { header, raw, key } = member;
const observed = await this.#recoverIntegrity(async () => {
if (header.fileSize > MAX_SYMLINK_TARGET_BYTES) {
await drain(this.#verified(source, header, raw));
return undefined;
}
return this.#collect(source, header, raw);
});
const consumed = await this.#consume(
source,
header,
raw,
header.fileSize <= MAX_SYMLINK_TARGET_BYTES,
);
if (path === undefined) return;
if ("mismatch" in observed) {
if (consumed.mismatch !== undefined) {
yield entryOf({
path,
kind: "symlink",
key,
header,
limitations: [observed.mismatch],
limitations: [crcMismatchDetail(consumed.mismatch)],
contentUnavailable: true,
});
return;
@@ -493,27 +504,10 @@ export class CpioArtifactReader implements ArtifactReader {
kind: "symlink",
key,
header,
limitations: [symlinkTargetLimitation(header, observed.value)],
limitations: [symlinkTargetLimitation(header, consumed.bytes)],
});
}
/** The one integrity-policy boundary for metadata consumed before yielding an entry. */
async #recoverIntegrity<T>(
read: () => Promise<T>,
): Promise<{ readonly value: T } | { readonly mismatch: string }> {
try {
return { value: await read() };
} catch (cause: unknown) {
if (
this.integrity !== "record-and-continue" ||
!(cause instanceof ArtifactReaderFailure) ||
cause.reason !== "integrity"
)
throw cause;
return { mismatch: cause.message };
}
}
#alias(
path: string,
key: string,
@@ -583,7 +577,16 @@ export class CpioArtifactReader implements ArtifactReader {
current.header,
await this.#collect(source, current.header, current.path),
);
else await drain(this.#verified(source, current.header, current.path));
else
await drain(
this.#verified(
source,
current.header,
current.path,
undefined,
"fail",
),
);
}
const waiting = this.#pending.get(current.header.identity);
const stored = this.#links.get(current.header.identity);
@@ -615,42 +618,88 @@ export class CpioArtifactReader implements ArtifactReader {
this.#buffered += bytes.length;
}
/**
* Member bytes and padding. `sum` receives the unsigned 32-bit total used
* by `070702`. Padding is consumed before the caller reports a mismatch, so
* a recovered archive stays aligned on the next header.
*/
async *#payload(
source: ByteSource,
header: CpioHeader,
sum: { value: number },
): AsyncGenerator<Buffer> {
this.#cancelled();
for await (const chunk of source.take(header.fileSize, "member data")) {
this.#cancelled();
if (header.format === "crc")
for (const byte of chunk) sum.value = (sum.value + byte) >>> 0;
yield chunk;
}
await drain(
source.take(padding(header.format, header.fileSize), "data padding"),
);
this.#cancelled();
}
/**
* One CRC check for every member kind. `fail` throws with the observation
* in the message. record-and-continue returns the observation so callers
* keep declared and observed values instead of catching a string.
*/
#crcMismatch(
header: CpioHeader,
path: string,
sum: number,
policy: "fail" | "record-and-continue" = this.integrity,
): ArtifactChecksumObservation | undefined {
if (header.format !== "crc" || sum === header.check) return undefined;
const observation = crcObservation(header.check, sum);
if (policy === "fail")
throw new ArtifactReaderFailure(
"integrity",
`cpio CRC disagrees with content: ${path} (${crcMismatchDetail(observation)})`,
);
return observation;
}
/** Read one member fully. `collect` retains bytes for symlinks and hard links. */
async #consume(
source: ByteSource,
header: CpioHeader,
path: string,
collect: boolean,
policy?: "fail" | "record-and-continue",
): Promise<{
readonly bytes: Buffer | undefined;
readonly mismatch: ArtifactChecksumObservation | undefined;
}> {
const sum = { value: 0 };
const chunks: Buffer[] = [];
for await (const chunk of this.#payload(source, header, sum))
if (collect) chunks.push(chunk);
return {
bytes: collect ? Buffer.concat(chunks) : undefined,
mismatch: this.#crcMismatch(header, path, sum.value, policy),
};
}
/** Member data and its padding, checked against a `070702` CRC. */
async *#verified(
source: ByteSource,
header: CpioHeader,
path: string,
record?: (observation: ArtifactChecksumObservation) => void,
policy?: "fail" | "record-and-continue",
): AsyncGenerator<Buffer> {
let sum = 0;
this.#cancelled();
for await (const chunk of source.take(header.fileSize, "member data")) {
this.#cancelled();
if (header.format === "crc")
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"),
const sum = { value: 0 };
yield* this.#payload(source, header, sum);
const mismatch = this.#crcMismatch(
header,
path,
sum.value,
policy ?? this.integrity,
);
this.#cancelled();
if (header.format === "crc" && sum !== header.check) {
if (record !== undefined)
record({
representation: "decoded",
algorithm: "cpio-byte-sum",
declared: header.check.toString(16).padStart(8, "0"),
observed: sum.toString(16).padStart(8, "0"),
});
else
throw new ArtifactReaderFailure(
"integrity",
`cpio CRC disagrees with content: ${path}`,
);
}
if (mismatch !== undefined) record?.(mismatch);
}
async #collect(
@@ -658,10 +707,10 @@ export class CpioArtifactReader implements ArtifactReader {
header: CpioHeader,
path: string,
): Promise<Buffer> {
const chunks: Buffer[] = [];
for await (const chunk of this.#verified(source, header, path))
chunks.push(chunk);
return Buffer.concat(chunks);
// Unopened linked bytes are not a recovered occurrence. A disagreement
// still fails the archive instead of being remembered as verified content.
const consumed = await this.#consume(source, header, path, true, "fail");
return consumed.bytes ?? Buffer.alloc(0);
}
#cancelled(): void {
+22 -3
View File
@@ -258,7 +258,7 @@ it("preserves CRC contradictions for special nodes and reaches later siblings",
paths.push(entry.path);
if (entry.path === "fifo")
expect(entry.limitations).toContain(
"cpio CRC disagrees with content: fifo",
"Declared decoded cpio-byte-sum 00000001 disagrees with observed 00000126.",
);
if (entry.path === "good")
expect((await buffer(await reader.open(entry))).toString()).toBe("ok");
@@ -282,6 +282,24 @@ it("does not expose a partial inventory when a previous TOC load failed", async
);
});
it("rejects a TOC whose element count would build an unbounded DOM", async () => {
const noise = "<n/>".repeat(100_001);
const bytes = rewriteXarToc(
xarArchive([{ name: "a", data: Buffer.from("ok") }]),
(xml) => xml.replace("<toc>", `<toc>${noise}`),
);
await withReader(bytes, async (reader) => {
await expect(
(async () => {
for await (const entry of reader.entries()) void entry;
})(),
).rejects.toMatchObject({
reason: "limit",
message: "xar TOC exceeds 100000 XML elements",
});
});
});
it("rejects a TOC checksum when the fixed header declares none", async () => {
const bytes = Buffer.from(
xarArchive([{ name: "a", data: Buffer.from("ok") }]),
@@ -336,7 +354,8 @@ it("rejects a CRC trailer whose declared checksum is not empty-data zero", async
})(),
).rejects.toMatchObject({
reason: "integrity",
message: "cpio CRC disagrees with content: TRAILER!!!",
message:
"cpio CRC disagrees with content: TRAILER!!! (Declared decoded cpio-byte-sum 00000001 disagrees with observed 00000000.)",
});
} finally {
await reader.close();
@@ -393,7 +412,7 @@ it("recovers directory CRC contradictions before yielding and reaches regular si
seen.push(entry.path);
if (entry.kind === "directory")
expect(entry.limitations).toContain(
"cpio CRC disagrees with content: dir",
"Declared decoded cpio-byte-sum 00000001 disagrees with observed 00000000.",
);
else
expect((await buffer(await reader.open(entry))).toString()).toBe("ok");
+2
View File
@@ -12,6 +12,7 @@ import {
} from "./ArtifactDecodedBudget.js";
import { artifactStreamPipeline } from "./ArtifactStreamPipeline.js";
import {
assertXarTocElements,
xarInteger as integer,
xarHeapPosition,
XarPathBudget,
@@ -486,6 +487,7 @@ export class XarArtifactReader implements ArtifactReader {
{ cause },
);
}
assertXarTocElements(xml);
} catch (cause: unknown) {
if (cause instanceof ArtifactReaderFailure) throw cause;
throw new ArtifactReaderFailure("format", "xar TOC is not zlib data", {
+24
View File
@@ -1,5 +1,29 @@
import { ArtifactReaderFailure } from "./ArtifactReader.js";
/**
* Element ceiling for one TOC. The byte cap still allows millions of tiny
* elements, and the DOM is built before member collection can charge the
* metadata budget.
*/
const MAX_TOC_ELEMENTS = 100_000;
/** Reject a TOC whose element count would materialize an unbounded DOM. */
export const assertXarTocElements = (xml: string): void => {
let elements = 0;
for (let index = 0; index < xml.length; index += 1) {
if (xml[index] !== "<") continue;
const next = xml[index + 1];
if (next === undefined || next === "/" || next === "?" || next === "!")
continue;
elements += 1;
if (elements > MAX_TOC_ELEMENTS)
throw new ArtifactReaderFailure(
"limit",
`xar TOC exceeds ${MAX_TOC_ELEMENTS} XML elements`,
);
}
};
/** Required XAR integer syntax: nonempty unsigned decimal, exactly representable. */
export const xarInteger = (
value: string | undefined,
@@ -154,7 +154,9 @@ it("preserves recovered directory CRC mismatches through graph materialization",
),
).toMatchObject({
hash_status: "mismatched",
limitations: ["cpio CRC disagrees with content: dir"],
limitations: [
"Declared decoded cpio-byte-sum 00000001 disagrees with observed 00000000.",
],
});
expect(
inventory.occurrences.find(