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

+37 -4
View File
@@ -5,11 +5,21 @@ import { renderBrandingSvg } from './svg/view'
/**
* The branding images embedded once per document. A PNG is decoded from
* its base64; an SVG is sanitised and rasterised at the view width. Each
* slot fails alone: the page prints the credit's fallback text instead and
* the export reports a `logo_failed` warning.
* its base64 once its header fits the pixel budget; an SVG is sanitised and
* rasterised at the view width. Each slot fails alone: the page prints the
* credit's fallback text instead and the export reports a `logo_failed`
* warning.
*/
/** A logo PNG is at most 4096² pixels and 8192 px a side (STEP6 §15). */
export const PNG_CAPS = { side: 8192, pixels: 4096 * 4096 } as const
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
const IHDR_TYPE = 0x49484452
const IHDR_END = 24
export type PngHeaderIssue = 'signature' | 'dimensions'
export type LogoSlot = Extract<ExportWarning, { kind: 'logo_failed' }>['slot']
export interface CreditAsset {
@@ -26,6 +36,24 @@ export interface BrandingImages {
partner: CreditAsset | null
}
/**
* Why a PNG is refused before any decoding, or null when its header fits
* the budget: the signature and the IHDR chunk must be there, and the
* announced width × height must stay under `PNG_CAPS`. The decoder would
* otherwise allocate the full bitmap of whatever size the header claims.
*/
export function pngHeaderIssue(bytes: Uint8Array): PngHeaderIssue | null {
if (bytes.byteLength < IHDR_END) return 'signature'
if (PNG_SIGNATURE.some((byte, i) => bytes[i] !== byte)) return 'signature'
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (view.getUint32(12) !== IHDR_TYPE) return 'signature'
const width = view.getUint32(16)
const height = view.getUint32(20)
if (width > PNG_CAPS.side || height > PNG_CAPS.side) return 'dimensions'
if (width * height > PNG_CAPS.pixels) return 'dimensions'
return null
}
function base64ToBytes(base64: string): Uint8Array {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
@@ -38,7 +66,12 @@ async function embedImage(
asset: ImageAsset,
rasterizer: Rasterizer,
): Promise<PDFImage> {
if (asset.kind === 'png') return pdfDoc.embedPng(base64ToBytes(asset.base64))
if (asset.kind === 'png') {
const bytes = base64ToBytes(asset.base64)
const issue = pngHeaderIssue(bytes)
if (issue) throw new Error(`png refused: ${issue}`)
return pdfDoc.embedPng(bytes)
}
const { svg, size } = renderBrandingSvg(asset.svg)
return pdfDoc.embedPng(await rasterizer(svg, size))
}
+2
View File
@@ -25,6 +25,8 @@ export type ArchiveExportErrorKind =
| 'snapshot_too_large'
| 'sheet_mismatch'
| 'too_many_pages'
/** The branding or the label set fails its schema (URLs included). */
| 'branding_invalid'
export class ArchiveExportError extends Error {
constructor(
+17
View File
@@ -1,9 +1,11 @@
import { PDFDocument } from 'pdf-lib'
import {
assertSnapshot,
BrandingSchema,
buildSheetIndex,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
PdfLabelSetSchema,
snapshotIndexSource,
SnapshotError,
type Report,
@@ -43,6 +45,20 @@ export const PAGE_CAPS = {
viewsPerObservation: 8,
} as const
/**
* Step 0: the branding and the labels pass their schemas again. They reach
* the engine from an archive or from the application and end up in link
* URIs and drawn text, so a caller cannot be trusted to have validated them.
*/
function assertBrandingAndLabels(input: ExportInput): void {
if (!BrandingSchema.safeParse(input.branding).success) {
throw new ArchiveExportError('branding_invalid', 'branding')
}
if (!PdfLabelSetSchema.safeParse(input.labels).success) {
throw new ArchiveExportError('branding_invalid', 'labels')
}
}
/** Step 1: the snapshot gate, with every asset accepted by the sanitiser. */
function checkedSnapshot(sheet: SheetSnapshot): SheetSnapshot {
let parsed: SheetSnapshot
@@ -161,6 +177,7 @@ async function drawPages(pages: Pages): Promise<void> {
export async function exportReportArchive(
input: ExportInput,
): Promise<ExportResult> {
assertBrandingAndLabels(input)
const sheet = checkedSnapshot(input.sheet)
assertExportable(input.report, sheet)
const envelope = buildEnvelope(input, sheet)
+9 -4
View File
@@ -1,4 +1,4 @@
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
import { PDFName, PDFHexString, type PDFPage } from 'pdf-lib'
export interface LinkRect {
x: number
@@ -8,14 +8,19 @@ export interface LinkRect {
url: string
}
/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */
/**
* A clickable `/Link` annotation opening `url`, appended to the page's
* Annots. The URI is written as a hex string: pdf-lib does not escape `(`,
* `)` or `\` in a literal string, so a hostile URL could otherwise close
* the literal and inject objects (a `/Next` JavaScript action, for one).
*/
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
const context = page.doc.context
const actionDict = context.obj({
Type: 'Action',
S: 'URI',
URI: PDFString.of(rect.url),
URI: PDFHexString.fromText(rect.url),
})
const annotDict = context.obj({
@@ -26,7 +31,7 @@ export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
A: actionDict,
})
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
const annots = page.node.Annots()
if (annots) {
annots.push(context.register(annotDict))
} else {
+50 -6
View File
@@ -5,10 +5,12 @@ import { SvgRejectedError } from '../errors'
* Allowlist sanitiser for the sheet drawings and the branding SVGs
* (STEP6 §15), on DOM Level 2 only. Elements and attributes outside the
* inventory of the real assets plus structural needs are removed with
* their subtree; `href` and `url(…)` must stay inside the document; a
* `style` attribute may carry no external reference; the halo filters are
* clamped. Element, nesting and `<use>` counters refuse an oversized tree.
* The caller learns what was removed (names only, never values).
* their subtree; `href` and `url(…)` must stay inside the document; no
* value carries a backslash (a CSS escape such as `u\72l(` would hide a
* reference from the rules below); a `style` or presentation attribute may
* call no function but `url(#…)`; the halo filters are clamped. Element,
* nesting and `<use>` counters refuse an oversized tree. The caller learns
* what was removed (names only, never values).
*/
export const SANITIZER_CAPS = {
@@ -126,9 +128,42 @@ const ALLOWED_ATTRIBUTES = new Set([
'style',
])
/** Attributes whose value is CSS-like: a function call there is a reference or an exploit. */
const PRESENTATION_ATTRIBUTES = new Set([
'fill',
'fill-opacity',
'fill-rule',
'stroke',
'stroke-width',
'stroke-linecap',
'stroke-linejoin',
'stroke-opacity',
'stroke-dasharray',
'stroke-dashoffset',
'stroke-miterlimit',
'opacity',
'filter',
'clip-path',
'clip-rule',
'mask',
'display',
'visibility',
'color',
'stop-color',
'stop-opacity',
'flood-color',
'flood-opacity',
'color-interpolation-filters',
'font-family',
'font-size',
'font-weight',
])
const LOCAL_REFERENCE = /^#[A-Za-z_][\w.:-]*$/
const URL_FUNCTION = /url\(\s*['"]?\s*(.?)/gi
const STYLE_FORBIDDEN = /expression\(|@import|javascript:|behavior:/i
const LOCAL_URL_OPEN = /url\(\s*['"]?\s*#/gi
const STYLE_FORBIDDEN =
/expression\(|image-set\(|@import|javascript:|behavior:/i
export interface SanitizeOutcome {
/** Removed element names and `element@attribute` pairs, in document order. */
@@ -157,11 +192,20 @@ function hrefIsLocal(value: string): boolean {
return LOCAL_REFERENCE.test(value.trim())
}
/** Any `(` left once the `url(#` openings are gone is a function we never allow. */
function callsOnlyLocalUrl(value: string): boolean {
return !value.replace(LOCAL_URL_OPEN, '').includes('(')
}
/** Whether an allowed attribute keeps its value, by name-specific rule. */
function attributeAcceptable(name: string, value: string): boolean {
if (value.includes('\\')) return false
if (!urlsAreLocal(value)) return false
if (name === 'href' || name === 'xlink:href') return hrefIsLocal(value)
if (name === 'style') return !STYLE_FORBIDDEN.test(value)
if (name === 'style') {
return !STYLE_FORBIDDEN.test(value) && callsOnlyLocalUrl(value)
}
if (PRESENTATION_ATTRIBUTES.has(name)) return callsOnlyLocalUrl(value)
return true
}
+11 -2
View File
@@ -27,6 +27,11 @@ export interface RenderedSvg {
size: RasterSize
}
/** A usable dimension: finite and strictly positive (`1e999` parses to Infinity). */
function isPositiveFinite(value: number | undefined): value is number {
return value !== undefined && Number.isFinite(value) && value > 0
}
/** Height over width of a `viewBox` value, or the fallback when unusable. */
function aspectOf(viewBox: string | null): number {
const parts = (viewBox ?? '')
@@ -34,10 +39,14 @@ function aspectOf(viewBox: string | null): number {
.split(/[\s,]+/)
.map(Number)
const [, , width, height] = parts
if (parts.length !== 4 || !(width! > 0) || !(height! > 0)) {
if (
parts.length !== 4 ||
!isPositiveFinite(width) ||
!isPositiveFinite(height)
) {
return ASPECT_FALLBACK
}
return height! / width!
return height / width
}
export function rasterSizeOf(viewBox: string | null): RasterSize {
+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()
}
})
})