diff --git a/src/artifacts/MacosPkgArtifactReader.test.ts b/src/artifacts/MacosPkgArtifactReader.test.ts index 439aa4bffa..6c0949a39d 100644 --- a/src/artifacts/MacosPkgArtifactReader.test.ts +++ b/src/artifacts/MacosPkgArtifactReader.test.ts @@ -219,6 +219,63 @@ it("preserves an unresolved AppleDouble sidecar at a partial cpio boundary", () expect(parsed.members.at(-1)?.contents?.length).toBe(0); }); +it("resolves a maximum-size cpio hard-link group in one bounded pass", () => { + const members = Array.from({ length: 4096 }, (_, index) => ({ + name: `f${String(index)}`, + mode: 0o100644, + device: 7, + inode: 12, + links: 4096, + ...(index === 0 ? { data: Buffer.from("x") } : {}), + })); + const parsed = parseCpioOdcPrefix(buildCpioOdc(members)); + expect(parsed.failure).toBeNull(); + expect(parsed.aliasBytes).toBe(4095); + expect(parsed.members.at(-1)?.contents?.toString()).toBe("x"); +}); + +it("consumes a trailing AppleDouble sidecar so the next hard-link group resolves", () => { + const linked = { mode: 0o100644, device: 7, inode: 12, links: 2 }; + const metadata = Buffer.from( + "0005160700020000" + "00".repeat(16) + "00010000000200000026000000017a", + "hex", + ); + const parsed = parseCpioOdc( + buildCpioOdc([ + { ...linked, name: "a1", data: Buffer.from("A") }, + { ...linked, name: "a2" }, + { ...linked, name: "._a1", data: metadata }, + { ...linked, name: "b1", data: Buffer.from("B") }, + { ...linked, name: "b2" }, + { ...linked, name: "c1", data: Buffer.from("C") }, + ]), + ); + if (!parsed.ok) throw parsed.error; + const contents = new Map( + parsed.value.map((member) => [member.name, member.contents]), + ); + expect(contents.get("a2")?.toString()).toBe("A"); + expect(contents.get("b2")?.toString()).toBe("B"); + expect(contents.get("._a1")?.equals(metadata)).toBe(true); + expect(contents.get("c1")?.toString()).toBe("C"); +}); + +it("refuses cpio files with malformed hard-link identity fields", () => { + const archive = buildCpioOdc([ + { name: "first.txt", mode: 0o100644, data: Buffer.from("first") }, + { name: "second.txt", mode: 0o100644, device: 7, inode: 12, links: 2 }, + ]); + const secondHeader = CPIO_ODC_HEADER_BYTES + "first.txt\0".length + 5; + const badLinks = Buffer.from(archive); + badLinks.write("000008", secondHeader + 36, "ascii"); + const parsed = parseCpioOdcPrefix(badLinks); + expect(parsed.failure).not.toBeNull(); + expect(parsed.members.map((member) => member.name)).toEqual(["first.txt"]); + const badInode = Buffer.from(archive); + badInode.write("000009", secondHeader + 12, "ascii"); + expect(parseCpioOdc(badInode).ok).toBe(false); +}); + it("inventories a product archive's Distribution, scripts and payload", async () => { const { reader, entries, coverage } = await entriesOf(buildProductArchive()); try { @@ -941,6 +998,135 @@ it("charges decoded payload bytes against the shared expansion budget", async () } }); +it("charges cpio hard-link aliases against the expansion budget", async () => { + const body = Buffer.alloc(128 * 1024, 0x61); + const linked = { mode: 0o100644, device: 7, inode: 12, links: 2 }; + const pkg = buildXar({ + files: [ + { + path: "PackageInfo", + bytes: Buffer.from(``), + }, + { + path: "Payload", + bytes: gzipSync( + buildCpioOdc([ + { name: ".", mode: 0o040755 }, + { ...linked, name: "original.bin", data: body }, + { ...linked, name: "alias.bin" }, + ]), + ), + }, + ], + }); + // The decoded cpio fits in 192 KiB, but decoded plus alias bytes do not. + const skipped = await entriesOf(pkg, "alias-budget.pkg", 192 * 1024); + try { + const paths = skipped.entries.map((entry) => entry.path); + expect(paths).toContain("Payload"); + expect(paths).not.toContain("Payload/original.bin"); + expect(paths).not.toContain("Payload/alias.bin"); + expect(skipped.coverage).toEqual([ + expect.objectContaining({ + status: "unknown", + limitations: expect.arrayContaining([ + expect.stringContaining("Did not expand Scripts/Payload for Payload"), + ]), + }), + ]); + } finally { + await skipped.reader.close(); + } + const admitted = await entriesOf( + pkg, + "alias-budget-admitted.pkg", + 512 * 1024, + ); + try { + const alias = admitted.entries.find( + (entry) => entry.path === "Payload/alias.bin", + )!; + expect((await buffer(await admitted.reader.open(alias))).equals(body)).toBe( + true, + ); + } finally { + await admitted.reader.close(); + } +}); + +it("lets admitted cpio aliases exhaust the budget for a later component", async () => { + const body = Buffer.alloc(128 * 1024, 0x62); + const linked = { mode: 0o100644, device: 7, inode: 12, links: 2 }; + const pkg = buildXar({ + files: [ + { + path: "Distribution", + bytes: Buffer.from(` + + REA Alias Budget + #A.pkg + #B.pkg + +`), + }, + { path: "A.pkg", type: "directory" }, + { + path: "A.pkg/PackageInfo", + bytes: Buffer.from(``), + }, + { + path: "A.pkg/Payload", + bytes: gzipSync( + buildCpioOdc([ + { name: ".", mode: 0o040755 }, + { ...linked, name: "original.bin", data: body }, + { ...linked, name: "alias.bin" }, + ]), + ), + }, + { path: "B.pkg", type: "directory" }, + { + path: "B.pkg/PackageInfo", + bytes: Buffer.from(``), + }, + { + path: "B.pkg/Payload", + bytes: gzipSync( + buildCpioOdc([ + { name: ".", mode: 0o040755 }, + { name: "big.bin", mode: 0o100644, data: body }, + ]), + ), + }, + ], + }); + // A charges decoded plus alias bytes (~256 KiB), leaving too little of + // the 320 KiB budget for B's decoded payload (~128 KiB). + const { reader, entries, coverage } = await entriesOf( + pkg, + "alias-components.pkg", + 320 * 1024, + ); + try { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("A.pkg/Payload/alias.bin"); + expect(paths).toContain("B.pkg/Payload"); + expect(paths).not.toContain("B.pkg/Payload/big.bin"); + expect(coverage).toEqual([ + expect.objectContaining({ + status: "unknown", + limitations: expect.arrayContaining([ + expect.stringMatching( + /Did not expand Scripts\/Payload for B\.pkg\/Payload/u, + ), + ]), + }), + ]); + } finally { + await reader.close(); + } +}); + it("classifies a product archive as pkg and inventories it through the shared scan", async () => { const bytes = buildProductArchive(); const path = await writePkg("scan.pkg", bytes); diff --git a/src/artifacts/macosPkg/CpioOdc.ts b/src/artifacts/macosPkg/CpioOdc.ts index cdc889301e..e5039ac0f7 100644 --- a/src/artifacts/macosPkg/CpioOdc.ts +++ b/src/artifacts/macosPkg/CpioOdc.ts @@ -152,64 +152,10 @@ interface LinkGroup { readonly penalty: number; } -/** - * Classify one candidate group of same-inode records. AppleDouble records - * keep their own bytes and never donate or receive a data body. An empty - * `._` record counts as a sidecar only inside a group carrying validated - * AppleDouble metadata for a sibling in that same group; otherwise it is a - * data path in its own right. Returns null when the records do not form a - * complete, unambiguous group. - */ -const classifyLinkGroup = ( - members: readonly CpioMember[], - records: readonly LinkRecord[], -): LinkGroup | null => { - const linkCount = records[0]?.linkCount; - if (linkCount === undefined || linkCount < 2) return null; - if (records.some((record) => record.linkCount !== linkCount)) return null; - const definiteSidecars = new Set( - records.filter((record) => { - const member = members[record.index]!; - return ( - appleDoubleBase(member) !== null && - hasAppleDoubleHeader(member.contents) - ); - }), - ); - const firstDefinite = records.findIndex((record) => - definiteSidecars.has(record), - ); - const data: LinkRecord[] = []; - let penalty = 0; - for (const [position, record] of records.entries()) { - if (definiteSidecars.has(record)) continue; - const member = members[record.index]!; - const base = appleDoubleBase(member); - if (firstDefinite !== -1 && base !== null && member.size === 0) { - const sibling = records.some( - (other) => - !definiteSidecars.has(other) && - normalizedMemberName(members[other.index]!) === base, - ); - // A sidecar whose data sibling is outside the group may belong to a - // record the archive has not shown; preserve that uncertainty. - if (!sibling) return null; - if (position < firstDefinite) penalty += 1; - continue; - } - data.push(record); - } - for (const record of definiteSidecars) { - const base = appleDoubleBase(members[record.index]!); - if ( - !data.some( - (other) => normalizedMemberName(members[other.index]!) === base, - ) - ) - return null; - } - return data.length === linkCount ? { data, penalty } : null; -}; +interface LinkCandidate { + readonly end: number; + readonly group: LinkGroup; +} const resolveLinkGroup = (members: CpioMember[], group: LinkGroup): number => { const bodies = group.data.map((record) => members[record.index]!.contents!); @@ -229,77 +175,274 @@ const resolveLinkGroup = (members: CpioMember[], group: LinkGroup): number => { return aliasBytes; }; +interface LinkSidecar { + readonly base: string; + readonly definite: boolean; + readonly position: number; +} + +interface LinkScan { + readonly linkCount: number; + readonly data: readonly LinkRecord[]; + readonly dataNames: ReadonlySet; + readonly nonSidecarNames: ReadonlySet; + readonly sidecars: readonly LinkSidecar[]; + readonly definiteCount: number; + readonly firstDefinite: number; + readonly early: LinkCandidate | null; + readonly end: number; + readonly complete: boolean; +} + +const sidecarsValid = ( + entries: readonly LinkSidecar[], + dataNames: ReadonlySet, + siblingNames: ReadonlySet, +): boolean => + entries.every((entry) => + entry.definite ? dataNames.has(entry.base) : siblingNames.has(entry.base), + ); + +const penaltyBefore = ( + entries: readonly LinkSidecar[], + first: number, +): number => + entries.filter((entry) => !entry.definite && entry.position < first).length; + +/** Scan one candidate group, stopping when its data records complete it. */ +const scanLinkGroup = ( + members: CpioMember[], + records: readonly LinkRecord[], + start: number, + spend: () => boolean, +): LinkScan | null => { + const linkCount = records[start]!.linkCount; + const data: LinkRecord[] = []; + const nonSidecar: LinkRecord[] = []; + const dataNames = new Set(); + const nonSidecarNames = new Set(); + const sidecars: LinkSidecar[] = []; + let definiteCount = 0; + let firstDefinite = -1; + let early: LinkCandidate | null = null; + let end = start; + let complete = false; + for (let index = start; index < records.length; index += 1) { + if (!spend()) return null; + const record = records[index]!; + if (record.linkCount !== linkCount) break; + const member = members[record.index]!; + const base = appleDoubleBase(member); + const definite = base !== null && hasAppleDoubleHeader(member.contents); + if (definite) { + definiteCount += 1; + if (firstDefinite === -1) firstDefinite = index; + sidecars.push({ base, definite: true, position: index }); + } else { + nonSidecar.push(record); + nonSidecarNames.add(normalizedMemberName(member)); + if (base !== null && member.size === 0) { + sidecars.push({ base, definite: false, position: index }); + } else { + data.push(record); + dataNames.add(normalizedMemberName(member)); + } + } + if ( + early === null && + definiteCount === 0 && + nonSidecar.length === linkCount + ) + early = { end: index + 1, group: { data: [...nonSidecar], penalty: 0 } }; + if (data.length === linkCount) { + end = index + 1; + complete = true; + break; + } + } + return { + linkCount, + data, + dataNames, + nonSidecarNames, + sidecars, + definiteCount, + firstDefinite, + early, + end, + complete, + }; +}; + +/** + * A complete group owns the sidecars that trail it; leaving one at the + * next boundary would strand it and block the following group. + */ +const trailingLinkCandidate = ( + members: CpioMember[], + records: readonly LinkRecord[], + scan: LinkScan, + spend: () => boolean, +): LinkCandidate | null => { + const trailing = [...scan.sidecars]; + const trailingNames = new Set(scan.nonSidecarNames); + let trailingFirst = scan.firstDefinite; + let trailingEnd = scan.end; + for (let index = scan.end; index < records.length; index += 1) { + if (!spend()) break; + const record = records[index]!; + if (record.linkCount !== scan.linkCount) break; + const member = members[record.index]!; + const base = appleDoubleBase(member); + const definite = base !== null && hasAppleDoubleHeader(member.contents); + const tentative = base !== null && member.size === 0; + if (!definite && !tentative) break; + if (definite ? !scan.dataNames.has(base) : !trailingNames.has(base)) break; + trailing.push({ base, definite, position: index }); + if (tentative) trailingNames.add(normalizedMemberName(member)); + if (definite && trailingFirst === -1) trailingFirst = index; + trailingEnd = index + 1; + } + if ( + trailingEnd === scan.end || + trailingFirst === -1 || + !sidecarsValid(trailing, scan.dataNames, trailingNames) + ) + return null; + return { + end: trailingEnd, + group: { + data: [...scan.data], + penalty: penaltyBefore(trailing, trailingFirst), + }, + }; +}; + +const linkCandidatesAt = ( + members: CpioMember[], + records: readonly LinkRecord[], + start: number, + spend: () => boolean, +): LinkCandidate[] => { + if (start >= records.length || records[start]!.linkCount < 2) return []; + const scan = scanLinkGroup(members, records, start, spend); + if (scan === null) return []; + if (!scan.complete) return scan.early === null ? [] : [scan.early]; + const candidates: LinkCandidate[] = []; + if (scan.early !== null) candidates.push(scan.early); + if ( + scan.definiteCount > 0 && + sidecarsValid(scan.sidecars, scan.dataNames, scan.nonSidecarNames) + ) + candidates.push({ + end: scan.end, + group: { + data: [...scan.data], + penalty: penaltyBefore(scan.sidecars, scan.firstDefinite), + }, + }); + const trailing = trailingLinkCandidate(members, records, scan, spend); + if (trailing !== null) candidates.push(trailing); + return candidates; +}; + /** * Resolve single-body hard-link aliases for one device/inode sequence. * Writers can reuse the inode after a complete group, so the sequence is - * partitioned into complete groups. A partition that needs a later - * AppleDouble header to reclassify an earlier ordinary `._` file loses to - * one that completes that file's own group first. + * partitioned into complete groups. AppleDouble records keep their own + * bytes and never donate or receive a data body: an empty `._` record + * counts as a sidecar only inside a group carrying validated AppleDouble + * metadata for a sibling in that same group, and a partition that needs a + * later AppleDouble header to reclassify an earlier ordinary `._` file + * loses to one that completes that file's own group first. + * + * Each group boundary offers at most three candidates (the group + * completing with empty `._` records as data, the group completing on + * definite data records, and that group plus its trailing owned + * sidecars), each found by one forward scan. Boundaries are visited once + * and total scan work is capped linearly in the record count, so a + * package-controlled link group cannot monopolize CPU. Among candidate + * partitions the resolver prefers the one resolving the longest prefix, + * then the lowest penalty, then the candidate consuming trailing + * sidecars. */ const resolveHardLinks = ( members: CpioMember[], records: readonly LinkRecord[], ): number => { - const candidates = new Map>(); - for (let start = 0; start < records.length; start += 1) { - const linkCount = records[start]!.linkCount; - let definiteData = 0; - for (let end = start + 1; end <= records.length; end += 1) { - const record = records[end - 1]!; - if (record.linkCount !== linkCount) break; - const member = members[record.index]!; - const definiteSidecar = - appleDoubleBase(member) !== null && - hasAppleDoubleHeader(member.contents); - const tentativeSidecar = - appleDoubleBase(member) !== null && member.size === 0; - if (!definiteSidecar && !tentativeSidecar) definiteData += 1; - if (definiteData > linkCount) break; - if (end - start > 4 * linkCount + 8) break; - const group = classifyLinkGroup(members, records.slice(start, end)); - if (group !== null) { - const byEnd = candidates.get(start) ?? new Map(); - byEnd.set(end, group); - candidates.set(start, byEnd); + if (records.length === 0) return 0; + let budget = 64 * records.length + 1024; + const spend = (): boolean => { + budget -= 1; + return budget >= 0; + }; + const cache = new Map(); + const candidates = (start: number): LinkCandidate[] => { + const cached = cache.get(start); + if (cached !== undefined) return cached; + const found = linkCandidatesAt(members, records, start, spend); + cache.set(start, found); + return found; + }; + const reachable = new Set([0]); + const stack = [0]; + while (stack.length > 0) { + const start = stack.pop()!; + for (const candidate of candidates(start)) { + if (!reachable.has(candidate.end)) { + reachable.add(candidate.end); + stack.push(candidate.end); } } } - const best = new Map(); - best.set(records.length, { penalty: 0, next: records.length }); - for (let start = records.length - 1; start >= 0; start -= 1) { - for (const [end, group] of candidates.get(start) ?? []) { - const rest = best.get(end); - if (rest === undefined) continue; - const penalty = group.penalty + rest.penalty; - const current = best.get(start); + interface Best { + readonly reach: number; + readonly penalty: number; + readonly next: number; + readonly group: LinkGroup | null; + } + const best = new Map(); + best.set(records.length, { + reach: records.length, + penalty: 0, + next: records.length, + group: null, + }); + for (const start of [...reachable].sort((a, b) => b - a)) { + if (start === records.length) continue; + let chosen: Best = { reach: start, penalty: 0, next: start, group: null }; + for (const candidate of candidates(start)) { + const rest = best.get(candidate.end) ?? { + reach: candidate.end, + penalty: 0, + next: candidate.end, + group: null, + }; + const penalty = candidate.group.penalty + rest.penalty; if ( - current === undefined || - penalty < current.penalty || - (penalty === current.penalty && end < current.next) + rest.reach > chosen.reach || + (rest.reach === chosen.reach && + (chosen.group === null || + penalty < chosen.penalty || + (penalty === chosen.penalty && candidate.end > chosen.next))) ) - best.set(start, { penalty, next: end }); + chosen = { + reach: rest.reach, + penalty, + next: candidate.end, + group: candidate.group, + }; } + best.set(start, chosen); } let aliasBytes = 0; let start = 0; while (start < records.length) { const chosen = best.get(start); - if (chosen !== undefined && chosen.next > start) { - aliasBytes += resolveLinkGroup( - members, - candidates.get(start)!.get(chosen.next)!, - ); - start = chosen.next; - continue; - } - // No partition covers the rest: resolve a complete leading group if - // one exists, then leave the remainder exactly as recorded. - const leading = [...(candidates.get(start) ?? [])].sort( - (a, b) => a[1].penalty - b[1].penalty || a[0] - b[0], - )[0]; - if (leading === undefined) break; - aliasBytes += resolveLinkGroup(members, leading[1]); - start = leading[0]; + if (chosen === undefined || chosen.group === null || chosen.next <= start) + break; + aliasBytes += resolveLinkGroup(members, chosen.group); + start = chosen.next; } return aliasBytes; }; @@ -467,9 +610,12 @@ const parseCpioOdcInto = ( } else if (kind === "file") contents = Buffer.from(body); if (kind === "file" && contents !== null) { const links = octalField(header, 36, 6, "nlink"); + if (!links.ok) return links; const device = octalField(header, 6, 6, "dev"); + if (!device.ok) return device; const inode = octalField(header, 12, 6, "ino"); - if (links.ok && device.ok && inode.ok && links.value > 1) { + if (!inode.ok) return inode; + if (links.value > 1) { const key = `${String(device.value)}:${String(inode.value)}`; const records = hardLinks.get(key) ?? []; records.push({ index: members.length, linkCount: links.value });