fix(pdf): security hardening — hex-encoded link URIs, strict branding URL schema, branding and labels re-validated at export, PNG dimension budget, CSS escape and parenthesis rules in the sanitiser, finite raster size, file size checked before read

This commit is contained in:
bchanot committed 2026-10-11 13:54:18 +02:00
1 parent 4930704d8a
commit 1f417b21fd
12 files changed
+437 -25

No files matched your search

+205 -1
View File
@@ -6,10 +6,12 @@
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { beforeAll, describe, expect, it } from 'vitest'
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,
@@ -17,23 +19,29 @@ import {
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'
@@ -297,6 +305,46 @@ describe('hostile SVG assets', () => {
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;')
@@ -409,3 +457,159 @@ describe('__proto__ ids and the inflate bomb', () => {
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,
}
}
describe('branding URL injection (HIGH)', () => {
it('the link sink alone keeps the whole URL inside the /URI string', async () => {
const doc = await PDFDocument.create()
const rect = { x: 0, y: 0, width: 10, height: 10, url: INJECTION_URL }
addLinkAnnotation(doc.addPage(), rect)
const bytes = await doc.save()
const raw = Buffer.from(bytes).toString('latin1')
expect(raw).not.toContain('/JavaScript')
expect(raw).not.toContain('/Next')
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(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
}
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(pngHeader(width, height))).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()
}
})
it('an oversized header logo fails alone with logo_failed and never reaches embedPng', async () => {
const branding = nologosBranding()
const huge = pngHeader(16_384, 16_384)
branding.headerLogo = {
kind: 'png',
base64: Buffer.from(huge).toString('base64'),
}
branding.footerLogo = {
kind: 'png',
base64: Buffer.from(ONE_PX_PNG).toString('base64'),
}
const embedPng = vi.spyOn(PDFDocument.prototype, 'embedPng')
try {
const { warnings } = await exportReportArchive({
...baseInput(golden.reports.demo, golden.snapshots.demo),
branding,
})
expect(warnings).toEqual([{ kind: 'logo_failed', slot: 'headerLogo' }])
const sizes = embedPng.mock.calls.map(
([png]) => (png as Uint8Array).byteLength,
)
expect(sizes).not.toContain(huge.byteLength)
expect(sizes).toContain(ONE_PX_PNG.byteLength)
} finally {
embedPng.mockRestore()
}
})
})