: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): make the image-scrub cap configurable (#115615)
Nicholas Waltzcf51aecc288d
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 47731c0fbc04..560697cb306a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -56,6 +56,8 @@ export type MlMirrorConfig = {* both the scrub consumer lane AND ref-aware downstream readers must be live first.*/SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: boolean+ /** At most the sidecar's IMAGE_SCRUB_MAX_BODY_BYTES, or the sidecar refuses the image and its ref dangles. */+ SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGE_BYTES: number/*** Collect the URLs of remote images as well, so the fetch lane can download them later.@@ -258,6 +260,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {SESSION_RECORDING_ML_REDIS_HOST: '',SESSION_RECORDING_ML_REDIS_PORT: 6379,SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: false,+ SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGE_BYTES: 900 * 1024,SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: false,SESSION_RECORDING_ML_URL_PRODUCER_ENABLED: false,SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_ENABLED: true,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 5573a0cff021..8f5f3d049513 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -69,6 +69,7 @@ export interface MlMirrorCollection {/** The root key for image content and URL HMAC keys. */pseudonymSecret: string | BuffercollectImages: boolean+ maxImageBytes: numbercollectUrls: boolean}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.tsindex e95251e539c3..a9df1051c955 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts@@ -47,14 +47,21 @@ async function imageSourceMetricValue(source: string, property: string, kind: st// classification (dlq vs drop), the timestamp window, header/body agreement, and the ParsedMessageData// assembly — not the scrub itself (that's covered by the Rust suite + shared fixtures).const mockAnonymizeKafkaPayload = jest.fn()+const mockMaxImageBytes = jest.fn()jest.mock('@posthog/replay-anonymizer', () => ({anonymizeKafkaPayload: (payload: Buffer,contentEncoding?: string | null,teamId?: string | null,contentKey?: string | null,- urlKey?: string | null- ) => mockAnonymizeKafkaPayload(payload, contentEncoding, teamId, contentKey, urlKey),+ urlKey?: string | null,+ _referenceNamespace?: string | null,+ _producedRefDedup?: unknown,+ maxImageBytes?: number | null+ ) => {+ mockMaxImageBytes(maxImageBytes)+ return mockAnonymizeKafkaPayload(payload, contentEncoding, teamId, contentKey, urlKey)+ },}))describe('createParseAndAnonymizeMessageStep', () => {@@ -217,6 +224,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {const step = createParseAndAnonymizeMessageStep({pseudonymSecret: secret,collectImages: true,+ maxImageBytes: 1234,collectUrls: false,})const teamId = pseudonymize(secret, PSEUDONYM_TEAM, '1')@@ -296,6 +304,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {contentKey,undefined)+ expect(mockMaxImageBytes).toHaveBeenLastCalledWith(1234)expect(result).toMatchObject({type: PipelineResultType.OK,value: { collectedImages: [{ ref: imageRef(expectedTeamId, 'hashA'), bytes: Buffer.from('a') }] },@@ -303,6 +312,17 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {}})+ it.each([0, -1, 1.5, NaN])('refuses to build with maxImageBytes %p', (maxImageBytes) => {+ expect(() =>+ createParseAndAnonymizeMessageStep({+ pseudonymSecret: secret,+ collectImages: true,+ maxImageBytes,+ collectUrls: false,+ })+ ).toThrow('maxImageBytes')+ })+it('unpacks the packed image buffer into per-image produce records', async () => {const packed = Buffer.concat([Buffer.from('aaa'), Buffer.from('bb')])addonSuccessWithImages(packed, [@@ -404,6 +424,7 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {const step = createParseAndAnonymizeMessageStep({pseudonymSecret: secret,collectImages: false,+ maxImageBytes: 1234,collectUrls: true,})@@ -441,6 +462,7 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {const step = createParseAndAnonymizeMessageStep({pseudonymSecret: secret,collectImages: false,+ maxImageBytes: 1234,collectUrls: false,})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.tsindex 626533cbbb0d..f4b0e4783eec 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts@@ -83,6 +83,7 @@ export interface ImageCollectionConfig {pseudonymSecret: string | Buffer/** Replace inlined images with refs and return their bytes for the scrub topic. */collectImages: boolean+ maxImageBytes: number/*** Keep a remote image's placeholder, stash its ref, and return its URL for the fetch lane.*@@ -108,6 +109,13 @@ export function createParseAndAnonymizeMessageStep<imageCollection?: ImageCollectionConfig,producedRefs?: ProducedRefs): ProcessingStep<T, T & ParseAndAnonymizeStepOutput> {+ // The addon rejects a bad cap on every call, which would drop every message while the consumer looks healthy.+ if (+ imageCollection &&+ !(Number.isSafeInteger(imageCollection.maxImageBytes) && imageCollection.maxImageBytes > 0)+ ) {+ throw new Error(`maxImageBytes must be a positive integer, got ${imageCollection.maxImageBytes}`)+ }const globalUrlKey =imageCollection?.collectUrls === true? pseudonymize(imageCollection.pseudonymSecret, PSEUDONYM_IMAGE_URL_KEY, PSEUDONYM_IMAGE_URL_GLOBAL_VALUE)@@ -185,7 +193,8 @@ export function createParseAndAnonymizeMessageStep<teamKeys?.contentKey,globalUrlKey,referenceNamespace,- producedRefDedup(producedRefs, Date.now())+ producedRefDedup(producedRefs, Date.now()),+ imageCollection?.maxImageBytes)} catch (error) {// A rejected promise (native panic, addon load failure) must fail closed.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.tsindex c3905fc06895..4cf3f7c52371 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts@@ -434,9 +434,25 @@ describeAddon('native image collection', () => {expect(second.lines!.toString()).toContain(urlRefs[0])})- it('collects nothing without the collection keys and blurs inline instead', async () => {+ it.each([+ ['without the collection keys', () => rustAddon!.anonymizeKafkaPayload(imagePayload())],+ [+ 'over maxImageBytes',+ () =>+ rustAddon!.anonymizeKafkaPayload(+ imagePayload(),+ undefined,+ PSEUDO_TEAM,+ CONTENT_KEY,+ null,+ null,+ undefined,+ 16+ ),+ ],+ ])('collects nothing %s and blurs inline instead', async (_case, anonymize) => {rustAddon!.initAnonymizer({ text: [], url: [] })- const result = await rustAddon!.anonymizeKafkaPayload(imagePayload())+ const result = await anonymize()expect(result.failed).toBe(false)expect(result.images).toBeNull()expect(result.lines!.toString()).not.toContain(PNG_B64)@@ -451,6 +467,18 @@ describeAddon('native image collection', () => {await expect(rustAddon!.anonymizeKafkaPayload(imagePayload(), undefined, undefined, undefined, CONTENT_KEY)).resolves.toMatchObject({ failed: false })+ await expect(+ rustAddon!.anonymizeKafkaPayload(+ imagePayload(),+ undefined,+ PSEUDO_TEAM,+ CONTENT_KEY,+ null,+ null,+ undefined,+ 0+ )+ ).rejects.toThrow('maxImageBytes')})it('runs either collection lane without the other', async () => {diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex 73e86931770c..52cd737a07d8 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -162,6 +162,7 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer// lane follows its producer flag. The URL lane collects on its own flag,// because collecting alone measures without sending anything anywhere.collectImages: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED,+ maxImageBytes: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_IMAGE_BYTES,collectUrls: this.config.SESSION_RECORDING_ML_URL_COLLECTION_ENABLED,},// Producing needs collection: without it the anonymizer returns no URLs, anddiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 4999aaf5673a..26ecf9f5a013 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -9553,7 +9553,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.7.3"+version = "0.8.0"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 8aea491d0f70..60dd4f6e9da9 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -210,6 +210,9 @@ export function initAnonymizer(allow: AllowListsInput): void {* The two lanes are independent: either, both, or neither. Only `contentKey` needs `teamId`.** `producedRefDedup` leaves out the collected images and URLs that an earlier message already produced.+ *+ * `maxImageBytes` caps the decoded size of a collected image; a bigger one is blurred inline.+ * Omitted, the crate default applies.*/export async function anonymizeKafkaPayload(payload: Buffer,@@ -218,7 +221,8 @@ export async function anonymizeKafkaPayload(contentKey?: string | null,urlKey?: string | null,referenceNamespace?: string | null,- producedRefDedup?: ProducedRefDedup+ producedRefDedup?: ProducedRefDedup,+ maxImageBytes?: number | null): Promise<AnonymizeKafkaPayloadResult> {const result = await native.anonymizeKafkaPayload(payload,@@ -229,7 +233,8 @@ export async function anonymizeKafkaPayload(referenceNamespace ?? undefined,producedRefDedup?.images?.nativeHandle,producedRefDedup?.urls?.nativeHandle,- producedRefDedup?.urlTimeBucket+ producedRefDedup?.urlTimeBucket,+ maxImageBytes ?? undefined)// Timings are best-effort telemetry: a malformed timings blob must never fail the message.let timings: AnonymizeTimings | null = nulldiff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 019caff0caa6..217273191aee 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -188,6 +188,21 @@ fn opt_dedup_cache_arg(}}+fn opt_max_image_bytes_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<Option<usize>> {+ let value = match cx.argument_opt(index) {+ Some(v) if v.is_a::<JsUndefined, _>(cx) || v.is_a::<JsNull, _>(cx) => return Ok(None),+ Some(v) => v.downcast_or_throw::<JsNumber, _>(cx)?.value(cx),+ None => return Ok(None),+ };+ // A wrong cap must fail the call rather than silently fall back to the default.+ if !(value.is_finite() && value >= 1.0 && value.fract() == 0.0 && value <= usize::MAX as f64) {+ return cx.throw_range_error(format!(+ "maxImageBytes must be a positive integer, got {value}"+ ));+ }+ Ok(Some(value as usize))+}+fn time_bucket_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<u64> {let bucket = cx.argument::<JsNumber>(index)?.value(cx);if !(bucket.is_finite() && bucket >= 0.0 && bucket.fract() == 0.0) {@@ -232,14 +247,18 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {Some(cache) => Some((cache, time_bucket_arg(&mut cx, 8)?)),None => None,};+ let max_image_bytes = opt_max_image_bytes_arg(&mut cx, 9)?;if team_id.is_none() && content_key.is_some() {return cx.throw_error("contentKey requires teamId");}let image_collection = match (team_id.clone(), content_key) {- (Some(team_id), Some(content_key)) => Some(ImageCollection {- team_id,- content_key,- }),+ (Some(team_id), Some(content_key)) => {+ let mut collection = ImageCollection::new(team_id, content_key);+ if let Some(max_image_bytes) = max_image_bytes {+ collection.max_image_bytes = max_image_bytes;+ }+ Some(collection)+ }_ => None,};let produced_ref_filter = ProducedRefFilter {diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 8d69b3b21090..ff2f8e3b7e9c 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.7.3"+version = "0.8.0"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex 5771998dbf5e..5fc43af60617 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -140,10 +140,11 @@ pub fn has_media_src_attr(attrs: &Object<'_>) -> bool {MEDIA_SRC_ATTRS.iter().any(|name| attrs.contains_key(*name))}-pub(crate) fn has_usable_srcset(value: &str, keep_image_refs: bool) -> bool {- (keep_image_refs && is_image_ref_strict(value))+pub(crate) fn has_usable_srcset(value: &str, ctx: &Ctx<'_>) -> bool {+ (ctx.keeps_image_refs() && is_image_ref_strict(value))|| candidate_for_scrubbing(value).is_some_and(|url| {- collectable_data_uri_bytes(url).is_some() || canonicalize(url).is_some()+ collectable_data_uri_bytes(url, ctx.max_collected_image_bytes()).is_some()+ || canonicalize(url).is_some()})}@@ -180,7 +181,7 @@ pub fn apply_blur(&& attrs.get("srcset").and_then(as_str)- .is_some_and(|value| has_usable_srcset(value, ctx.keeps_image_refs()));+ .is_some_and(|value| has_usable_srcset(value, ctx));// Computed only when a remote image is about to be collected, because the inline style is// parsed for it and most elements never reach that branch.let mut hidden_pixel: Option<bool> = None;diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex 575d82ad895f..4e8148d852a5 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -949,7 +949,7 @@ impl<'c, 'a> Walker<'c, 'a> {match self.find_member(start, b"srcset").ok()? {Some(span) if scan::is_string(self.bytes, span) => {let value = scan::unescape(self.bytes, span).ok()?;- has_usable_srcset(&value, self.ctx.keeps_image_refs())+ has_usable_srcset(&value, self.ctx)}_ => false,}diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rsindex 4668cd0cbf58..705827ec0493 100644--- a/rust/replay-anonymizer/src/canvas.rs+++ b/rust/replay-anonymizer/src/canvas.rs@@ -440,10 +440,7 @@ mod tests {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());let ctx = Ctx::with_image_collection(&allow,- Some(ImageCollection {- team_id: "0".repeat(32),- content_key: "k".repeat(32),- }),+ Some(ImageCollection::new("0".repeat(32), "k".repeat(32))),);let b64 = png_base64(8, 8, [10, 200, 10, 255]);let scrub_with = |mime: &str| -> serde_json::Value {diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex b4f7b70aa552..56cde33584b5 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -118,8 +118,7 @@ fn is_ref_hash(hash: &str) -> bool {.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')}-/// Per-image cap: a collected image must fit in one Kafka message on the scrub topic with headroom-/// under the broker's 1 MB default. Bigger images stay on the inline blur path.+/// Default per-image cap. Bigger images stay on the inline blur path.pub const MAX_IMAGE_BYTES: usize = 900 * 1024;/// Per-message caps bound what one payload can pin in memory and fan out onto the scrub topic;/// images past them stay on the inline blur path. The count cap is sized so the byte cap is the@@ -142,6 +141,17 @@ pub struct ImageCollection {/// Per-team key for the content HMAC, derived by the caller. Its ASCII/// bytes key [`hash_image_bytes`].pub content_key: String,+ pub max_image_bytes: usize,+}++impl ImageCollection {+ pub fn new(team_id: String, content_key: String) -> Self {+ Self {+ team_id,+ content_key,+ max_image_bytes: MAX_IMAGE_BYTES,+ }+ }}pub struct CollectedImage {@@ -154,6 +164,7 @@ pub struct CollectedImage {pub struct ImageCollector {team_id: String,content_key: String,+ max_image_bytes: usize,images: Vec<CollectedImage>,seen: HashSet<String>,total_bytes: usize,@@ -164,16 +175,21 @@ impl ImageCollector {Self {team_id: collection.team_id,content_key: collection.content_key,+ max_image_bytes: collection.max_image_bytes,images: Vec::new(),seen: HashSet::new(),total_bytes: 0,}}+ pub fn max_image_bytes(&self) -> usize {+ self.max_image_bytes+ }+/// Collect decoded image bytes and return their ref, or `None` when a cap says this image must/// stay on the inline blur path.pub fn collect(&mut self, bytes: Vec<u8>) -> Option<String> {- if bytes.len() > MAX_IMAGE_BYTES {+ if bytes.len() > self.max_image_bytes {return None;}let hash = hash_image_bytes(self.content_key.as_bytes(), &bytes);@@ -228,7 +244,7 @@ pub fn normalize_collected_mime(mime: &str) -> &'static str {/// a base64 raster image: SVG is a text format whose PII must stay on the inline scrub path, and/// non-base64 payloads mirror `blur_image_data_uri`'s refusal. MIME types are case-insensitive,/// so the checks run on a lowercased meta — `image/SVG+xml` must not dodge the SVG exclusion.-pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {+pub fn collectable_data_uri_bytes(uri: &str, max_image_bytes: usize) -> Option<Vec<u8>> {let rest = uri.strip_prefix("data:")?;let (meta, payload) = rest.split_once(',')?;let meta = meta.to_ascii_lowercase();@@ -244,7 +260,7 @@ pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {// An encoded payload that can't decode under the per-image cap would be decoded here only to// be rejected by `collect` (and then decoded again by the blur fallback) — bail on the// encoded length instead.- if payload.len() > MAX_IMAGE_BYTES.div_ceil(3) * 4 {+ if payload.len() > max_image_bytes.div_ceil(3) * 4 {return None;}let bytes = base64::engine::general_purpose::STANDARD@@ -260,13 +276,17 @@ pub fn collectable_data_uri_bytes(uri: &str) -> Option<Vec<u8>> {mod tests {use super::*;+ fn collectable(uri: &str) -> Option<Vec<u8>> {+ collectable_data_uri_bytes(uri, MAX_IMAGE_BYTES)+ }+const TEST_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";fn collector() -> ImageCollector {- ImageCollector::new(ImageCollection {- team_id: "a".repeat(32),- content_key: String::from_utf8(TEST_KEY.to_vec()).unwrap(),- })+ ImageCollector::new(ImageCollection::new(+ "a".repeat(32),+ String::from_utf8(TEST_KEY.to_vec()).unwrap(),+ ))}#[test]@@ -345,17 +365,17 @@ mod tests {#[test]fn collectable_rejects_svg_non_base64_and_non_image() {- assert!(collectable_data_uri_bytes("data:image/svg+xml;base64,PHN2Zz4=").is_none());- assert!(collectable_data_uri_bytes("data:image/bmp;base64,Qk0=").is_none());- assert!(collectable_data_uri_bytes("data:image/x-bmp;base64,Qk0=").is_none());- assert!(collectable_data_uri_bytes("data:image/x-ms-bmp;base64,Qk0=").is_none());- assert!(collectable_data_uri_bytes("data:image/png;base64,Qk0=").is_none());- assert!(collectable_data_uri_bytes("data:image/svg+xml;utf8,<svg/>").is_none());- assert!(collectable_data_uri_bytes("data:text/plain;base64,aGk=").is_none());- assert!(collectable_data_uri_bytes("data:image/png;utf8,notbase64").is_none());- assert!(collectable_data_uri_bytes("data:image/png;base64,%%%").is_none());+ assert!(collectable("data:image/svg+xml;base64,PHN2Zz4=").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());+ assert!(collectable("data:image/png;base64,Qk0=").is_none());+ assert!(collectable("data:image/svg+xml;utf8,<svg/>").is_none());+ 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());assert_eq!(- collectable_data_uri_bytes("data:image/png;base64,aGVsbG8=").as_deref(),+ collectable("data:image/png;base64,aGVsbG8=").as_deref(),Some(b"hello".as_slice()));}@@ -365,7 +385,7 @@ mod tests {// 4/3 * MAX_IMAGE_BYTES encoded chars is the fit boundary; one full quartet past it means// the decoded bytes cannot fit, so it must bail before paying the decode.let over = "A".repeat(MAX_IMAGE_BYTES.div_ceil(3) * 4 + 4);- assert!(collectable_data_uri_bytes(&format!("data:image/png;base64,{over}")).is_none());+ assert!(collectable(&format!("data:image/png;base64,{over}")).is_none());}#[test]@@ -389,10 +409,10 @@ mod tests {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_uri_bytes("data:image/SVG+xml;base64,PHN2Zz4=").is_none());- assert!(collectable_data_uri_bytes("data:image/Svg+Xml;base64,PHN2Zz4=").is_none());+ assert!(collectable("data:image/SVG+xml;base64,PHN2Zz4=").is_none());+ assert!(collectable("data:image/Svg+Xml;base64,PHN2Zz4=").is_none());assert_eq!(- collectable_data_uri_bytes("data:image/PNG;BASE64,aGVsbG8=").as_deref(),+ 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 7bf0738677ea..db3197130d28 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -16,6 +16,7 @@ use crate::assets::PLACEHOLDER_SRC;use crate::blur::{blank_image_data_uri, blur_image_data_uri, pixelate_raw_rgba};use crate::collect::{collectable_data_uri_bytes, is_image_ref, CollectedImage, ImageCollection, ImageCollector,+ MAX_IMAGE_BYTES,};use crate::images::{ImageFallback, ImagePolicy, ImageQueue};use crate::timings::PhaseTimings;@@ -313,7 +314,7 @@ impl<'a> Ctx<'a> {if let Some(Some(hit)) = self.blur_cache.borrow().get(original) {return Some(hit.clone());}- let bytes = collectable_data_uri_bytes(original)?;+ let bytes = collectable_data_uri_bytes(original, collector.borrow().max_image_bytes())?;let collected = collector.borrow_mut().collect(bytes)?;self.blur_cache.borrow_mut()@@ -321,6 +322,14 @@ impl<'a> Ctx<'a> {Some(collected)}+ pub(crate) fn max_collected_image_bytes(&self) -> usize {+ self.collector+ .as_ref()+ .map_or(MAX_IMAGE_BYTES, |collector| {+ collector.borrow().max_image_bytes()+ })+ }+/// Pixelate raw RGBA pixels, memoized on dimensions + bytes.pub fn pixelate_raw(&self, rgba_base64: &str, width: u32, height: u32) -> Option<String> {let key = format!("raw:{width}x{height}:{rgba_base64}");diff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rsindex 55a4ef4adf0c..a91d5b4bf261 100644--- a/rust/replay-anonymizer/src/css.rs+++ b/rust/replay-anonymizer/src/css.rs@@ -731,10 +731,10 @@ mod tests {let allow = AllowLists::default();let ctx = Ctx::with_image_collection(&allow,- Some(ImageCollection {- team_id: "0123456789abcdef0123456789abcdef".to_string(),- content_key: "fedcba9876543210fedcba9876543210".to_string(),- }),+ Some(ImageCollection::new(+ "0123456789abcdef0123456789abcdef".to_string(),+ "fedcba9876543210fedcba9876543210".to_string(),+ )),);let original = png_data_uri(8, 8, [10, 20, 30, 255]);let css = format!("background-image:url('{original}')");@@ -758,10 +758,10 @@ mod tests {let allow = AllowLists::default();let ctx = Ctx::with_image_collection(&allow,- Some(ImageCollection {- team_id: "0123456789abcdef0123456789abcdef".to_string(),- content_key: "fedcba9876543210fedcba9876543210".to_string(),- }),+ Some(ImageCollection::new(+ "0123456789abcdef0123456789abcdef".to_string(),+ "fedcba9876543210fedcba9876543210".to_string(),+ )),).collecting_urls(Some(UrlCollection {reference_namespace: None,@@ -815,10 +815,10 @@ mod tests {let allow = AllowLists::default();let ctx = Ctx::with_image_collection(&allow,- Some(ImageCollection {- team_id: "0123456789abcdef0123456789abcdef".to_string(),- content_key: "fedcba9876543210fedcba9876543210".to_string(),- }),+ Some(ImageCollection::new(+ "0123456789abcdef0123456789abcdef".to_string(),+ "fedcba9876543210fedcba9876543210".to_string(),+ )),);let original = "data:image/svg+xml;base64,PHN2Zz48dGV4dD5qb2huLmZha2VuYW1lQGV4YW1wbGUuY29tPC90ZXh0Pjwvc3ZnPg==";let css = format!("background-image:url('{original}')");diff --git a/rust/replay-anonymizer/tests/image_token_fuzz.rs b/rust/replay-anonymizer/tests/image_token_fuzz.rsindex 913d1613c0a9..71f537ff6842 100644--- a/rust/replay-anonymizer/tests/image_token_fuzz.rs+++ b/rust/replay-anonymizer/tests/image_token_fuzz.rs@@ -77,11 +77,14 @@ fn leaked_tokens(lines: &[u8]) -> Vec<String> {found}+// The production cap is too large to cross cheaply 240 times, so the fuzz lowers it.+const FUZZ_MAX_IMAGE_BYTES: usize = 64 * 1024;+fn png_of(width: u32, height: u32, seed: u8) -> String {let mut img = image::RgbaImage::new(width, height);for (x, y, px) in img.enumerate_pixels_mut() {// Noise, so the encoder cannot collapse it — a large image has to stay large enough to- // exceed the collection lane's per-image cap.+ // exceed `FUZZ_MAX_IMAGE_BYTES`.let v = ((x * 7 + y * 13) as u8).wrapping_mul(seed | 1);*px = image::Rgba([v, v.wrapping_add(seed), v ^ seed, 255]);}@@ -108,7 +111,7 @@ fn image_uri(rng: &mut Rng, small: &[String], large: &[String]) -> String {match rng.below(5) {// Collectable when collection is on; deferred token otherwise.0 | 1 => small[rng.below(small.len() as u64) as usize].clone(),- // Over the collection lane's per-image cap, so deferred even with collection on.+ // Over `FUZZ_MAX_IMAGE_BYTES`, so deferred even with collection on.2 => large[rng.below(large.len() as u64) as usize].clone(),// A text format: never collectable, and unblurrable, so it exercises the fallback.3 => svg_uri(rng.below(4) as u8),@@ -177,8 +180,17 @@ fn make_event(rng: &mut Rng, small: &[String], large: &[String], ts: f64) -> Valfn fuzz_no_deferred_image_token_reaches_output() {let allow = AllowLists::default();let small: Vec<String> = (0..4).map(|i| png_of(8, 8, i as u8 + 1)).collect();- // Comfortably over the collection lane's 900 KB per-image cap.let large: Vec<String> = (0..2).map(|i| png_of(900, 900, i as u8 + 7)).collect();+ for (name, images, over) in [("small", &small, false), ("large", &large, true)] {+ for uri in images {+ let decoded = uri.split_once(',').map_or(0, |(_, b64)| b64.len() / 4 * 3);+ assert_eq!(+ decoded > FUZZ_MAX_IMAGE_BYTES,+ over,+ "{name} image vs the fuzz cap"+ );+ }+ }let mut rng = Rng(0xDEAD_BEEF_1234_5678);let mut failures: Vec<String> = Vec::new();@@ -209,8 +221,11 @@ fn fuzz_no_deferred_image_token_reaches_output() {image_policy: ImagePolicy::Parallel,},collect.then(|| ImageCollection {- team_id: "a".repeat(32),- content_key: "0123456789abcdef0123456789abcdef".to_string(),+ max_image_bytes: FUZZ_MAX_IMAGE_BYTES,+ ..ImageCollection::new(+ "a".repeat(32),+ "0123456789abcdef0123456789abcdef".to_string(),+ )}),);messages += 1;diff --git a/rust/replay-anonymizer/tests/image_token_leak.rs b/rust/replay-anonymizer/tests/image_token_leak.rsindex 27dabcaa1242..7d863421fb3e 100644--- a/rust/replay-anonymizer/tests/image_token_leak.rs+++ b/rust/replay-anonymizer/tests/image_token_leak.rs@@ -95,10 +95,10 @@ fn svg_data_uri() -> String {}fn collection() -> ImageCollection {- ImageCollection {- team_id: "a".repeat(32),- content_key: "0123456789abcdef0123456789abcdef".to_string(),- }+ ImageCollection::new(+ "a".repeat(32),+ "0123456789abcdef0123456789abcdef".to_string(),+ )}fn snapshot_message(items: serde_json::Value) -> serde_json::Value {diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex f34016869259..295566523205 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -887,10 +887,7 @@ fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {byte_walk,image_policy,},- Some(ImageCollection {- team_id: team_id.clone(),- content_key: content_key.clone(),- }),+ Some(ImageCollection::new(team_id.clone(), content_key.clone())),).expect("anonymizes (walk={byte_walk})");@@ -979,10 +976,10 @@ fn image_collection_svg_stays_on_the_inline_scrub_path() {&allow,&mut bytes,AnonymizeOpts::default(),- Some(ImageCollection {- team_id: "0123456789abcdef0123456789abcdef".to_string(),- content_key: "fedcba9876543210fedcba9876543210".to_string(),- }),+ Some(ImageCollection::new(+ "0123456789abcdef0123456789abcdef".to_string(),+ "fedcba9876543210fedcba9876543210".to_string(),+ )),).expect("anonymizes");let lines = String::from_utf8(out.lines.clone()).unwrap();diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex 48387fa4230e..7fab9aedfcc5 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -666,10 +666,10 @@ fn monthly_refs_survive_compressed_snapshot_fields() {image_policy: ImagePolicy::Inline,},None,- Some(ImageCollection {- team_id: namespace.to_string(),- content_key: URL_KEY.to_string(),- }),+ Some(ImageCollection::new(+ namespace.to_string(),+ URL_KEY.to_string(),+ )),Some(UrlCollection {url_key: URL_KEY.to_string(),reference_namespace: Some(namespace.to_string()),