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

412 lines
13 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 } from 'vitest'
import {
assertSnapshot,
SnapshotError,
type Report,
type ReportArchiveEnvelope,
type SheetSnapshot,
} from '@faunosteo/domain'
import {
ArchiveExportError,
defaultPdfLabels,
exportReportArchive,
readReportArchive,
type ExportInput,
type Rasterizer,
} from '../src'
import { inflateFlate } from '../src/attachment/inflate'
import { SvgRejectedError } from '../src/errors'
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,
nologosBranding,
ONE_PX_PNG,
rasterizerOf,
recordDrawing,
} 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('<!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()
})
})