:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-anonymizer): scrub svg data uris, rendered under a deadline (#116878)
Nicholas Waltz64376a4d9b47
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 7438623a4f93..79ee08031f10 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md@@ -260,6 +260,20 @@ The image compiles the addon from `rust/` in a Rust stage of `Dockerfile.ml-mirrEvery worker loads it at startup, so a missing or stale addon fails the smoke test and with it the image build.On a dev machine, `npm run build:native` builds it into `native/`.+## SVG++The anonymizer sends an SVG data URI as its decoded document, checking only its size and that it starts with markup.+Parsing and rendering both cost more than the document's size suggests: a few hundred bytes of huge strokes, markers or clip paths can take minutes to draw, and thousands of attributes on one element make the XML parser quadratic.+So both run in a separate process (`src/svg-rasterizer-process.mjs`, through the addon's `rasterizeSvg`), which the sidecar kills when a render runs past `IMAGE_SCRUB_SVG_TIMEOUT_MS` (2s).+A worker thread inside a native call cannot be stopped, but a process can.+The renderer refuses DTDs, filters, masks, patterns, `foreignObject`, deep nesting and more than 8 `<use>` elements before it draws anything.+Rendering drops the document's metadata, so the sidecar reads the XMP training opt-out from the SVG itself first.+The PNG then goes through the same scrub as any other image.++The renderer has no text or raster-image support and refuses every nested image reference, so the PNG holds only shapes.+A refused document and a timed-out render both answer 422 (`undecodable` reasons `svg_refused` and `svg_timeout`), so the consumer skips the image.+`IMAGE_SCRUB_SVG_RASTERIZERS` (1) sets how many renders run at once.+## ObservabilityBeyond the HTTP outcome counters (scrubbed/failed/undecodable/rejected/too-large/aborted, duration, output bytes), `/metrics` carries the outcome signals an anonymization control needs:diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.tsindex 0782f616074c..7f3b8dae96f1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts@@ -28,6 +28,8 @@ export interface Config {// look merely slow forever and hold the head of its partition. Measured from dispatch rather// than enqueue so queue wait is not charged to whichever worker happens to hold the job.jobTimeoutMs: number+ svgTimeoutMs: number+ svgRasterizers: number}export function loadConfig(): Config {@@ -37,5 +39,7 @@ export function loadConfig(): Config {maxConcurrency: ADMITTED_PER_WORKER * SCRUB_WORKERS,maxBodyBytes: numFromEnv('IMAGE_SCRUB_MAX_BODY_BYTES', 20 * 1024 * 1024, 1024, 512 * 1024 * 1024),jobTimeoutMs: numFromEnv('IMAGE_SCRUB_JOB_TIMEOUT_MS', 15_000, 1000, 600_000),+ svgTimeoutMs: numFromEnv('IMAGE_SCRUB_SVG_TIMEOUT_MS', 2_000, 50, 60_000),+ svgRasterizers: numFromEnv('IMAGE_SCRUB_SVG_RASTERIZERS', 1, 1, 16),}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.tsindex 8167448f1408..9b1bac88d536 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts@@ -23,6 +23,8 @@ export type UndecodableImageReason =| 'invalid_body'| 'invalid_dimensions'| 'pixel_limit'+ | 'svg_refused'+ | 'svg_timeout'| 'unsupported_format'export class UndecodableImageError extends PermanentImageError {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.tsindex 9378bbde9afc..6c65a1847845 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts@@ -1,4 +1,6 @@/* eslint-disable no-console -- sidecar logs to stdout */+import { fileURLToPath } from 'node:url'+import { loadConfig } from './config.ts'import { ORT_THREADS, SCRUB_WORKERS } from './cores.ts'import { bindingRatio } from './floors.ts'@@ -6,10 +8,12 @@ import { ScrubMetrics, trackPool } from './metrics.ts'import { startPool } from './pool.ts'import { limitsFromEnv } from './scale-plan.ts'import { startServer } from './server.ts'+import { isSvgDocument, startSvgRasterizer } from './svg.ts'// Resolved here rather than in pool.ts: entry points run under tsx, where import.meta works, while// jest's CJS transform cannot load a src/ module that contains it (see the note in qr.ts).const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)+const SVG_RASTERIZER_PATH = fileURLToPath(new URL('./svg-rasterizer-process.mjs', import.meta.url))const cfg = loadConfig()const SCRUB_LIMITS = limitsFromEnv()@@ -37,6 +41,7 @@ if (uvThreadpoolSize < SCRUB_WORKERS) {// scrub and the readiness probe cannot pass on a half-started pool.const pool = await startPool(SCRUB_WORKERS, WORKER_URL, cfg.jobTimeoutMs)trackPool(pool)+const svg = await startSvgRasterizer(cfg.svgRasterizers, SVG_RASTERIZER_PATH, cfg.svgTimeoutMs, cfg.jobTimeoutMs)const { scrub, metrics } = startServer(cfg.port,@@ -44,7 +49,8 @@ const { scrub, metrics } = startServer(cfg.maxConcurrency,cfg.maxBodyBytes,async (input, signal) => {- const { out, t } = await pool.scrub(input, signal)+ const raster = isSvgDocument(input) ? await svg.rasterize(input, signal) : input+ const { out, t } = await pool.scrub(raster, signal)ScrubMetrics.observeScrubOutcome(t)return out},@@ -62,7 +68,7 @@ for (const sig of ['SIGINT', 'SIGTERM'] as const) {// The backstop stays armed across pool.close(): terminating a worker wedged inside a// native ORT call is exactly the step that can hang, and clearing the timer first// would disarm it for the only part of shutdown that needs it.- void pool.close().finally(() => {+ void Promise.all([pool.close(), svg.close()]).finally(() => {clearTimeout(force)process.exit(0)})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.tsindex 22032f2e473b..65ae3438f8db 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts@@ -17,11 +17,17 @@* the output pixels, because a face model can run and still put its boxes away from the face.*/import { readFile } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'import sharp from 'sharp'import { startPool } from './pool.ts'+import { startSvgRasterizer } from './svg.ts'const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)+const SVG_RASTERIZER_PATH = fileURLToPath(new URL('./svg-rasterizer-process.mjs', import.meta.url))+const SVG_FIXTURE = Buffer.from(+ "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='8'><rect width='16' height='8' fill='red'/></svg>"+)/*** A rendered fixture, embedded as bytes rather than drawn here.@@ -127,11 +133,20 @@ async function greySpreadOverFaceMiddle(async function main(): Promise<void> {const pool = await startPool(2, WORKER_URL)+ const svg = await startSvgRasterizer(1, SVG_RASTERIZER_PATH, 10_000, 10_000)const png = TEXT_FIXTURE_PNGconst face = await readFile(FACE_FIXTURE)// Two at once, so the build fails if a second worker cannot start or the pool mis-routes replies.- const [first, second, faceScrub] = await Promise.all([pool.scrub(png), pool.scrub(png), pool.scrub(face)])- await pool.close()+ const [first, second, faceScrub, svgScrub] = await Promise.all([+ pool.scrub(png),+ pool.scrub(png),+ pool.scrub(face),+ svg.rasterize(SVG_FIXTURE).then((raster) => pool.scrub(raster)),+ ])+ await Promise.all([pool.close(), svg.close()])+ if (svgScrub.out.length === 0) {+ throw new Error('smoke scrub of the rendered svg produced empty output')+ }for (const [label, result] of [['first', first],diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg-rasterizer-process.mjs b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg-rasterizer-process.mjsnew file mode 100644index 000000000000..128b161ada96--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg-rasterizer-process.mjs@@ -0,0 +1,20 @@+// A process rather than a worker thread, because only a process can be stopped inside a native call.+import { createRequire } from 'node:module'+import { resolve } from 'node:path'++const ADDON_PATH = resolve('native/replay-anonymizer.node')+const { rasterizeSvg } = createRequire(ADDON_PATH)(ADDON_PATH)+if (typeof rasterizeSvg !== 'function') {+ throw new Error(`the native addon at ${ADDON_PATH} has no rasterizeSvg; rebuild it with \`npm run build:native\``)+}++process.on('message', ({ id, input }) => {+ let reply+ try {+ reply = { id, out: rasterizeSvg(input) }+ } catch (error) {+ reply = { id, refused: error instanceof Error ? error.message : String(error) }+ }+ process.send(reply)+})+process.send({ ready: true })diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.test.tsnew file mode 100644index 000000000000..f0873b91804b--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.test.ts@@ -0,0 +1,69 @@+import { ImageOptOutError, UndecodableImageError } from './image-input.ts'+import { ScrubAbandonedError } from './pool.ts'+import { type SvgRasterizer, isSvgDocument, startSvgRasterizer } from './svg.ts'++// cwd-relative rather than import.meta, which jest's CJS transform cannot load (see qr.ts).+const CHILD = `${process.cwd()}/src/svg-rasterizer-process.mjs`+const SQUARE = Buffer.from(+ "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='8'><rect width='16' height='8' fill='red'/></svg>"+)+const SLOW = Buffer.from(+ `<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'>${"<circle r='1e6' stroke='red' stroke-width='1e7' fill='none'/>".repeat(40)}</svg>`+)++describe('svg', () => {+ let rasterizer: SvgRasterizer | undefined++ afterEach(async () => {+ await rasterizer?.close()+ rasterizer = undefined+ })++ it.each([+ ['an svg document', SQUARE, true],+ [+ 'one after a BOM and whitespace',+ Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(' \n'), SQUARE]),+ true,+ ],+ ['a png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), false],+ ['a jpeg', Buffer.from([0xff, 0xd8, 0xff]), false],+ ['an empty body', Buffer.alloc(0), false],+ ])('tells %s by its first bytes', (_label, input, expected) => {+ expect(isSvgDocument(input)).toBe(expected)+ })++ it('renders an svg to png and refuses one it cannot render', async () => {+ rasterizer = await startSvgRasterizer(1, CHILD, 5_000, 10_000)+ const png = await rasterizer.rasterize(SQUARE)+ expect(png.subarray(0, 4).toString('latin1')).toBe('\x89PNG')+ await expect(rasterizer.rasterize(Buffer.from('<svg'))).rejects.toMatchObject({ reason: 'svg_refused' })+ })++ it('refuses an svg whose metadata opts out of AI training before rendering it', async () => {+ rasterizer = await startSvgRasterizer(1, CHILD, 5_000, 10_000)+ const optedOut = Buffer.from(+ "<svg xmlns='http://www.w3.org/2000/svg' xmlns:plus='http://ns.useplus.org/ldf/xmp/1.0/' width='8' height='8'>" ++ '<metadata><plus:DataMining>http://ns.useplus.org/ldf/vocab/DMI-PROHIBITED</plus:DataMining></metadata></svg>'+ )+ await expect(rasterizer.rasterize(optedOut)).rejects.toBeInstanceOf(ImageOptOutError)+ })++ it('drops a request whose caller hung up while it waits behind a slow render', async () => {+ rasterizer = await startSvgRasterizer(1, CHILD, 10_000, 30_000)+ const slow = rasterizer.rasterize(SLOW).catch(() => 'slow settled')+ const controller = new AbortController()+ const waiting = rasterizer.rasterize(SQUARE, controller.signal)+ controller.abort()+ await expect(Promise.race([waiting, slow])).rejects.toBeInstanceOf(ScrubAbandonedError)+ })++ it('kills a render that runs past its deadline and serves the next one', async () => {+ rasterizer = await startSvgRasterizer(1, CHILD, 200, 30_000)+ const slow = rasterizer.rasterize(SLOW)+ const next = rasterizer.rasterize(SQUARE)+ await expect(slow).rejects.toBeInstanceOf(UndecodableImageError)+ await expect(slow).rejects.toMatchObject({ reason: 'svg_timeout' })+ expect((await next).subarray(0, 4).toString('latin1')).toBe('\x89PNG')+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.tsnew file mode 100644index 000000000000..1e951f1b47a4--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/svg.ts@@ -0,0 +1,232 @@+/* eslint-disable no-console -- sidecar logs to stdout */+import { type ChildProcess, fork } from 'node:child_process'++import { ImageOptOutError, UndecodableImageError } from './image-input.ts'+import { ScrubAbandonedError } from './pool.ts'+import { xmpProhibitsAiTraining } from './xmp.ts'++const READY_TIMEOUT_MS = 30_000+const RESTART_BACKOFF_BASE_MS = 500+const RESTART_BACKOFF_MAX_MS = 30_000+// Abandonment is otherwise checked only on dispatch, which never comes while every renderer is down.+const QUEUE_SWEEP_MS = 1_000++/**+ * The lane sends an SVG only as a document that starts with markup, and no raster format the scrub+ * takes starts with `<`, so markup after an optional BOM and whitespace is enough to tell.+ */+export function isSvgDocument(input: Buffer): boolean {+ let i = input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf ? 3 : 0+ while (i < input.length && (input[i] === 0x20 || input[i] === 0x09 || input[i] === 0x0a || input[i] === 0x0d)) {+ i+++ }+ return input[i] === 0x3c+}++export interface SvgRasterizer {+ rasterize(input: Buffer, signal?: AbortSignal): Promise<Buffer>+ usableProcesses(): number+ close(): Promise<void>+}++interface Job {+ id: number+ input: Buffer+ resolve: (png: Buffer) => void+ reject: (error: Error) => void+ signal?: AbortSignal+ queuedAt: number+}++interface Slot {+ child: ChildProcess+ job: { job: Job; deadline: NodeJS.Timeout } | null+ usable: boolean+ retired: boolean+}++type Reply = { ready: true } | { id: number; out: Uint8Array } | { id: number; refused: string }++/** The child script is a parameter because jest's CJS transform cannot load import.meta (see qr.ts). */+export async function startSvgRasterizer(+ size: number,+ childPath: string,+ timeoutMs: number,+ abandonAfterMs: number+): Promise<SvgRasterizer> {+ const slots: Slot[] = []+ const queue: Job[] = []+ const restartFailures: number[] = []+ let nextJobId = 0+ let closing = false++ const abandoned = (job: Job): boolean =>+ job.signal?.aborted === true || performance.now() - job.queuedAt > abandonAfterMs++ const pump = (): void => {+ for (const dead of queue.filter(abandoned)) {+ queue.splice(queue.indexOf(dead), 1)+ dead.reject(new ScrubAbandonedError(`svg job ${dead.id} was abandoned before it ran`))+ }+ for (const slot of slots) {+ if (!slot?.usable || slot.job || queue.length === 0) {+ continue+ }+ const job = queue.shift()!+ const deadline = setTimeout(() => {+ retire(+ slots.indexOf(slot),+ slot,+ new UndecodableImageError('svg_timeout', `svg job ${job.id} timed out`)+ )+ }, timeoutMs)+ deadline.unref()+ slot.job = { job, deadline }+ slot.child.send({ id: job.id, input: job.input })+ }+ }++ const spawn = async (index: number): Promise<void> => {+ const child = fork(childPath, [], {+ serialization: 'advanced',+ execArgv: [],+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],+ })+ const slot: Slot = { child, job: null, usable: false, retired: false }+ slots[index] = slot+ child.on('error', (error) => console.error(`[image-scrub] svg rasterizer ${index}: ${String(error)}`))+ await new Promise<void>((ready, failed) => {+ const timer = setTimeout(() => {+ cleanup()+ failed(new Error(`svg rasterizer did not become ready within ${READY_TIMEOUT_MS}ms`))+ }, READY_TIMEOUT_MS)+ const onMessage = (msg: Reply): void => {+ if ('ready' in msg) {+ cleanup()+ ready()+ }+ }+ const onExit = (code: number | null): void => {+ cleanup()+ failed(new Error(`svg rasterizer exited with code ${code} before it was ready`))+ }+ const cleanup = (): void => {+ clearTimeout(timer)+ child.off('message', onMessage)+ child.off('exit', onExit)+ }+ child.on('message', onMessage)+ child.once('exit', onExit)+ }).catch((error: unknown) => {+ child.kill('SIGKILL')+ throw error+ })++ child.on('message', (msg: Reply) => {+ if ('ready' in msg || !slot.job || slot.job.job.id !== msg.id) {+ return+ }+ const { job, deadline } = slot.job+ clearTimeout(deadline)+ slot.job = null+ restartFailures[index] = 0+ if ('refused' in msg) {+ job.reject(new UndecodableImageError('svg_refused', msg.refused))+ } else {+ job.resolve(Buffer.from(msg.out.buffer, msg.out.byteOffset, msg.out.byteLength))+ }+ pump()+ })+ child.on('exit', (code, signal) =>+ retire(index, slot, new Error(`svg rasterizer exited with ${signal ?? `code ${code}`}`))+ )+ slot.usable = true+ }++ const retire = (index: number, slot: Slot, error: Error): void => {+ if (closing || slot.retired) {+ return+ }+ slot.retired = true+ slot.usable = false+ if (slot.job) {+ clearTimeout(slot.job.deadline)+ slot.job.job.reject(error)+ slot.job = null+ }+ slot.child.kill('SIGKILL')+ scheduleReplacement(index)+ }++ const scheduleReplacement = (index: number): void => {+ const failures = (restartFailures[index] ?? 0) + 1+ restartFailures[index] = failures+ const delayMs =+ failures === 1 ? 0 : Math.min(RESTART_BACKOFF_MAX_MS, RESTART_BACKOFF_BASE_MS * 2 ** (failures - 2))+ const timer = setTimeout(() => {+ if (closing) {+ return+ }+ spawn(index)+ .then(pump)+ .catch((error: unknown) => {+ console.error(`[image-scrub] svg rasterizer ${index} failed to restart: ${String(error)}`)+ scheduleReplacement(index)+ })+ }, delayMs)+ timer.unref()+ }++ await Promise.all(Array.from({ length: size }, (_unused, i) => spawn(i)))+ const sweep = setInterval(pump, QUEUE_SWEEP_MS)+ sweep.unref()++ return {+ rasterize(input: Buffer, signal?: AbortSignal): Promise<Buffer> {+ if (closing) {+ return Promise.reject(new Error('svg rasterizer is closing'))+ }+ // Rendering drops the document's metadata, so its training opt-out is read first.+ let optedOut: boolean+ try {+ optedOut = xmpProhibitsAiTraining(input)+ } catch {+ return Promise.reject(new UndecodableImageError('svg_refused', 'svg is not well-formed XML'))+ }+ if (optedOut) {+ return Promise.reject(new ImageOptOutError('image metadata prohibits AI training'))+ }+ return new Promise<Buffer>((resolve, reject) => {+ queue.push({ id: nextJobId++, input, resolve, reject, signal, queuedAt: performance.now() })+ pump()+ })+ },+ usableProcesses(): number {+ return slots.filter((s) => s?.usable).length+ },+ async close(): Promise<void> {+ closing = true+ clearInterval(sweep)+ for (const job of queue.splice(0)) {+ job.reject(new Error('svg rasterizer is closing'))+ }+ await Promise.all(+ slots.filter(Boolean).map(+ (slot) =>+ new Promise<void>((done) => {+ if (slot.job) {+ clearTimeout(slot.job.deadline)+ slot.job.job.reject(new Error('svg rasterizer is closing'))+ }+ if (slot.child.exitCode !== null || slot.child.signalCode !== null) {+ done()+ return+ }+ slot.child.once('exit', () => done())+ slot.child.kill('SIGKILL')+ })+ )+ )+ },+ }+}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 2b5493ec173b..be35d2e68c36 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -251,6 +251,12 @@ dependencies = ["rustversion",]+[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"+[[package]]name = "arrayvec"version = "0.7.6"@@ -3765,6 +3771,12 @@ version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"+[[package]]+name = "data-url"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+[[package]]name = "dateparser"version = "0.2.1"@@ -4532,6 +4544,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]+[[package]]name = "event-listener"version = "2.5.3"@@ -4851,6 +4872,12 @@ dependencies = ["zlib-rs",]+[[package]]+name = "float-cmp"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"+[[package]]name = "float-cmp"version = "0.10.0"@@ -6226,6 +6253,12 @@ dependencies = ["png",]+[[package]]+name = "imagesize"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"+[[package]]name = "include_dir"version = "0.7.4"@@ -7044,6 +7077,18 @@ dependencies = ["tracing",]+[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]+[[package]]name = "kv-log-macro"version = "1.0.7"@@ -9467,6 +9512,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]+[[package]]name = "portable-atomic"version = "1.13.1"@@ -9516,7 +9570,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.10.0"+version = "0.11.0"dependencies = ["ahash 0.8.12","anyhow",@@ -10757,6 +10811,8 @@ dependencies = ["lru","neon","posthog-replay-anonymizer",+ "resvg",+ "roxmltree","serde","serde_json","sha2 0.10.9",@@ -10898,6 +10954,21 @@ dependencies = ["web-sys",]+[[package]]+name = "resvg"+version = "0.48.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"+dependencies = [+ "bytemuck",+ "log",+ "pico-args",+ "rgb",+ "svgtypes",+ "tiny-skia",+ "usvg",+]+[[package]]name = "rfc6979"version = "0.4.0"@@ -11046,6 +11117,15 @@ dependencies = ["librocksdb-sys",]+[[package]]+name = "roxmltree"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb"+dependencies = [+ "memchr",+]+[[package]]name = "rsa"version = "0.9.10"@@ -11916,6 +11996,15 @@ dependencies = ["time",]+[[package]]+name = "simplecss"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"+dependencies = [+ "log",+]+[[package]]name = "siphasher"version = "0.3.11"@@ -12337,6 +12426,15 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9091b6114800a5f2141aee1d1b9d6ca3592ac062dc5decb3764ec5895a47b4eb"+[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+dependencies = [+ "float-cmp 0.9.0",+]+[[package]]name = "string_cache"version = "0.8.9"@@ -12471,6 +12569,16 @@ version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]+name = "svgtypes"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"+dependencies = [+ "kurbo",+ "siphasher 1.0.2",+]+[[package]]name = "swc_atoms"version = "9.0.0"@@ -13222,6 +13330,32 @@ dependencies = ["crunchy",]+[[package]]+name = "tiny-skia"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]+[[package]]name = "tiny_http"version = "0.12.0"@@ -14153,6 +14287,25 @@ dependencies = ["tonic-build 0.12.3",]+[[package]]+name = "usvg"+version = "0.48.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"+dependencies = [+ "data-url",+ "imagesize",+ "kurbo",+ "log",+ "pico-args",+ "roxmltree",+ "simplecss",+ "siphasher 1.0.2",+ "strict-num",+ "svgtypes",+ "tiny-skia-path",+]+[[package]]name = "utf8-zero"version = "0.8.1"@@ -14243,7 +14396,7 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8"dependencies = [- "float-cmp",+ "float-cmp 0.10.0","halfbrown","itoa","ryu",diff --git a/rust/replay-anonymizer-node/Cargo.toml b/rust/replay-anonymizer-node/Cargo.tomlindex daa37e6458af..ee45bfe65b03 100644--- a/rust/replay-anonymizer-node/Cargo.toml+++ b/rust/replay-anonymizer-node/Cargo.toml@@ -16,6 +16,9 @@ neon = { workspace = true, features = ["external-buffers"] }# default-features = false: the offline typed-parse module has no place in the ingestion cdylib.posthog-replay-anonymizer = { path = "../replay-anonymizer", default-features = false }brotlic = "0.8"+# No text or embedded raster images: SVG text never renders, and nothing beyond the document is read.+resvg = { version = "0.48", default-features = false }+roxmltree = "0.21"lru = "0.12"serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 16ce3b3131e8..5938227e92cf 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -8,12 +8,13 @@//! `tests/fixtures/`, which the Jest suite runs against through this addon.//!//! It also carries the image-scrub sidecar's pixel layout conversions (`pixels`), which fill model-//! inputs in place in typed arrays that the sidecar allocates, and the produce lanes' ref dedup-//! caches (`dedup`), which hold their entries outside the V8 heap.+//! inputs in place in typed arrays that the sidecar allocates, its SVG rasterizer (`svg`), and the+//! produce lanes' ref dedup caches (`dedup`), which hold their entries outside the V8 heap.mod brotli;mod dedup;mod pixels;+mod svg;use std::collections::HashSet;use std::sync::{Arc, RwLock};@@ -512,6 +513,15 @@ fn rgb_to_rgba_ffi(mut cx: FunctionContext) -> JsResult<JsUndefined> {convert_in_place(&mut cx, rgb, rgba, pixels::rgb_to_rgba)}+fn rasterize_svg_ffi(mut cx: FunctionContext) -> JsResult<JsBuffer> {+ let document = cx.argument::<JsUint8Array>(0)?;+ let rendered = svg::rasterize_svg(document.as_slice(&cx));+ match rendered {+ Ok(png) => JsBuffer::from_slice(&mut cx, &png),+ Err(reason) => cx.throw_error(reason),+ }+}+fn ref_dedup_cache_new(mut cx: FunctionContext) -> JsResult<JsBox<DedupCacheHandle>> {let capacity = cx.argument::<JsNumber>(0)?.value(&mut cx);if !(capacity.is_finite() && capacity >= 0.0 && capacity.fract() == 0.0) {@@ -628,6 +638,7 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("rgbToChw", rgb_to_chw_ffi)?;cx.export_function("rgbToNormalizedChw", rgb_to_normalized_chw_ffi)?;cx.export_function("rgbToRgba", rgb_to_rgba_ffi)?;+ cx.export_function("rasterizeSvg", rasterize_svg_ffi)?;cx.export_function("refDedupCacheNew", ref_dedup_cache_new)?;cx.export_function("refDedupCacheClaimRefs", ref_dedup_cache_claim_refs)?;cx.export_function("refDedupCacheReleaseRefs", ref_dedup_cache_release_refs)?;diff --git a/rust/replay-anonymizer-node/src/svg.rs b/rust/replay-anonymizer-node/src/svg.rsnew file mode 100644index 000000000000..468eb889d983--- /dev/null+++ b/rust/replay-anonymizer-node/src/svg.rs@@ -0,0 +1,176 @@+//! The renderer has no text or raster-image support and every nested image reference is refused, so+//! the PNG holds only shapes and nothing beyond the document is read.++use posthog_replay_anonymizer::collect::{DROP_SVG, DROP_SVG_TOO_COMPLEX};+use posthog_replay_anonymizer::svg::MAX_SVG_BYTES;+use resvg::{tiny_skia, usvg};++const MIN_RASTER_SIDE: f32 = 256.0;+const MAX_RASTER_SIDE: f32 = 512.0;+pub const DROP_SVG_TOO_LARGE: &str = "image_svg_too_large";++const MAX_NODES: u32 = 2_000;+const MAX_DEPTH: usize = 32;+const MAX_USES: usize = 8;+const REFUSED_ELEMENTS: &[&str] = &["filter", "mask", "pattern", "foreignObject"];++fn refuses_effects(text: &str) -> bool {+ text.contains("filter") || text.contains("mask")+}++/// Refusing DTDs also rules out entity expansion.+fn check_render_budget(document: &[u8]) -> Result<(), &'static str> {+ let text = std::str::from_utf8(document).map_err(|_| DROP_SVG)?;+ let options = roxmltree::ParsingOptions {+ allow_dtd: false,+ nodes_limit: MAX_NODES,+ ..roxmltree::ParsingOptions::default()+ };+ let parsed =+ roxmltree::Document::parse_with_options(text, options).map_err(|error| match error {+ roxmltree::Error::NodesLimitReached => DROP_SVG_TOO_COMPLEX,+ _ => DROP_SVG,+ })?;+ let mut uses = 0;+ for node in parsed.descendants().filter(|node| node.is_element()) {+ let name = node.tag_name().name();+ if node.ancestors().count() > MAX_DEPTH || REFUSED_ELEMENTS.contains(&name) {+ return Err(DROP_SVG_TOO_COMPLEX);+ }+ if name == "use" {+ uses += 1;+ }+ if name == "style" && node.text().is_some_and(refuses_effects) {+ return Err(DROP_SVG_TOO_COMPLEX);+ }+ let effect_attribute = node.attributes().any(|attribute| {+ matches!(attribute.name(), "filter" | "mask")+ || (attribute.name() == "style" && refuses_effects(attribute.value()))+ });+ if effect_attribute || uses > MAX_USES {+ return Err(DROP_SVG_TOO_COMPLEX);+ }+ }+ Ok(())+}++pub fn rasterize_svg(document: &[u8]) -> Result<Vec<u8>, &'static str> {+ if document.len() > MAX_SVG_BYTES {+ return Err(DROP_SVG_TOO_LARGE);+ }+ check_render_budget(document)?;+ let options = usvg::Options {+ image_href_resolver: usvg::ImageHrefResolver {+ resolve_data: Box::new(|_, _, _| None),+ resolve_string: Box::new(|_, _| None),+ },+ ..usvg::Options::default()+ };+ let tree = usvg::Tree::from_data(document, &options).map_err(|_| DROP_SVG)?;+ let size = tree.size();+ let long = size.width().max(size.height());+ let scale = long.clamp(MIN_RASTER_SIDE, MAX_RASTER_SIDE) / long;+ let width = (size.width() * scale).ceil().max(1.0) as u32;+ let height = (size.height() * scale).ceil().max(1.0) as u32;+ let mut pixmap = tiny_skia::Pixmap::new(width, height).ok_or(DROP_SVG)?;+ resvg::render(+ &tree,+ tiny_skia::Transform::from_scale(scale, scale),+ &mut pixmap.as_mut(),+ );+ pixmap.encode_png().map_err(|_| DROP_SVG)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn png_dims(png: &[u8]) -> (u32, u32) {+ assert!(png.starts_with(b"\x89PNG"), "not a png");+ let be = |i: usize| u32::from_be_bytes(png[i..i + 4].try_into().unwrap());+ (be(16), be(20))+ }++ fn decode(png: &[u8]) -> Vec<[u8; 4]> {+ let pixmap = tiny_skia::Pixmap::decode_png(png).unwrap();+ pixmap+ .data()+ .chunks_exact(4)+ .map(|p| [p[0], p[1], p[2], p[3]])+ .collect()+ }++ #[test]+ fn renders_shapes_at_a_bounded_size() {+ let square = "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='8'><rect width='16' height='8' fill='red'/></svg>";+ let png = rasterize_svg(square.as_bytes()).expect("renders");+ assert_eq!(png_dims(&png), (256, 128));+ assert!(decode(&png).iter().all(|p| *p == [255, 0, 0, 255]));+ let huge = "<svg xmlns='http://www.w3.org/2000/svg' width='100000' height='50000'/>";+ assert_eq!(+ png_dims(&rasterize_svg(huge.as_bytes()).unwrap()),+ (512, 256)+ );+ }++ #[test]+ fn draws_no_text_and_reads_no_files() {+ let text = "<svg xmlns='http://www.w3.org/2000/svg' width='64' height='64'><text x='0' y='32' font-size='32'>secret</text></svg>";+ let file = "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='64' height='64'><image width='64' height='64' xlink:href='/etc/hosts'/></svg>";+ for doc in [text, file] {+ let png = rasterize_svg(doc.as_bytes()).unwrap();+ assert!(+ decode(&png).iter().all(|p| p[3] == 0),+ "nothing drawn: {doc}"+ );+ }+ }++ #[test]+ fn refuses_what_the_lane_would_refuse() {+ assert_eq!(rasterize_svg(b"not svg"), Err(DROP_SVG));+ let mut big = b"<svg xmlns='http://www.w3.org/2000/svg'>".to_vec();+ big.resize(MAX_SVG_BYTES + 1, b' ');+ assert_eq!(rasterize_svg(&big), Err(DROP_SVG_TOO_LARGE));+ }++ #[test]+ fn refuses_what_it_cannot_parse_or_render_in_bounded_time() {+ let svg = |body: &str| {+ format!("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8'>{body}</svg>")+ };+ let nested = format!("{}<rect/>{}", "<g>".repeat(40), "</g>".repeat(40));+ let uses = "<rect id='r'/>".to_string() + &"<use href='#r'/>".repeat(9);+ let rects = "<rect/>".repeat(2_500);+ let cases = [+ ("not svg".to_string(), DROP_SVG),+ (+ format!("<!DOCTYPE svg [<!ENTITY a 'b'>]>{}", svg("&a;")),+ DROP_SVG,+ ),+ (+ svg("<filter id='f'/><rect filter='url(#f)'/>"),+ DROP_SVG_TOO_COMPLEX,+ ),+ (+ svg("<rect style='filter: blur(4px)'/>"),+ DROP_SVG_TOO_COMPLEX,+ ),+ (+ svg("<style>rect { mask: url(#m) }</style><rect/>"),+ DROP_SVG_TOO_COMPLEX,+ ),+ (svg(&nested), DROP_SVG_TOO_COMPLEX),+ (svg(&uses), DROP_SVG_TOO_COMPLEX),+ (svg(&rects), DROP_SVG_TOO_COMPLEX),+ ];+ for (doc, reason) in cases {+ assert_eq!(+ check_render_budget(doc.as_bytes()),+ Err(reason),+ "{}",+ &doc[..doc.len().min(80)]+ );+ }+ }+}diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex aa6da2873d77..fe25289f94c6 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.10.0"+version = "0.11.0"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, image collection for an out-of-band scrub, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex 1817843dfbc1..b35d4c0738ae 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -130,7 +130,8 @@ pub const MAX_TOTAL_BYTES_PER_MESSAGE: usize = 64 * 1024 * 1024;/// Why an image did not reach the scrub lane. Each one is blanked and counted under this reason.pub(crate) const DROP_COLLECTION_OFF: &str = "image_collection_off";pub(crate) const DROP_NOT_RASTER: &str = "image_not_base64_raster";-pub(crate) const DROP_SVG: &str = "image_svg";+pub const DROP_SVG: &str = "image_svg";+pub const DROP_SVG_TOO_COMPLEX: &str = "image_svg_too_complex";pub(crate) const DROP_BMP: &str = "image_bmp";pub(crate) const DROP_AVIF: &str = "image_avif";pub(crate) const DROP_TOO_LARGE: &str = "image_too_large";@@ -259,18 +260,14 @@ pub fn collectable_data_uri_bytes(.and_then(|rest| rest.split_once(',')).ok_or(DROP_NOT_RASTER)?;let meta = meta.to_ascii_lowercase();- if !meta.starts_with("image/") || !meta.contains("base64") {- return Err(if meta.starts_with("image/svg") {- DROP_SVG- } else {- DROP_NOT_RASTER- });- }let mime_type = meta.split_once(';').map_or(meta.as_str(), |(mime_type, _)| mime_type);if mime_type.starts_with("image/svg") {- return Err(DROP_SVG);+ return crate::svg::svg_document(&meta, payload, max_image_bytes);+ }+ if !meta.starts_with("image/") || !meta.contains("base64") {+ return Err(DROP_NOT_RASTER);}if mime_type.contains("bmp") {return Err(DROP_BMP);@@ -391,8 +388,8 @@ mod tests {}#[test]- fn collectable_rejects_svg_non_base64_and_non_image() {- assert!(collectable("data:image/svg+xml;base64,PHN2Zz4=").is_none());+ fn collectable_rejects_broken_svg_non_base64_and_non_image() {+ assert!(collectable("data:image/svg+xml;base64,bm90IHN2Zw==").is_none());assert!(collectable("data:image/bmp;base64,Qk0=").is_none());assert!(collectable("data:image/x-bmp;base64,Qk0=").is_none());assert!(collectable("data:image/x-ms-bmp;base64,Qk0=").is_none());@@ -400,7 +397,10 @@ mod tests {// AVIF bytes behind a raster label.assert!(collectable("data:image/png;base64,AAAAHGZ0eXBhdmlm").is_none());assert!(collectable("data:image/png;base64,Qk0=").is_none());- assert!(collectable("data:image/svg+xml;utf8,<svg/>").is_none());+ assert_eq!(+ collectable("data:image/svg+xml;utf8,<svg/>").as_deref(),+ Some(b"<svg/>".as_slice())+ );assert!(collectable("data:text/plain;base64,aGk=").is_none());assert!(collectable("data:image/png;utf8,notbase64").is_none());assert!(collectable("data:image/png;base64,%%%").is_none());@@ -437,10 +437,18 @@ mod tests {#[test]fn collectable_mime_checks_are_case_insensitive() {- // MIME types are case-insensitive; a mixed-case SVG must not dodge the text-format- // exclusion, and a mixed-case raster/base64 marker must still collect.- assert!(collectable("data:image/SVG+xml;base64,PHN2Zz4=").is_none());- assert!(collectable("data:image/Svg+Xml;base64,PHN2Zz4=").is_none());+ // MIME types are case-insensitive; a mixed-case SVG must still take the SVG path, which+ // alone accepts a URL-encoded payload, and a mixed-case raster/base64 marker must collect.+ for uri in [+ "data:image/SVG+xml;utf8,<svg/>",+ "data:image/Svg+Xml;utf8,<svg/>",+ ] {+ assert_eq!(+ collectable(uri).as_deref(),+ Some(b"<svg/>".as_slice()),+ "{uri}"+ );+ }assert_eq!(collectable("data:image/PNG;BASE64,aGVsbG8=").as_deref(),Some(b"hello".as_slice())diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 61fc3f8374f9..f869c16642ad 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -12,7 +12,7 @@ use anyhow::{bail, Result};use serde::Serialize;use crate::allow_lists::AllowLists;-use crate::assets::PLACEHOLDER_SRC;+use crate::assets::{is_numbered_placeholder, PLACEHOLDER_SRC};use crate::collect::{collectable_data_uri_bytes, is_image_ref, CollectedImage, ImageCollection, ImageCollector,DROP_COLLECTION_OFF, DROP_MESSAGE_CAP, MAX_IMAGE_BYTES,@@ -123,6 +123,14 @@ impl<'a> Ctx<'a> {/// to the caller for the out-of-band scrub. An image the lane cannot take is replaced by/// `fallback` and counted, never passed through or scrubbed here.pub(crate) fn scrub_image(&self, original: &str, fallback: ImageFallback) -> String {+ // This anonymizer's own stand-ins, met again on a re-scrub, carry no page content. A numbered+ // placeholder's digits are free text a page could forge, so it is trusted only on a re-scrub.+ if original == PLACEHOLDER_SRC+ || original == blank_image_data_uri()+ || (self.keeps_image_refs() && is_numbered_placeholder(original))+ {+ return original.to_string();+ }match self.collect_image(original) {Ok(reference) => reference,Err(reason) => {@@ -405,6 +413,38 @@ mod tests {assert_eq!(ctx.into_collected_images().len(), 1);}+ #[test]+ fn this_anonymizers_own_stand_ins_are_never_collected() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let lane = || Some(ImageCollection::new("42".to_string(), "k".repeat(32)));+ let numbered = crate::assets::numbered_placeholder(7);+ let cases = [+ (+ Ctx::with_image_collection(&allow, lane()),+ PLACEHOLDER_SRC.to_string(),+ true,+ ),+ (+ Ctx::with_image_collection(&allow, lane()),+ blank_image_data_uri(),+ true,+ ),+ (+ Ctx::with_image_collection(&allow, lane()).preserving_image_refs(),+ numbered.clone(),+ true,+ ),+ // Untrusted input: the digits could carry anything, so it goes through the scrub.+ (Ctx::with_image_collection(&allow, lane()), numbered, false),+ ];+ for (ctx, original, kept) in cases {+ let scrubbed = ctx.scrub_image(&original, ImageFallback::Placeholder);+ assert_eq!(scrubbed == original, kept, "{original}");+ assert!(ctx.take_scrub_drops().is_empty());+ assert_eq!(ctx.into_collected_images().is_empty(), kept);+ }+ }+#[test]fn an_image_the_lane_cannot_take_is_blanked_and_counted() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());@@ -424,7 +464,7 @@ mod tests {),(Ctx::with_image_collection(&allow, lane()),- "data:image/svg+xml;base64,PHN2Zz4=".to_string(),+ "data:image/svg+xml;base64,bm90IHN2Zw==".to_string(),crate::collect::DROP_SVG,),(diff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rsindex 98b5c47f30f6..5bc9fc4fe3bb 100644--- a/rust/replay-anonymizer/src/css.rs+++ b/rust/replay-anonymizer/src/css.rs@@ -811,7 +811,7 @@ mod tests {}#[test]- fn inline_svg_in_css_stays_out_of_the_collection_lane() {+ fn inline_svg_in_css_reaches_the_collection_lane_as_its_document() {let allow = AllowLists::default();let ctx = Ctx::with_image_collection(&allow,@@ -823,10 +823,11 @@ mod tests {let original = "data:image/svg+xml;base64,PHN2Zz48dGV4dD5qb2huLmZha2VuYW1lQGV4YW1wbGUuY29tPC90ZXh0Pjwvc3ZnPg==";let css = format!("background-image:url('{original}')");let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");- assert!(rewritten.refs.is_empty());+ assert_eq!(rewritten.refs.len(), 1);assert!(!rewritten.css.contains(original));- assert!(rewritten.css.contains("data:image/png;base64"));- assert!(ctx.take_image_source_counts().is_empty());+ let images = ctx.into_collected_images();+ assert_eq!(images.len(), 1);+ assert!(images[0].bytes.starts_with(b"<svg>"));}#[test]diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex e006a04f427c..95fe7dc553e6 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -54,6 +54,8 @@ pub mod snapshot;#[doc(hidden)]pub mod srcset;#[doc(hidden)]+pub mod svg;+#[doc(hidden)]pub mod text;pub mod timings;#[cfg(feature = "typed-parse")]diff --git a/rust/replay-anonymizer/src/svg.rs b/rust/replay-anonymizer/src/svg.rsnew file mode 100644index 000000000000..e395cd6f3c88--- /dev/null+++ b/rust/replay-anonymizer/src/svg.rs@@ -0,0 +1,88 @@+//! The scrub parses and renders an SVG in a process it kills at a deadline, because neither cost is+//! bounded by document size. Only the bytes are checked here, so nothing here can be made slow.++use base64::Engine;++use crate::collect::{DROP_SVG, DROP_TOO_LARGE};++pub const MAX_SVG_BYTES: usize = 256 * 1024;++/// The scrub tells an SVG from a raster image by its leading `<`.+fn starts_with_markup(document: &[u8]) -> bool {+ let body = document.strip_prefix(b"\xef\xbb\xbf").unwrap_or(document);+ body.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'<')+}++pub(crate) fn svg_document(+ meta: &str,+ payload: &str,+ max_input_bytes: usize,+) -> Result<Vec<u8>, &'static str> {+ let max_input_bytes = max_input_bytes.min(MAX_SVG_BYTES);+ if payload.len() > max_input_bytes.saturating_mul(3) {+ return Err(DROP_TOO_LARGE);+ }+ let document: Vec<u8> = if meta.contains(";base64") {+ base64::engine::general_purpose::STANDARD+ .decode(payload.as_bytes())+ .map_err(|_| DROP_SVG)?+ } else {+ percent_encoding::percent_decode_str(payload).collect()+ };+ if document.len() > max_input_bytes {+ return Err(DROP_TOO_LARGE);+ }+ if !starts_with_markup(&document) {+ return Err(DROP_SVG);+ }+ Ok(document)+}+#[cfg(test)]+mod tests {+ use super::*;++ const SQUARE: &str =+ "<svg xmlns='http://www.w3.org/2000/svg' width='16' height='8'><rect width='16' height='8' fill='red'/></svg>";++ #[test]+ fn decodes_base64_and_url_encoded_documents() {+ let b64 = base64::engine::general_purpose::STANDARD.encode(SQUARE);+ let encoded: String =+ percent_encoding::utf8_percent_encode(SQUARE, percent_encoding::NON_ALPHANUMERIC)+ .to_string();+ for (meta, payload) in [+ ("image/svg+xml;base64", b64.as_str()),+ ("image/svg+xml;utf8", encoded.as_str()),+ ("image/svg+xml;charset=utf-8", SQUARE),+ ] {+ assert_eq!(+ svg_document(meta, payload, 1 << 20).as_deref(),+ Ok(SQUARE.as_bytes()),+ "{meta}"+ );+ }+ }++ #[test]+ fn refuses_what_the_scrub_would_not_take_as_svg() {+ let cases = [+ ("not svg".to_string(), DROP_SVG),+ (+ format!("<svg>{}</svg>", " ".repeat(MAX_SVG_BYTES)),+ DROP_TOO_LARGE,+ ),+ ];+ for (doc, reason) in cases {+ assert_eq!(+ svg_document("image/svg+xml;utf8", &doc, 1 << 30),+ Err(reason),+ "{}",+ &doc[..doc.len().min(80)]+ );+ }+ assert_eq!(+ svg_document("image/svg+xml;utf8", SQUARE, 16),+ Err(DROP_TOO_LARGE)+ );+ }+}diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rsindex 2bf56143dbea..dd0091dacf53 100644--- a/rust/replay-anonymizer/tests/ref_idempotence.rs+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs@@ -124,8 +124,8 @@ fn a_namespaced_url_ref_survives_only_a_trusted_rescrub() {for url_ref in [URL_REF, LEGACY_URL_REF] {let mut line = img_line(url_ref, "data-anon-image-ref-src");let attrs = &mut line[1]["data"]["adds"][0]["node"]["attributes"];- attrs["src"] = json!("data:image/svg+xml;base64,PHN2Zz4=");- attrs["srcset"] = json!("data:image/svg+xml;base64,PHN2Zz4=");+ attrs["src"] = json!("data:image/svg+xml;base64,bm90IHN2Zw==");+ attrs["srcset"] = json!("data:image/svg+xml;base64,bm90IHN2Zw==");assert!(scrub_trusted(&line).contains(url_ref));assert!(!scrub_default(&line).contains("data-anon-image-ref-src"));for byte_walk in [true, false] {diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex 6619fd8eebee..868c3ae453d4 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -1016,8 +1016,7 @@ fn image_collection_off_blanks_images_and_returns_no_bytes() {}#[test]-fn image_collection_blanks_svg() {- // SVG is text — PII inside it must not ride to the scrub topic as an "image".+fn image_collection_sends_svg_to_the_scrub_as_its_document() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());use base64::Engine;let svg = base64::engine::general_purpose::STANDARD.encode(@@ -1045,14 +1044,8 @@ fn image_collection_blanks_svg() {).expect("anonymizes");let lines = String::from_utf8(out.lines.clone()).unwrap();- assert!(out.meta.images.is_empty(), "svg must not be collected");- assert!(out.meta.image_sources.is_empty());+ assert_eq!(out.meta.images.len(), 1, "collected once");+ assert!(out.image_bytes.starts_with(b"<svg"));assert!(!lines.contains(&svg), "raw svg must not pass through");- let drops: Vec<_> = out- .meta- .scrub_drops- .iter()- .map(|d| (d.reason, d.count))- .collect();- assert_eq!(drops, vec![("image_svg", 1)]);+ assert!(out.meta.scrub_drops.is_empty());}diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex c30325f1062f..d092038e558d 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -512,7 +512,7 @@ fn unusable_srcset_keeps_the_src_fallback() {"https://cdn.example.com/a.png?token=secret 2x","https://127.0.0.1/a.png 2x","data:image/png;base64,%%% 2x",- "data:image/svg+xml;base64,PHN2Zz4= 2x",+ "data:image/svg+xml;base64,bm90IHN2Zw== 2x",] {for (engine, result) in run(json!({