fix(pdf): PNG gate inflates IDAT natively against the exact raw size, validates IHDR fields, refuses zero dimensions and interlace (UPNG inflateRaw spin)

This commit is contained in:
bchanot committed 2026-10-11 14:52:03 +02:00
1 parent 0ceb357b18
commit cb95627a11
4 files changed
+412 -76

No files matched your search

+249 -42
View File
@@ -6,6 +6,7 @@
*/
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 {
@@ -26,7 +27,7 @@ import {
type Rasterizer,
} from '../src'
import { inflateFlate } from '../src/attachment/inflate'
import { pngHeaderIssue } from '../src/branding'
import { pngIssue } from '../src/branding'
import { SvgRejectedError } from '../src/errors'
import { addLinkAnnotation } from '../src/render/linkAnnotation'
import { parseSvg, serializeSvg } from '../src/svg/parse'
@@ -579,20 +580,37 @@ describe('branding URL injection (HIGH)', () => {
})
})
/** A PNG signature and an IHDR chunk announcing `width` × `height`, nothing after. */
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([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
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
}
@@ -611,8 +629,36 @@ function pngChunk(type: string, data: Uint8Array): Uint8Array {
const concat = (...parts: Uint8Array[]): Uint8Array =>
Uint8Array.from(Buffer.concat(parts.map((p) => Buffer.from(p))))
const CHANNELS: Record<number, number> = { 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))
const IDAT = pngChunk('IDAT', new Uint8Array(16))
/** 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 {
@@ -638,24 +684,158 @@ function itxtThenFatIendPng(): Uint8Array {
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 → 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)
['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('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()
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('<svg/>')
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,
@@ -663,42 +843,42 @@ describe('PNG budget (MEDIUM)', () => {
logos.poweredBy!.logo,
]) {
if (asset?.kind !== 'png') throw new Error('png expected')
expect(pngHeaderIssue(Buffer.from(asset.base64, 'base64'))).toBeNull()
expect(await pngIssue(Buffer.from(asset.base64, 'base64'))).toBeNull()
}
const touchIcon = readFileSync(resolve(PUBLIC_DIR, 'apple-touch-icon.png'))
expect(pngHeaderIssue(new Uint8Array(touchIcon))).toBeNull()
expect(await pngIssue(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')
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(pngHeaderIssue(apng)).toBe('chunks')
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(pngHeaderIssue(frame), type).toBe('chunks')
expect(await pngIssue(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')
expect(await pngIssue(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()
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(pngHeaderIssue(shortIhdr)).toBe('signature')
expect(await pngIssue(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')
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),
@@ -706,19 +886,18 @@ describe('PNG budget (MEDIUM)', () => {
pngChunk(type, new Uint8Array(7)),
IEND,
)
expect(pngHeaderIssue(png), type).toBe('chunks')
expect(await pngIssue(png), type).toBe('chunks')
}
})
it('the list must end on an empty IEND that closes the buffer; ancillary chunks pass', () => {
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(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')
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)),
@@ -727,13 +906,18 @@ describe('PNG budget (MEDIUM)', () => {
IDAT,
IEND,
)
expect(pngHeaderIssue(ancillary)).toBeNull()
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) => {
@@ -749,7 +933,8 @@ describe('PNG budget (MEDIUM)', () => {
}
// 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.
// 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')
@@ -777,4 +962,26 @@ describe('PNG budget (MEDIUM)', () => {
},
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()
}
})
})