/** * T8 (STEP6 §6, §15): a hostile or oversized snapshot never sinks the * report on import and never produces an unreadable file on export; hostile * SVG content is removed, refused or clamped; the real assets pass the * sanitiser untouched; the inflate bomb guard stays. */ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { deflateSync } from 'node:zlib' import { beforeAll, describe, expect, it, vi } from 'vitest' import { PDFDict, PDFDocument, PDFName } from 'pdf-lib' import { assertSnapshot, SnapshotError, type Branding, type Report, type ReportArchiveEnvelope, type SheetSnapshot, } from '@faunosteo/domain' import { ArchiveExportError, defaultPdfLabels, exportFromEnvelope, exportReportArchive, readReportArchive, type ExportInput, type Rasterizer, } from '../src' import { inflateFlate } from '../src/attachment/inflate' import { pngIssue } from '../src/branding' import { SvgRejectedError } from '../src/errors' import { addLinkAnnotation } from '../src/render/linkAnnotation' import { parseSvg, serializeSvg } from '../src/svg/parse' import { sanitizeSvgRoot } from '../src/svg/sanitize' import { rasterSizeOf } from '../src/svg/view' import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft' import { FIXED_EXPORTED_AT, logosBranding, nologosBranding, ONE_PX_PNG, rasterizerOf, readLinks, recordDrawing, TWO_BY_ONE_PNG, } from './helpers/goldens' import { pdfWithAttachment } from './helpers/pdf' import { loadGoldenReports, type GoldenReports } from './helpers/reports' let golden: GoldenReports let envelope: ReportArchiveEnvelope const clone = (value: T): T => JSON.parse(JSON.stringify(value)) as T function baseInput(report: Report, sheet: SheetSnapshot): ExportInput { return { report, sheet, branding: nologosBranding(), labels: defaultPdfLabels, locale: 'fr', rasterizer: rasterizerOf('nologos'), exportedAt: FIXED_EXPORTED_AT, } } beforeAll(async () => { golden = loadGoldenReports() envelope = ( await exportReportArchive( baseInput(golden.reports.demo, golden.snapshots.demo), ) ).envelope }) /** The reason the domain gate gives: the oracle the engine must surface. */ function domainReason(snapshot: unknown): string { try { assertSnapshot(snapshot) return 'accepted' } catch (error) { if (error instanceof SnapshotError) return error.reason throw error } } type Mutation = (snapshot: SheetSnapshot) => void const UUID = (i: number) => `00000000-0000-4000-8000-00000000000${i}` const MUTATIONS: Array<[string, string, Mutation]> = [ [ '5 assets', 'schema', (s) => { s.assets = Array.from({ length: 5 }, (_, i) => ({ ...s.assets[0]!, svgAssetId: i === 0 ? s.assets[0]!.svgAssetId : UUID(i), })) }, ], [ 'a 3 MiB asset', 'caps', (s) => { s.assets[0]!.svg = 'é'.repeat(1_100_000) }, ], [ 'finding depth 9', 'caps', (s) => { const leaf = { id: 'deep', name: { fr: 'x', en: 'x' }, description: {}, requires_vet_referral: false, reference_ids: [], review_status: 'inherited' as const, children: [] as never[], } let node: typeof leaf = leaf for (let depth = 0; depth < 9; depth += 1) { node = { ...leaf, id: `n${depth}`, children: [node] as never[] } } const zone = s.document.finding_zones.find((z) => z.categories.length)! zone.categories[0]!.children.push(node) }, ], [ '1,025 annotations', 'caps', (s) => { s.document.annotations.push( ...Array.from({ length: 1025 }, (_, i) => ({ ...s.document.annotations[0]!, id: `extra-${i}`, })), ) }, ], [ 'a view chain cycle', 'integrity', (s) => { const head = s.document.views.find((v) => v.id === 'head')! if (head.kind === 'detail') head.parent_view_id = 'head' }, ], [ 'a dangling svg_asset_id', 'integrity', (s) => { s.document.views.find((v) => v.kind === 'main')!.svg_asset_id = UUID(9) }, ], [ 'another sheet (sheet_mismatch)', 'sheet_mismatch', (s) => { s.ref.documentSha256 = 'f'.repeat(64) }, ], ] describe('import: the report survives a rejected snapshot', () => { it.each(MUTATIONS)( '%s → %s', async (_name, reason, mutate) => { const hostile = clone(envelope) mutate(hostile.sheetSnapshot) if (reason !== 'sheet_mismatch') { expect(domainReason(hostile.sheetSnapshot)).toBe(reason) } const bytes = await pdfWithAttachment('osteo-report.json', hostile) const outcome = await readReportArchive(bytes, golden.draft.migrationMap) expect(outcome.report).toEqual(golden.reports.demo) expect(outcome.origin).toBe('envelope_v1') expect(outcome.archive).toBeNull() expect(outcome.snapshotRejected).toBe(reason) }, 20_000, ) }) describe('export: a snapshot over the caps fails with a typed error and no file', () => { it.each([ ['1,025 annotations', 'snapshot_too_large', MUTATIONS[3]![2]], ['a 3 MiB asset', 'snapshot_too_large', MUTATIONS[1]![2]], ['5 assets', 'snapshot_invalid', MUTATIONS[0]![2]], ['a dangling svg_asset_id', 'snapshot_invalid', MUTATIONS[5]![2]], ['another sheet', 'sheet_mismatch', MUTATIONS[6]![2]], ] as const)('%s → %s', async (_name, kind, mutate) => { const sheet = clone(golden.snapshots.demo) mutate(sheet) const promise = exportReportArchive(baseInput(golden.reports.demo, sheet)) await expect(promise).rejects.toBeInstanceOf(ArchiveExportError) await expect(promise).rejects.toMatchObject({ kind }) }) it('too many observations or views per observation → too_many_pages', async () => { const demo = golden.reports.demo const many = { ...demo, observations: Array.from({ length: 501 }, (_, i) => ({ ...demo.observations[0]!, id: `o${i}`, })), } await expect( exportReportArchive(baseInput(many, golden.snapshots.demo)), ).rejects.toMatchObject({ kind: 'too_many_pages' }) const views = { ...demo, observations: [ { ...demo.observations[0]!, zones: Array.from({ length: 9 }, (_, i) => ({ annotationId: 'c7-t1', viewId: `v${i}`, })), }, ], } await expect( exportReportArchive(baseInput(views, golden.snapshots.demo)), ).rejects.toMatchObject({ kind: 'too_many_pages' }) }) }) // --------------------------------------------------------------------------- // Hostile SVG const SVG_OPEN = '' const wrap = (inner: string) => `${SVG_OPEN}${inner}` /** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */ async function exportWithAsset(svg: string): Promise { const sheet = clone(golden.snapshots.demo) sheet.assets[0]!.svg = svg const seen: string[] = [] const rasterizer: Rasterizer = async (text) => { seen.push(text) return ONE_PX_PNG } const report = { ...golden.reports.demo, observations: [golden.reports.demo.observations[0]!], } const { warnings } = await exportReportArchive({ ...baseInput(report, sheet), rasterizer, }) expect(warnings).toEqual([]) return seen } describe('hostile SVG assets', () => { it('' + '' + '' + '' + '' + '' + '', ), ) expect(seen).toBeDefined() for (const forbidden of [ '') expect(seen).toContain('') expect(seen).toContain('fill="#b85a3f"') }) it('the sanitiser names what it removed and clamps stdDeviation', () => { const root = parseSvg( wrap( '' + '' + '', ), ) const { removed } = sanitizeSvgRoot(root) expect(removed).toEqual([ 'script', 'g@onclick', 'g@data-x', 'path@style', 'feTurbulence', 'use@xlink:href', 'a', ]) expect(serializeSvg(root)).toContain('stdDeviation="100 3"') }) it('CSS escapes, image-set and function calls in style or presentation attributes are removed', () => { const root = parseSvg( wrap( '' + `` + '' + '' + '' + '', ), ) const { removed } = sanitizeSvgRoot(root) expect(removed).toEqual([ 'path@style', 'path@style', 'path@fill', 'path@fill', 'path@id', ]) const out = serializeSvg(root) expect(out).not.toContain('evil') expect(out).not.toContain('rgb(') expect(out).toContain('fill="url(#ok)" transform="translate(1 2)"') }) it('a non-finite or empty viewBox falls back to the 0.6 ratio, never NaN', () => { for (const viewBox of [ '0 0 1e999 1e999', '0 0 Infinity 10', '0 0 NaN 10', '0 0 0 10', '0 0 -5 10', '', ]) { const size = rasterSizeOf(viewBox) expect(size, viewBox).toEqual({ widthPx: 1200, heightPx: 720 }) expect(Number.isFinite(size.heightPx)).toBe(true) } }) it(' and 257 are refused: the export fails as snapshot_invalid', async () => { const entity = ']>' + wrap('&x;') await expect(exportWithAsset(entity)).rejects.toMatchObject({ kind: 'snapshot_invalid', }) const uses = (count: number) => wrap( '' + ''.repeat(count), ) await expect(exportWithAsset(uses(257))).rejects.toMatchObject({ kind: 'snapshot_invalid', }) expect(() => sanitizeSvgRoot(parseSvg(uses(257)))).toThrow(SvgRejectedError) await expect(exportWithAsset(uses(256))).resolves.toHaveLength(1) }) it('a huge root viewBox is clamped to a 1200×2400 raster', async () => { expect(rasterSizeOf('0 0 1 100000')).toEqual({ widthPx: 1200, heightPx: 2400, }) expect(rasterSizeOf('0 0 100000 1')).toEqual({ widthPx: 1200, heightPx: 240, }) expect(rasterSizeOf(null)).toEqual({ widthPx: 1200, heightPx: 720 }) const sizes: Array<{ widthPx: number; heightPx: number }> = [] const branding = nologosBranding() branding.partner!.logo = { kind: 'svg', svg: '', } await exportReportArchive({ ...baseInput(golden.reports.demo, golden.snapshots.demo), branding, rasterizer: async (_svg, size) => { sizes.push(size) return ONE_PX_PNG }, }) expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 }) }) it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => { for (const file of [ resolve(DRAFT_DIR, 'assets/horse.svg'), resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'), ]) { const text = readFileSync(file, 'utf8') const pristine = serializeSvg(parseSvg(text)) const root = parseSvg(text) expect(sanitizeSvgRoot(root)).toEqual({ removed: [] }) expect(serializeSvg(root)).toBe(pristine) } }) }) describe('__proto__ ids and the inflate bomb', () => { it('report ids named __proto__ print raw and pollute nothing', async () => { const demo = golden.reports.demo const report: Report = { ...demo, observations: [ { ...demo.observations[0]!, zones: [{ annotationId: '__proto__', viewId: 'main' }], findings: [ { findingZoneId: '__proto__', path: ['__proto__'], labelFrSnapshot: 'proto fr', labelEnSnapshot: 'proto en', }, ], }, ], } const recording = recordDrawing() try { const { warnings } = await exportReportArchive( baseInput(report, golden.snapshots.demo), ) expect(warnings).toEqual([]) const drawn = recording.texts.map((t) => t.text) expect(drawn).toContain('__proto__') expect(drawn).toContain('CONSTATS — __PROTO__') expect(drawn).toContain('proto fr') } finally { recording.stop() } expect(Object.keys(Object.prototype)).toEqual([]) expect(({} as Record).polluted).toBeUndefined() }) async function deflate(data: Uint8Array): Promise { const stream = new Blob([data]) .stream() .pipeThrough(new CompressionStream('deflate')) return new Uint8Array(await new Response(stream).arrayBuffer()) } it('inflates a normal payload and returns null for a 24 MB bomb', async () => { const payload = new TextEncoder().encode(JSON.stringify({ version: 2 })) const out = await inflateFlate(await deflate(payload)) expect(new TextDecoder().decode(out!)).toContain('version') const bomb = await deflate(new Uint8Array(24 * 1024 * 1024)) expect(bomb.byteLength).toBeLessThan(1024 * 1024) expect(await inflateFlate(bomb)).toBeNull() }) }) // --------------------------------------------------------------------------- // Branding: URL injection at the link sink, PNG budget /** Closes the `/URI (` literal and chains a JavaScript action when written unescaped. */ const INJECTION_URL = 'https://a.example/) /Next << /S /JavaScript /JS (app.alert\\(1\\)) >> /Z (' /** Every dictionary of the loaded file whose `/S` is `JavaScript`. */ function javaScriptActions(doc: PDFDocument): PDFDict[] { return doc.context .enumerateIndirectObjects() .map(([, object]) => object) .filter((object): object is PDFDict => object instanceof PDFDict) .filter((dict) => dict.get(PDFName.of('S')) === PDFName.of('JavaScript')) } function reexportOptions() { return { locale: 'fr' as const, rasterizer: rasterizerOf('nologos'), exportedAt: FIXED_EXPORTED_AT, } } /** The same payload without spaces: PDF syntax needs none, and the sink lets it through to the hex string. */ const TIGHT_INJECTION_URL = INJECTION_URL.replaceAll(' ', '') /** The saved bytes of a one-page PDF holding one link to `url`, objects uncompressed so the bytes can be read. */ async function savedLink(url: string): Promise { const doc = await PDFDocument.create() addLinkAnnotation(doc.addPage(), { x: 0, y: 0, width: 10, height: 10, url }) return doc.save({ useObjectStreams: false }) } /** `` of the URL's ASCII bytes, as the sink must write `/URI`. */ const asciiHex = (url: string): string => Array.from(url, (c) => c.charCodeAt(0).toString(16).padStart(2, '0')).join('') describe('branding URL injection (HIGH)', () => { it('writes /URI as the hex of the ASCII bytes, no UTF-16 BOM, and reloads to the URL', async () => { const url = 'https://faunosteo.com' const bytes = await savedLink(url) const raw = Buffer.from(bytes).toString('latin1') const uriMatch = /\/URI\s*<([0-9A-Fa-f]+)>/.exec(raw) expect(uriMatch?.[1]?.toLowerCase()).toBe(asciiHex(url)) expect(uriMatch?.[1]?.toUpperCase().startsWith('FEFF')).toBe(false) expect(Buffer.from(uriMatch![1]!, 'hex').toString('latin1')).toBe(url) const [link] = await readLinks(bytes) expect(link?.uri).toBe(url) }) it('a URL with a code point above 0x7e or below 0x21 throws branding_invalid at the sink', async () => { for (const url of [ 'https://faunosté.com', 'https://a.example/ b', INJECTION_URL, 'https://a.example/\u00ff', ]) { await expect(savedLink(url), url).rejects.toMatchObject({ kind: 'branding_invalid', }) await expect(savedLink(url), url).rejects.toBeInstanceOf( ArchiveExportError, ) } }) it('the link sink alone keeps the whole URL inside the /URI string', async () => { const bytes = await savedLink(TIGHT_INJECTION_URL) const raw = Buffer.from(bytes).toString('latin1') expect(raw).not.toContain('/JavaScript') expect(raw).not.toContain('/Next') expect(raw).not.toContain('/JS') const reloaded = await PDFDocument.load(bytes) expect(javaScriptActions(reloaded)).toEqual([]) const action = reloaded .getPage(0) .node.Annots()! .lookup(0, PDFDict) .lookup(PDFName.of('A'), PDFDict) expect(action.has(PDFName.of('Next'))).toBe(false) expect(action.get(PDFName.of('S'))).toBe(PDFName.of('URI')) const [link] = await readLinks(bytes) expect(link?.uri).toBe(TIGHT_INJECTION_URL) }) it('exportFromEnvelope refuses the URL before drawing anything: branding_invalid', async () => { const hostile = clone(envelope) hostile.branding = { ...hostile.branding, siteUrl: INJECTION_URL, } as unknown as Branding const recording = recordDrawing() try { const promise = exportFromEnvelope(hostile, reexportOptions()) await expect(promise).rejects.toBeInstanceOf(ArchiveExportError) await expect(promise).rejects.toMatchObject({ kind: 'branding_invalid' }) expect(recording.texts).toEqual([]) expect(recording.images).toEqual([]) } finally { recording.stop() } }) it('a credit URL with a parenthesis and a broken label set are refused the same way', async () => { const credit = clone(envelope) credit.branding.partner!.url = 'https://a.example/)' await expect( exportFromEnvelope(credit, reexportOptions()), ).rejects.toMatchObject({ kind: 'branding_invalid' }) const labels = clone(envelope) delete (labels.labels.fr as Record)['pdf.subject'] await expect( exportFromEnvelope(labels, reexportOptions()), ).rejects.toMatchObject({ kind: 'branding_invalid' }) await expect( exportFromEnvelope(clone(envelope), reexportOptions()), ).resolves.toMatchObject({ warnings: [] }) }) }) interface IhdrFields { depth?: number colourType?: number compression?: number filter?: number interlace?: number } const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] /** * A PNG signature and an IHDR chunk announcing `width` × `height`, 8-bit * greyscale non-interlaced unless `fields` says otherwise, nothing after. */ function pngHeader( width: number, height: number, fields: IhdrFields = {}, signature = true, ): Uint8Array { const bytes = new Uint8Array(33) bytes.set(PNG_SIGNATURE) if (!signature) bytes[3] = 0x48 const view = new DataView(bytes.buffer) view.setUint32(8, 13) bytes.set([0x49, 0x48, 0x44, 0x52], 12) view.setUint32(16, width) view.setUint32(20, height) const { depth = 8, colourType = 0, compression = 0 } = fields const { filter = 0, interlace = 0 } = fields bytes.set([depth, colourType, compression, filter, interlace], 24) return bytes } /** One chunk: length, four-letter type, `data`, a zero CRC. */ function pngChunk(type: string, data: Uint8Array): Uint8Array { const bytes = new Uint8Array(12 + data.byteLength) new DataView(bytes.buffer).setUint32(0, data.byteLength) bytes.set( Array.from(type, (c) => c.charCodeAt(0)), 4, ) bytes.set(data, 8) return bytes } const concat = (...parts: Uint8Array[]): Uint8Array => Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p)))) const CHANNELS: Record = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 } /** Raw scanlines of a non-interlaced image: a filter byte then the packed samples, per row. */ function rawSize( width: number, height: number, fields: IhdrFields = {}, ): number { const { depth = 8, colourType = 0 } = fields const bitsPerPixel = CHANNELS[colourType]! * depth return (Math.ceil((width * bitsPerPixel) / 8) + 1) * height } /** An IDAT chunk holding the zlib stream of `raw`. */ const idatOf = (raw: Uint8Array): Uint8Array => pngChunk('IDAT', deflateSync(raw)) const IEND = pngChunk('IEND', new Uint8Array(0)) /** The IDAT of a 1×1 8-bit greyscale image (2 raw bytes), what `pngHeader(1, 1)` announces. */ const IDAT = idatOf(new Uint8Array(2)) /** A complete valid PNG of zero pixels: header, one IDAT of the exact raw size, IEND. */ function validPng( width: number, height: number, fields: IhdrFields = {}, ): Uint8Array { const raw = new Uint8Array(rawSize(width, height, fields)) return concat(pngHeader(width, height, fields), idatOf(raw), IEND) } /** A 1×1 header followed by a second IHDR announcing 10000 × 10000, then IEND. */ function doubledIhdrPng(): Uint8Array { const second = pngHeader(10_000, 10_000).subarray(8) return concat(pngHeader(1, 1), second, IEND) } /** * The auditor's PoC: a valid 1×1 PNG whose IEND is replaced by a `tEXt` * chunk "AAAA" with a non-zero CRC and no NUL byte, so UPNG's `nextZero` * never stops (`ONE_PX_PNG` minus its 12-byte IEND). */ function textWithoutNulPng(): Uint8Array { const text = pngChunk('tEXt', new TextEncoder().encode('AAAA')) text.fill(0xff, text.byteLength - 4) return concat(ONE_PX_PNG.subarray(0, ONE_PX_PNG.byteLength - 12), text) } /** The second PoC: an `iTXt` chunk, then an IEND of length 0x010101 with a non-zero payload. */ function itxtThenFatIendPng(): Uint8Array { const itxt = pngChunk('iTXt', new TextEncoder().encode('kw')) const fatIend = pngChunk('IEND', new Uint8Array(0x010101).fill(1)) return concat(pngHeader(1, 1), IDAT, itxt, fatIend) } /** * The third PoC, 77 bytes: 16×16 RGBA, a zlib IDAT cut to 20 bytes, IEND. * Signature and chunk list are sound; UPNG's `inflateRaw` reads past the * end of the stream and never returns. */ function truncatedIdatPng(): Uint8Array { const raw = Uint8Array.from( { length: rawSize(16, 16, { colourType: 6 }) }, (_, i) => i & 0xff, ) const stream = deflateSync(raw).subarray(0, 20) const header = pngHeader(16, 16, { colourType: 6 }) return concat(header, pngChunk('IDAT', stream), IEND) } interface Chunk { type: string data: Uint8Array } /** The chunks of a well-formed PNG, in file order, CRCs dropped. */ function chunksOf(png: Uint8Array): Chunk[] { const view = new DataView(png.buffer, png.byteOffset, png.byteLength) const chunks: Chunk[] = [] let offset = 8 while (offset < png.byteLength) { const length = view.getUint32(offset) const type = String.fromCharCode(...png.subarray(offset + 4, offset + 8)) chunks.push({ type, data: png.subarray(offset + 8, offset + 8 + length) }) offset += 12 + length } return chunks } const pngOf = (chunks: Chunk[]): Uint8Array => concat( Uint8Array.from(PNG_SIGNATURE), ...chunks.map((c) => pngChunk(c.type, c.data)), ) function headerLogoBytes(): Uint8Array { const asset = logosBranding().headerLogo if (asset?.kind !== 'png') throw new Error('png expected') return Uint8Array.from(Buffer.from(asset.base64, 'base64')) } /** The real header logo with the last 5 bytes of its IDAT stream removed: the chunk list stays sound. */ function cutLogoPng(): Uint8Array { const chunks = chunksOf(headerLogoBytes()) const last = chunks.filter((c) => c.type === 'IDAT').at(-1)! last.data = last.data.subarray(0, last.data.byteLength - 5) return pngOf(chunks) } describe('PNG budget (MEDIUM)', () => { it.each([ ['8193 × 1', 8193, 1], ['1 × 8193', 1, 8193], ['4097 × 4096 (over 4096²)', 4097, 4096], ['12000 × 12000 (144 Mpx)', 12_000, 12_000], ['0 × 0', 0, 0], ['1 × 0', 1, 0], ['8192 × 0', 8192, 0], ])('%s → dimensions', async (_name, width, height) => { const png = concat(pngHeader(width, height), IEND) expect(await pngIssue(png)).toBe('dimensions') }) it('the raw-size budget: 16 MiB of scanlines at most, whatever the pixel count', async () => { // 1-bit grey: 513 bytes a row. expect(await pngIssue(validPng(4096, 4096, { depth: 1 }))).toBeNull() expect(await pngIssue(validPng(8192, 2048, { depth: 1 }))).toBeNull() // 8-bit grey: (4095 + 1) × 4096 is exactly 16 MiB, one more row byte is over. expect(await pngIssue(validPng(4095, 4096))).toBeNull() const overByARow = concat(pngHeader(4096, 4096), IEND) expect(await pngIssue(overByARow)).toBe('dimensions') // 8-bit RGBA at 4096²: 67 MB of scanlines, refused before any inflation. const rgba = concat(pngHeader(4096, 4096, { colourType: 6 }), IEND) expect(await pngIssue(rgba)).toBe('dimensions') expect(rawSize(4096, 4096, { colourType: 6 })).toBeGreaterThan( 16 * 1024 * 1024, ) }) it.each([ ['depth 255', { depth: 255 }], ['colour type 5', { colourType: 5 }], ['interlace 1 (Adam7)', { interlace: 1 }], ['filter method 1', { filter: 1 }], ['compression method 1', { compression: 1 }], ['depth 4 for RGBA', { depth: 4, colourType: 6 }], ['depth 16 for a palette', { depth: 16, colourType: 3 }], ])('%s → ihdr', async (_name, fields: IhdrFields) => { expect(await pngIssue(validPng(4, 3, fields))).toBe('ihdr') const atTheCap = concat(pngHeader(4096, 4096, fields), IEND) expect(await pngIssue(atTheCap)).toBe('ihdr') }) it('every colour type and depth the spec allows passes with a matching IDAT', async () => { const allowed: Array<[number, number[]]> = [ [0, [1, 2, 4, 8, 16]], [2, [8, 16]], [3, [1, 2, 4, 8]], [4, [8, 16]], [6, [8, 16]], ] for (const [colourType, depths] of allowed) { for (const depth of depths) { const png = validPng(5, 3, { depth, colourType }) expect( await pngIssue(png), `type ${colourType} depth ${depth}`, ).toBeNull() } } }) it('an IDAT stream that is truncated, empty, not zlib or off by one raw byte → idat', async () => { const poc = truncatedIdatPng() expect(poc.byteLength).toBe(77) expect(await pngIssue(poc)).toBe('idat') expect(await pngIssue(cutLogoPng())).toBe('idat') expect(await pngIssue(concat(pngHeader(1, 1), IEND))).toBe('idat') const notZlib = pngChunk('IDAT', new Uint8Array(16)) expect(await pngIssue(concat(pngHeader(1, 1), notZlib, IEND))).toBe('idat') for (const delta of [1, -1]) { const raw = new Uint8Array(rawSize(4, 3) + delta) const png = concat(pngHeader(4, 3), idatOf(raw), IEND) expect(await pngIssue(png), `off by ${delta}`).toBe('idat') } expect(await pngIssue(validPng(4, 3))).toBeNull() }) it('the IDAT stream may span several chunks', async () => { const stream = deflateSync(new Uint8Array(rawSize(4, 3))) const split = Math.floor(stream.byteLength / 2) const png = concat( pngHeader(4, 3), pngChunk('IDAT', stream.subarray(0, split)), pngChunk('IDAT', stream.subarray(split)), IEND, ) expect(await pngIssue(png)).toBeNull() }) it('a wrong signature or a truncated header is refused; the real logos pass', async () => { expect(await pngIssue(pngHeader(1, 1, {}, false))).toBe('signature') expect(await pngIssue(pngHeader(1, 1).subarray(0, 20))).toBe('signature') const svg = new TextEncoder().encode('') expect(await pngIssue(svg)).toBe('signature') expect(await pngIssue(ONE_PX_PNG)).toBeNull() expect(await pngIssue(TWO_BY_ONE_PNG)).toBeNull() const logos = logosBranding() for (const asset of [ logos.headerLogo, logos.footerLogo, logos.poweredBy!.logo, ]) { if (asset?.kind !== 'png') throw new Error('png expected') expect(await pngIssue(Buffer.from(asset.base64, 'base64'))).toBeNull() } const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png')) expect(await pngIssue(new Uint8Array(touchIcon))).toBeNull() }) it('the chunk walk refuses a second IHDR, an APNG acTL and a length past the buffer', async () => { expect(await pngIssue(doubledIhdrPng())).toBe('chunks') const apng = concat( pngHeader(1, 1), pngChunk('acTL', new Uint8Array(8)), IEND, ) expect(await pngIssue(apng)).toBe('chunks') for (const type of ['fcTL', 'fdAT']) { const frame = concat( pngHeader(1, 1), pngChunk(type, new Uint8Array(4)), IEND, ) expect(await pngIssue(frame), type).toBe('chunks') } const idat = pngChunk('IDAT', new Uint8Array(16)) new DataView(idat.buffer).setUint32(0, 1_000_000) expect(await pngIssue(concat(pngHeader(1, 1), idat))).toBe('chunks') const partialHead = concat(pngHeader(1, 1), new Uint8Array(5)) expect(await pngIssue(partialHead)).toBe('chunks') expect(await pngIssue(concat(pngHeader(1, 1), IDAT, IEND))).toBeNull() const shortIhdr = pngHeader(1, 1) new DataView(shortIhdr.buffer).setUint32(8, 12) expect(await pngIssue(shortIhdr)).toBe('signature') }) it('a chunk UPNG reads with nextZero, or any type outside the allowlist, is refused', async () => { expect(await pngIssue(textWithoutNulPng())).toBe('chunks') expect(await pngIssue(itxtThenFatIendPng())).toBe('chunks') for (const type of ['tIME', 'zTXt', 'iCCP', 'abCD']) { const png = concat( pngHeader(1, 1), IDAT, pngChunk(type, new Uint8Array(7)), IEND, ) expect(await pngIssue(png), type).toBe('chunks') } }) it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', async () => { const valid = concat(pngHeader(1, 1), IDAT, IEND) expect(await pngIssue(concat(valid, new Uint8Array([0])))).toBe('chunks') expect(await pngIssue(concat(pngHeader(1, 1), IDAT))).toBe('chunks') const fatIend = pngChunk('IEND', new Uint8Array(1)) expect(await pngIssue(concat(pngHeader(1, 1), IDAT, fatIend))).toBe( 'chunks', ) const ancillary = concat( pngHeader(1, 1), pngChunk('gAMA', new Uint8Array(4)), pngChunk('pHYs', new Uint8Array(9)), pngChunk('sRGB', new Uint8Array(1)), IDAT, IEND, ) expect(await pngIssue(ancillary)).toBeNull() }) it.each([ ['an oversized header logo', () => concat(pngHeader(16_384, 16_384), IEND)], ['a doubled-IHDR header logo', doubledIhdrPng], ['a tEXt-without-NUL header logo (UPNG would spin)', textWithoutNulPng], [ 'a truncated-IDAT header logo (UPNG inflateRaw would read past the buffer)', truncatedIdatPng, ], ['a 1 × 0 header logo', () => concat(pngHeader(1, 0), IDAT, IEND)], ])( '%s fails alone with logo_failed and never reaches embedPng', async (_name, make) => { const branding = nologosBranding() const huge = make() branding.headerLogo = { kind: 'png', base64: Buffer.from(huge).toString('base64'), } branding.footerLogo = { kind: 'png', base64: Buffer.from(ONE_PX_PNG).toString('base64'), } // The spy refuses the hostile bytes itself: a regression that lets // them through fails on the assertion below instead of spinning the // worker in UPNG's nextZero or inflateRaw, which no vitest timeout // can interrupt. const realEmbedPng = PDFDocument.prototype.embedPng const embedPng = vi .spyOn(PDFDocument.prototype, 'embedPng') .mockImplementation(function (this: PDFDocument, png) { if (Buffer.from(png as Uint8Array).equals(Buffer.from(huge))) { throw new Error('hostile png reached embedPng') } return realEmbedPng.call(this, png) }) try { const { warnings } = await exportReportArchive({ ...baseInput(golden.reports.demo, golden.snapshots.demo), branding, }) expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }]) const base64 = (png: Uint8Array) => Buffer.from(png).toString('base64') const embedded = embedPng.mock.calls.map(([png]) => base64(png as Uint8Array), ) expect(embedded).not.toContain(base64(huge)) expect(embedded).toContain(base64(ONE_PX_PNG)) } finally { embedPng.mockRestore() } }, 10_000, ) it('the real logos reach embedPng when the gate passes them', async () => { const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng') try { const { warnings } = await exportReportArchive({ ...baseInput(golden.reports.demo, golden.snapshots.demo), branding: logosBranding(), rasterizer: rasterizerOf('logos'), }) expect(warnings).toEqual([]) const embedded = embedPng.mock.calls.map(([png]) => Buffer.from(png as Uint8Array).toString('base64'), ) const logos = logosBranding() for (const asset of [logos.headerLogo, logos.footerLogo]) { if (asset?.kind !== 'png') throw new Error('png expected') expect(embedded).toContain(asset.base64) } } finally { embedPng.mockRestore() } }) })