/** * 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 = (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(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).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, } } 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)['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(''))).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() } }) })