Files
faunosteo/packages/pdf/tests/security.test.ts
T

781 lines
26 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 { 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 { pngHeaderIssue } 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 { 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 = <T>(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 =
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 2073.4 1629.4">'
const wrap = (inner: string) => `${SVG_OPEN}${inner}</svg>`
/** Exports the demo first observation on a snapshot whose drawing is `svg`; returns what the rasterizer saw. */
async function exportWithAsset(svg: string): Promise<string[]> {
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('<script>, on*, javascript: href, external <image>, <style> are gone from what is rasterised', async () => {
const [seen] = await exportWithAsset(
wrap(
'<script>alert(1)</script>' +
'<style>path{fill:url(http://evil.test/a)}</style>' +
'<defs><path id="p" d="M0 0h10v10z"/></defs>' +
'<path d="M0 0h1" onload="steal()" style="fill:url(http://evil.test/b)"/>' +
'<use xlink:href="javascript:alert(1)"/><use href="#p"/>' +
'<image href="https://evil.test/x.png" width="10" height="10"/>' +
'<path d="M1 1h1" fill="url(http://evil.test/c)"/>',
),
)
expect(seen).toBeDefined()
for (const forbidden of [
'<script',
'<style',
'onload',
'javascript:',
'<image',
'evil.test',
]) {
expect(seen).not.toContain(forbidden)
}
expect(seen).toContain('<use href="#p"/>')
expect(seen).toContain('<path id="p" d="M0 0h10v10z"/>')
expect(seen).toContain('fill="#b85a3f"')
})
it('the sanitiser names what it removed and clamps stdDeviation', () => {
const root = parseSvg(
wrap(
'<script>x</script><g onclick="y()" data-x="1"><path d="M0 0" style="fill:url(http://e)"/></g>' +
'<filter id="f"><feGaussianBlur stdDeviation="500,3"/><feTurbulence/></filter>' +
'<use xlink:href="javascript:z"/><a href="#ok"/>',
),
)
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(
'<path d="M0 0" style="fill:u\\72l(http://evil/x)"/>' +
`<path d="M0 0" style='fill:image-set("http://evil/y")'/>` +
'<path d="M0 0" fill="u\\72l(http://evil/x)"/>' +
'<path d="M0 0" fill="rgb(1,2,3)"/>' +
'<path d="M0 0" id="a&#92;b"/>' +
'<path d="M0 0" fill="url(#ok)" transform="translate(1 2)"/>',
),
)
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('<!ENTITY> and 257 <use> are refused: the export fails as snapshot_invalid', async () => {
const entity =
'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY x "y">]>' + wrap('&x;')
await expect(exportWithAsset(entity)).rejects.toMatchObject({
kind: 'snapshot_invalid',
})
const uses = (count: number) =>
wrap(
'<defs><path id="p" d="M0 0h1"/></defs>' +
'<use href="#p"/>'.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: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 100000"><rect width="1" height="1"/></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(PUBLIC_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<string, unknown>).polluted).toBeUndefined()
})
async function deflate(data: Uint8Array): Promise<Uint8Array> {
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<Uint8Array> {
const doc = await PDFDocument.create()
addLinkAnnotation(doc.addPage(), { x: 0, y: 0, width: 10, height: 10, url })
return doc.save({ useObjectStreams: false })
}
/** `<hex>` 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<string, string>)['pdf.subject']
await expect(
exportFromEnvelope(labels, reexportOptions()),
).rejects.toMatchObject({ kind: 'branding_invalid' })
await expect(
exportFromEnvelope(clone(envelope), reexportOptions()),
).resolves.toMatchObject({ warnings: [] })
})
})
/** A PNG signature and an IHDR chunk announcing `width` × `height`, nothing after. */
function pngHeader(
width: number,
height: number,
signature = true,
): Uint8Array {
const bytes = new Uint8Array(33)
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
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)
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 IEND = pngChunk('IEND', new Uint8Array(0))
const IDAT = pngChunk('IDAT', new Uint8Array(16))
/** 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)
}
describe('PNG budget (MEDIUM)', () => {
it.each([
['8193 × 1 → dimensions', 8193, 1, 'dimensions'],
['1 × 8193 → dimensions', 1, 8193, 'dimensions'],
['4097 × 4096 (over 4096²) → dimensions', 4097, 4096, 'dimensions'],
['12000 × 12000 (144 Mpx) → dimensions', 12_000, 12_000, 'dimensions'],
['4096 × 4096 → accepted', 4096, 4096, null],
['8192 × 2048 → accepted', 8192, 2048, null],
])('%s', (_name, width, height, issue) => {
expect(pngHeaderIssue(concat(pngHeader(width, height), IEND))).toBe(issue)
})
it('a wrong signature or a truncated header is refused; the real logos pass', () => {
expect(pngHeaderIssue(pngHeader(1, 1, false))).toBe('signature')
expect(pngHeaderIssue(pngHeader(1, 1).subarray(0, 20))).toBe('signature')
expect(pngHeaderIssue(new TextEncoder().encode('<svg/>'))).toBe('signature')
expect(pngHeaderIssue(ONE_PX_PNG)).toBeNull()
expect(pngHeaderIssue(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(pngHeaderIssue(Buffer.from(asset.base64, 'base64'))).toBeNull()
}
const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png'))
expect(pngHeaderIssue(new Uint8Array(touchIcon))).toBeNull()
})
it('the chunk walk refuses a second IHDR, an APNG acTL and a length past the buffer', () => {
expect(pngHeaderIssue(doubledIhdrPng())).toBe('chunks')
const apng = concat(
pngHeader(1, 1),
pngChunk('acTL', new Uint8Array(8)),
IEND,
)
expect(pngHeaderIssue(apng)).toBe('chunks')
for (const type of ['fcTL', 'fdAT']) {
const frame = concat(
pngHeader(1, 1),
pngChunk(type, new Uint8Array(4)),
IEND,
)
expect(pngHeaderIssue(frame), type).toBe('chunks')
}
const idat = pngChunk('IDAT', new Uint8Array(16))
new DataView(idat.buffer).setUint32(0, 1_000_000)
expect(pngHeaderIssue(concat(pngHeader(1, 1), idat))).toBe('chunks')
const partialHead = concat(pngHeader(1, 1), new Uint8Array(5))
expect(pngHeaderIssue(partialHead)).toBe('chunks')
expect(pngHeaderIssue(concat(pngHeader(1, 1), IDAT, IEND))).toBeNull()
const shortIhdr = pngHeader(1, 1)
new DataView(shortIhdr.buffer).setUint32(8, 12)
expect(pngHeaderIssue(shortIhdr)).toBe('signature')
})
it('a chunk UPNG reads with nextZero, or any type outside the allowlist, is refused', () => {
expect(pngHeaderIssue(textWithoutNulPng())).toBe('chunks')
expect(pngHeaderIssue(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(pngHeaderIssue(png), type).toBe('chunks')
}
})
it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', () => {
const valid = concat(pngHeader(1, 1), IDAT, IEND)
expect(pngHeaderIssue(concat(valid, new Uint8Array([0])))).toBe('chunks')
expect(pngHeaderIssue(concat(pngHeader(1, 1), IDAT))).toBe('chunks')
expect(
pngHeaderIssue(
concat(pngHeader(1, 1), IDAT, pngChunk('IEND', new Uint8Array(1))),
),
).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(pngHeaderIssue(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],
])(
'%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, 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,
)
})