Skip to content

: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.

fix(replay): narrow the ml mirror image lane to png, jpeg, gif and webp (#103957)

Tom Piccirello1788f594e4ef
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
index 1aac6bdf8e40..f24daaab3b5c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
@@ -562,7 +562,6 @@ the userinfo of a URL, cookies, and known credential query parameters
| `image/jpeg` | JPEG |
| `image/gif` | GIF |
| `image/webp` | WebP |
-| `image/avif` | AVIF |
**14.11** This lane does not check that the downloaded bytes match the expected media type. It is expected that the image scrubber will do this.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
index 0ce41ad3da43..949bd7249a51 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.test.ts
@@ -151,6 +151,7 @@ describe('HttpImageFetcher', () => {
['a type that is not an image', 'text/html', PNG, 'not_image'],
['a type outside the raster set', 'image/svg+xml', PNG, 'not_image'],
['the BMP format', 'image/bmp', Buffer.from('BM'), 'not_image'],
+ ['the AVIF format', 'image/avif', Buffer.from('\x00\x00\x00\x18ftypavif', 'binary'), 'not_image'],
['a payload that is not the declared format', 'image/gif', PNG, 'ok'],
['a payload of the wrong raster format', 'image/png', GIF, 'ok'],
])('handles %s', async (_name, contentType, bytes, outcome) => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
index 89531d138a8d..46576f2dc5b5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher.ts
@@ -12,8 +12,12 @@ import { WebBotAuthRequestSigner } from './web-bot-auth'
*
* SVG is absent on purpose. It is a text format that can carry the page's own data, so its redaction
* belongs on the inline path rather than on an image model.
+ *
+ * AVIF is absent because the image scrubber unblocks only the PNG, JPEG, GIF and WebP loaders
+ * (`sharp.unblock` in the sidecar's image-input.ts), so it would reject every AVIF image that this
+ * lane fetched.
*/
-const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif'] as const
+const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const
export type ImageContentType = (typeof ALLOWED_CONTENT_TYPES)[number]
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
index 9783a9686d04..a35cc886c71c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
@@ -29,6 +29,10 @@ import { limitsFromEnv, planScales } from '../src/scale-plan.ts'
import { type Src } from '../src/src-image.ts'
import { detectFacesYunet, loadYunet } from '../src/yunet.ts'
+// yunet.ts loads image-input.ts, which blocks every loader except PNG, JPEG, GIF and WebP for the whole process.
+// zxing writes the QR fixture as SVG, so this script unblocks the SVG loader again.
+sharp.unblock({ operation: ['VipsForeignLoadSvg'] })
+
const wasmFile = createRequire(`${process.cwd()}/`).resolve('zxing-wasm/writer/zxing_writer.wasm')
const wasmBytes = readFileSync(wasmFile)
prepareZXingModule({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts
index bdbe1c81796f..306e7e0e24b3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts
@@ -24,6 +24,10 @@ import { detectTextDbnet, loadDbnet } from '../src/dbnet.ts'
import { limitsFromEnv, planScales } from '../src/scale-plan.ts'
import { decodeSrc } from '../src/src-image.ts'
+// src-image.ts loads image-input.ts, which blocks every loader except PNG, JPEG, GIF and WebP for the whole process.
+// This script draws its frames as SVG, so it unblocks the SVG loader again.
+sharp.unblock({ operation: ['VipsForeignLoadSvg'] })
+
const FRAME_W = 1280
const FRAME_H = 720
const PHRASE = 'Account 4242 4242 4242 4242'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts
index 48d4600eaf4e..85a29baec5c0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.test.ts
@@ -7,14 +7,15 @@ describe('blur', () => {
// A capture can name a data URI `image/png` and put any bytes after the comma, and libvips
// dispatches on magic bytes rather than that name, so the loader set is what actually bounds
- // which decoders user content can reach. TIFF is blocked; the fetcher formats stay reachable.
+ // which decoders user content can reach. image-input.ts allows only the PNG, JPEG, GIF and WebP
+ // loaders. The rejection rows below cover every other loader in sharp's libvips that accepts a
+ // buffer: TIFF, HEIF (AVIF and HEIC) and SVG.
//
- // The native VIPS format (`VipsForeignLoadVips`, also blocked in image-input.ts) has no row here: a
- // real `.v`/`.vips` buffer, built with the `vips` CLI, fails to decode with the identical
- // "unsupported image format" error whether or not the block is applied, so there is no buffer
- // that can exercise that branch either way. Blocking it only guards a call path that loads
- // from a file path, which nothing in this sidecar does today.
- it.each(['gif', 'png', 'jpeg', 'webp', 'avif'])('decodes %s input', async (format) => {
+ // Loaders that libvips compiles in but that take no buffer input have no row here. That covers
+ // CSV, matrix and the native VIPS format: a real `.v`/`.vips` buffer, built with the `vips` CLI,
+ // fails to decode with the identical "unsupported image format" error whether or not the block is
+ // applied, so no buffer can exercise that branch either way.
+ it.each(['gif', 'png', 'jpeg', 'webp'])('decodes %s input', async (format) => {
const bytes = await swatch()
.toFormat(format as keyof FormatEnum)
.toBuffer()
@@ -22,9 +23,46 @@ describe('blur', () => {
await expect(blurOnly(bytes)).resolves.toBeInstanceOf(Buffer)
})
- it('rejects TIFF input because it is not an accepted fetcher format', async () => {
- const bytes = await swatch().tiff().toBuffer()
+ // An UltraHDR JPEG (for example from an Android camera) carries an ISO 21496-1 gain map after the
+ // primary image. libvips gives such a file to its UltraHDR loader when that loader is available,
+ // and the allowlist blocks that loader, so this case proves that the file still decodes through
+ // the plain JPEG loader, which ignores the gain map.
+ it('decodes a JPEG that carries a gain map', async () => {
+ // sharp 0.35.3 implements withGainMap(), but its type declarations do not include it.
+ const gainMapped = swatch() as Sharp & { withGainMap: () => Sharp }
+ const bytes = await gainMapped.withGainMap().jpeg().toBuffer()
+ expect(bytes.includes('urn:iso:std:iso:ts:21496')).toBe(true)
- await expect(blurOnly(bytes)).rejects.toBeInstanceOf(UndecodableImageError)
+ await expect(blurOnly(bytes)).resolves.toBeInstanceOf(Buffer)
+ })
+
+ // sharp's prebuilt libvips has no HEVC encoder, so the HEIC case relabels an AVIF file's major
+ // (offset 8) and compatible (offset 16 on) ftyp brands as `heic`. The HEIF loader claims a buffer
+ // by those brands, so the block has to reject it too.
+ const heicBranded = async (): Promise<Buffer> => {
+ const bytes = await swatch().avif().toBuffer()
+ bytes.write('heic', 8, 'ascii')
+ for (let offset = 16; offset + 4 <= bytes.readUInt32BE(0); offset += 4) {
+ bytes.write('heic', offset, 'ascii')
+ }
+ return bytes
+ }
+
+ it.each([
+ ['TIFF', () => swatch().tiff().toBuffer()],
+ ['AVIF', () => swatch().avif().toBuffer()],
+ ['HEIC', heicBranded],
+ [
+ 'SVG',
+ async () =>
+ Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="#0af"/></svg>'
+ ),
+ ],
+ ])('rejects %s input as an unsupported format', async (_format, encode) => {
+ const error = await blurOnly(await encode()).catch((e: unknown) => e)
+
+ expect(error).toBeInstanceOf(UndecodableImageError)
+ expect(error).toMatchObject({ reason: 'unsupported_format' })
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
index f0889aed056e..3eb5d56e0747 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
@@ -41,19 +41,15 @@ describe('compose', () => {
}> {
// Flush to every edge of the box on purpose: a resize kernel reaching outward from the box
// boundary has to find content there, or the fixture cannot show the leak it exists to catch.
- const strokes = []
+ //
+ // The strokes are written straight into 3-channel raw pixels, which is the layout Src declares,
+ // because image-input.ts blocks the SVG loader for the whole process.
+ const data = Buffer.alloc(W * H * 3, 0xff)
for (let y = box.top; y < box.top + box.height; y += 24) {
- strokes.push(`<rect x="${box.left}" y="${y}" width="${box.width}" height="5" fill="#000000"/>`)
+ for (let row = y; row < Math.min(y + 5, H); row++) {
+ data.fill(0, (row * W + box.left) * 3, (row * W + box.left + box.width) * 3)
+ }
}
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">
- <rect width="${W}" height="${H}" fill="#ffffff"/>${strokes.join('')}</svg>`
- // flatten to 3 channels exactly as decodeSrc does: Src is declared 3-channel, and an SVG
- // renders with alpha, so skipping it hands compose a buffer it reads misaligned.
- const { data, info } = await sharp(Buffer.from(svg))
- .flatten({ background: '#fff' })
- .raw()
- .toBuffer({ resolveWithObject: true })
- expect(info.channels).toBe(3)
return { data, W, H, format: 'png', inputPixels: W * H }
}
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.ts
index 32eeb285533e..8167448f1408 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
@@ -5,8 +5,14 @@ import { imageMetadataProhibitsAiTraining } from './xmp.ts'
// One libvips thread per operation and no shared cache bound CPU and memory to the request concurrency limit.
sharp.concurrency(1)
sharp.cache(false)
-// The accepted image types do not need TIFF or native VIPS loaders, so blocking them removes unnecessary decoder paths.
-sharp.block({ operation: ['VipsForeignLoadTiff', 'VipsForeignLoadVips'] })
+// The lane accepts only PNG, JPEG, GIF and WebP, so every other loader is blocked. An allowlist also covers a loader
+// that a later libvips build adds. Blocking or unblocking a class applies to its buffer, file and source subclasses,
+// so any other input, such as TIFF, AVIF, HEIC or SVG, fails as an unsupported format. The UltraHDR loader stays
+// blocked, so a JPEG with a gain map decodes through the JPEG loader, which ignores the gain map.
+sharp.block({ operation: ['VipsForeignLoad'] })
+sharp.unblock({
+ operation: ['VipsForeignLoadPng', 'VipsForeignLoadJpeg', 'VipsForeignLoadNsgif', 'VipsForeignLoadWebp'],
+})
// Compressed image bytes can expand many times in memory, so every decoder applies this pixel limit before allocation.
export const LIMIT_INPUT_PIXELS = 50_000_000
@@ -60,7 +66,7 @@ export async function inspectImage(input: Buffer): Promise<ImageDescription> {
return {
width: metadata.width,
height: metadata.height,
- format: metadata.format === 'heif' ? 'avif' : (metadata.format ?? 'unknown'),
+ format: metadata.format ?? 'unknown',
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
index 711065a7ec5b..283ce5779eb5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
@@ -7,17 +7,18 @@ import {
prepareFetchedImage,
} from './image-transport'
+const AVIF_HEADER = Buffer.concat([
+ Buffer.from([0x00, 0x00, 0x00, 0x18]),
+ Buffer.from('ftypavif', 'ascii'),
+ Buffer.alloc(4),
+ Buffer.from('avifmif1', 'ascii'),
+])
+
const imageHeaders = {
'image/png': Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
'image/jpeg': Buffer.from([0xff, 0xd8, 0xff, 0xe0]),
'image/gif': Buffer.from('GIF89a', 'ascii'),
'image/webp': Buffer.from('RIFF\x04\x00\x00\x00WEBP', 'binary'),
- 'image/avif': Buffer.concat([
- Buffer.from([0x00, 0x00, 0x00, 0x18]),
- Buffer.from('ftypavif', 'ascii'),
- Buffer.alloc(4),
- Buffer.from('avifmif1', 'ascii'),
- ]),
} satisfies Record<(typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number], Buffer>
describe('image transport', () => {
@@ -83,6 +84,7 @@ describe('image transport', () => {
it.each([
['a missing content-type', imageHeaders['image/png'], undefined, 'missing_content_type'],
['a BMP content-type', Buffer.from('BM', 'ascii'), 'image/bmp', 'unsupported_content_type'],
+ ['an AVIF content-type', AVIF_HEADER, 'image/avif', 'unsupported_content_type'],
] as const)('labels %s', async (_case, bytes, contentType, reason) => {
await expect(prepareFetchedImage(bytes, contentType, undefined)).rejects.toMatchObject({ reason })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
index 8811e99aea80..10b20c8fe30b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
@@ -8,7 +8,7 @@ export const CAPTURE_TIMESTAMP_HEADER = 'capture-timestamp-ms'
const MAX_CONTENT_ENCODING_LAYERS = 4
-export const SUPPORTED_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif'] as const
+export const SUPPORTED_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const
export type SupportedImageMediaType = (typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number]
@@ -95,23 +95,6 @@ async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer>
return Buffer.concat(chunks, outputBytes)
}
-function isAvif(bytes: Buffer): boolean {
- if (bytes.length < 16 || bytes.toString('ascii', 4, 8) !== 'ftyp') {
- return false
- }
- const boxSize = bytes.readUInt32BE(0)
- if (boxSize < 16 || boxSize > bytes.length) {
- return false
- }
- for (let offset = 8; offset + 4 <= boxSize; offset += 4) {
- const brand = bytes.toString('ascii', offset, offset + 4)
- if (brand === 'avif' || brand === 'avis') {
- return true
- }
- }
- return false
-}
-
export function isSupportedImageMediaType(contentType: string): contentType is SupportedImageMediaType {
return SUPPORTED_IMAGE_MEDIA_TYPES.includes(contentType as SupportedImageMediaType)
}
@@ -128,8 +111,6 @@ export function imageBytesMatchMediaType(bytes: Buffer, contentType: SupportedIm
}
case 'image/webp':
return bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'
- case 'image/avif':
- return isAvif(bytes)
}
}