: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)!: blank images the scrub lane cannot take (#116877)
Nicholas Waltz722518fa12bb
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.tsindex 3453bb52b65d..452e6ef7bc29 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.ts@@ -71,8 +71,6 @@ export function recordAnonymizeTimingSpans('anonymize.route': outcome.route ?? '','anonymize.cv_total_ms': timings.cvTotalNs / NS_PER_MS,'anonymize.cv_count': timings.cvCount,- 'anonymize.blur_total_ms': timings.blurTotalNs / NS_PER_MS,- 'anonymize.blur_count': timings.blurCount,})},})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.tsindex 85a29baec5c0..57fb99d06ef3 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@@ -1,6 +1,6 @@import sharp, { type FormatEnum, type Sharp } from 'sharp'-import { UndecodableImageError, blurOnly } from './blur.ts'+import { BLANK_PNG, UndecodableImageError, blurOnly } from './blur.ts'describe('blur', () => {const swatch = (): Sharp => sharp({ create: { width: 8, height: 8, channels: 3, background: '#0af' } })@@ -27,6 +27,11 @@ describe('blur', () => {// 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('stores a blank that decodes to one transparent pixel', async () => {+ const { data, info } = await sharp(BLANK_PNG).ensureAlpha().raw().toBuffer({ resolveWithObject: true })+ expect([info.width, info.height, data[3]]).toEqual([1, 1, 0])+ })+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 }diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.tsindex 92caa2b98716..a5f8068854c5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts@@ -13,7 +13,7 @@ const BLUR_SIGMA = 2.34const MAX_LONG_SIDE = 96// 1x1 transparent PNG: the output substituted for an image the NSFW/gore gate rejects (see advancedScrub).export const BLANK_PNG = Buffer.from(- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNgAAIAAAUAAen63NgAAAAASUVORK5CYII=','base64')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex 560697cb306a..a822a52ba290 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -52,7 +52,7 @@ export type MlMirrorConfig = {/*** Produce collected original images to the scrub topic. Enabling changes the mirrored JSONL- * shape: image fields carry `image:<teamId>:<hash>` refs instead of blurred data URIs, so+ * shape: image fields carry `image:<teamId>:<hash>` refs instead of blank images, so* both the scrub consumer lane AND ref-aware downstream readers must be live first.*/SESSION_RECORDING_ML_IMAGE_SCRUB_PRODUCER_ENABLED: booleandiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex 9d2b144be64f..b0d81aa841bd 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -130,7 +130,7 @@ export class MlMirrorMetrics {private static readonly mlImageTeamIdInvalid = new Counter({name: 'recording_blob_ingestion_v2_ml_image_team_id_invalid',- help: 'Messages whose team ID failed the consumer ref-shape check; collection disabled for them (inline blur instead)',+ help: 'Messages whose team ID failed the consumer ref-shape check; collection disabled for them, so their images are blanked',})private static readonly mlUrlBytes = new Histogram({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.tsindex 31641d2cb9a3..20179adc0aa4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts@@ -57,7 +57,7 @@ export function createProduceCollectedImagesStep<: undefined// The ack handlers must capture only the refs: `image.bytes` are subarray views into the- // whole packed FFI buffer (up to 32 MB per source message), and queueMessages copies the+ // whole packed FFI buffer (up to 64 MiB per source message), and queueMessages copies the// slices synchronously — a closure holding `fresh` would pin the full packed buffer per// in-flight produce, unbounded by the producer queue's byte accounting.const refs = fresh.map((image) => image.ref)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 4cf3f7c52371..2d9e76d1ffce 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@@ -450,7 +450,7 @@ describeAddon('native image collection', () => {16),],- ])('collects nothing %s and blurs inline instead', async (_case, anonymize) => {+ ])('collects nothing %s and blanks the image instead', async (_case, anonymize) => {rustAddon!.initAnonymizer({ text: [], url: [] })const result = await anonymize()expect(result.failed).toBe(false)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.tsindex b2acbd3ba12c..7b568c2911b5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts@@ -66,7 +66,7 @@ export function getDefaultKafkaSessionreplayProducerEnvConfig(): KafkaSessionrep/*** ML_IMAGE_SCRUB producer — same replay cluster, but a dedicated client instance so the- * image-scrub lane's heavy, best-effort payloads (original image bytes, up to 32 MB per source+ * image-scrub lane's heavy, best-effort payloads (original image bytes, up to 64 MiB per source* message) buffer in their own librdkafka queue. A scrub-topic slowdown then fails fast inside* this producer (failed produces are swallowed by design — a dangling ref reads as a placeholder)* instead of filling the shared SESSIONREPLAY queue and starving DLQ/overflow/metadata produces.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 4065bd4577cf..2b5493ec173b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2822,12 +2822,6 @@ dependencies = ["uuid",]-[[package]]-name = "color_quant"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"-[[package]]name = "colorchoice"version = "1.0.4"@@ -5296,16 +5290,6 @@ dependencies = ["wasm-bindgen",]-[[package]]-name = "gif"-version = "0.14.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"-dependencies = [- "color_quant",- "weezl",-]-[[package]]name = "gimli"version = "0.32.3"@@ -6237,24 +6221,9 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"dependencies = ["bytemuck","byteorder-lite",- "color_quant",- "gif",- "image-webp","moxcms","num-traits","png",- "zune-core",- "zune-jpeg",-]--[[package]]-name = "image-webp"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"-dependencies = [- "byteorder-lite",- "quick-error 2.0.1",][[package]]@@ -6708,12 +6677,6 @@ version = "2.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72167d68f5fce3b8655487b8038691a3c9984ee769590f93f2a631f4ad64e4f5"-[[package]]-name = "jpeg-decoder"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"-[[package]]name = "js-source-scopes"version = "0.7.1"@@ -9553,7 +9516,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.9.1"+version = "0.10.0"dependencies = ["ahash 0.8.12","anyhow",@@ -9561,7 +9524,6 @@ dependencies = ["flate2","hmac 0.12.1","image",- "jpeg-decoder","libdeflater","lz4","memchr",@@ -10311,12 +10273,6 @@ version = "1.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"-[[package]]-name = "quick-error"-version = "2.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"-[[package]]name = "quick-xml"version = "0.26.0"@@ -11353,7 +11309,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"dependencies = ["fnv",- "quick-error 1.2.3",+ "quick-error","tempfile","wait-timeout",]@@ -14574,12 +14530,6 @@ dependencies = ["rustls-pki-types",]-[[package]]-name = "weezl"-version = "0.1.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"-[[package]]name = "which"version = "4.4.2"@@ -15257,21 +15207,6 @@ dependencies = ["pkg-config",]-[[package]]-name = "zune-core"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"--[[package]]-name = "zune-jpeg"-version = "0.5.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"-dependencies = [- "zune-core",-]-[[patch.unused]]name = "js-source-scopes"version = "0.6.0"diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 4d414771340c..c8235e68c495 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -94,12 +94,9 @@ export interface AnonymizeTimings {/** Accumulated cv de/recompression time across all events in the message. */cvTotalNs: numbercvCount: number- /** Accumulated image blur/pixelate time (cache misses only). */- blurTotalNs: number- blurCount: number/*** The op in flight when processing stopped: `done` on success, else the phase or op- * (`queued` | `decompress` | `scrub` | `cv` | `blur` | `serialize_meta`) that was running.+ * (`queued` | `decompress` | `scrub` | `cv` | `serialize_meta`) that was running.*/lastOp: string}@@ -198,9 +195,9 @@ export function initAnonymizer(allow: AllowListsInput): void {** Non-empty `teamId` + `contentKey` enable image collection using the raw team ID and per-team* content HMAC key. The master secret stays with the caller. Inlined images are replaced- * with `image:<teamId>:<hash>` refs (hash = keyed HMAC of the bytes) instead of the inline- * blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to- * the scrub topic.+ * with `image:<teamId>:<hash>` refs (hash = keyed HMAC of the bytes), and the original bytes come+ * back in `images`/`meta.images` for the caller to produce to the scrub topic. Without them every+ * inlined image is blanked.** `urlKey` enables the URL-collection lane independently. It is the global URL HMAC key. A remote* image's `src` keeps the media placeholder, a namespaced sibling attribute carries its ref, and@@ -212,7 +209,7 @@ export function initAnonymizer(allow: AllowListsInput): void {** `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.+ * `maxImageBytes` caps the decoded size of a collected image; a bigger one is blanked.* Omitted, the crate default applies.*/export async function anonymizeKafkaPayload(diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 217273191aee..16ce3b3131e8 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -27,7 +27,7 @@ use posthog_replay_anonymizer::collect::{image_ref, url_ref};use posthog_replay_anonymizer::snapshot::{AnonymizedMessage, ImageEntry};use posthog_replay_anonymizer::{is_public_host, politeness_key, snapshot, try_canonicalize, AllowLists, FailKind,- ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,+ ImageCollection, PhaseTimings, UrlCollection,};use serde::Deserialize;@@ -39,28 +39,6 @@ compile_error!("replay-anonymizer-node requires panic=unwind: catch_unwind is the fail-closed guard");-/// Deferred-parallel image scrubbing is the production default; `REPLAY_ANONYMIZER_PARALLEL_IMAGES=0`-/// (or `false`) is the rollback lever to the inline path. Worker count comes from-/// `REPLAY_ANONYMIZER_IMAGE_THREADS` (see the core crate's `images` module).-static IMAGE_POLICY: std::sync::OnceLock<ImagePolicy> = std::sync::OnceLock::new();--fn image_policy() -> ImagePolicy {- *IMAGE_POLICY.get_or_init(|| {- // Forgiving parse: this is an incident rollback lever, so common falsy spellings count.- let disabled = std::env::var("REPLAY_ANONYMIZER_PARALLEL_IMAGES").is_ok_and(|v| {- matches!(- v.trim().to_ascii_lowercase().as_str(),- "0" | "false" | "off" | "no"- )- });- if disabled {- ImagePolicy::Inline- } else {- ImagePolicy::Parallel- }- })-}-// The allow lists are immutable per process; set once at startup via `initAnonymizer`.static ALLOW: RwLock<Option<AllowLists>> = RwLock::new(None);@@ -302,10 +280,7 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {let scrubbed = snapshot::anonymize_kafka_payload_collecting(allow,&mut payload,- snapshot::AnonymizeOpts {- image_policy: image_policy(),- ..Default::default()- },+ snapshot::AnonymizeOpts::default(),Some(&timings),image_collection,url_collection,diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 45b9b1070c51..aa6da2873d77 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,8 +1,8 @@[package]name = "posthog-replay-anonymizer"-version = "0.9.1"+version = "0.10.0"edition = "2021"-description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"+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"homepage = "https://posthog.com"repository = "https://github.com/PostHog/posthog"@@ -24,8 +24,6 @@ hmac = { workspace = true }libdeflater = { workspace = true }lz4 = { workspace = true }memchr = "2"-image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp"] }-jpeg-decoder = { version = "0.3", default-features = false }serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }@@ -36,6 +34,7 @@ url = { workspace = true }zstd = { workspace = true }[dev-dependencies]+image = { version = "0.25", default-features = false, features = ["png"] }# flate2: tests verify reference gzip streams with an independent codec (not libdeflate), so a# codec regression can't hide by round-tripping through itself.flate2 = { workspace = true }diff --git a/rust/replay-anonymizer/README.md b/rust/replay-anonymizer/README.mdindex 4f9173e3a9d6..5793ad1201f8 100644--- a/rust/replay-anonymizer/README.md+++ b/rust/replay-anonymizer/README.md@@ -1,6 +1,6 @@# posthog-replay-anonymizer-PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/`cv` neutralization. This is the scrub core behind PostHog's ml-mirror pipelines.+PII scrubber for rrweb session-replay events: text/URL redaction, image collection for an out-of-band scrub, and canvas/`cv` neutralization. An image the scrub lane cannot take is blanked; nothing is blurred in this crate. This is the scrub core behind PostHog's ml-mirror pipelines.Consumers:diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex 5fc43af60617..12113bc8f392 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -1,15 +1,13 @@-//! Media detection + placeholder/blur dispatch.-//! Blur runs inline (native), so there is no deferred-job/blank-first dance — the attribute lands on-//! its final blurred (or placeholder) value directly.+//! Media detection, and dispatch of media sources to the image scrub or the placeholder.use std::borrow::Cow;use simd_json::borrowed::{Object, Value};-use crate::blur::is_image_data_uri;use crate::collect::{collectable_data_uri_bytes, is_image_ref_strict};use crate::context::{Ctx, ImageSource};-use crate::images::ImageFallback;+use crate::data_uri::is_image_data_uri;+use crate::data_uri::ImageFallback;use crate::json::{as_f64, as_str, string_value};use crate::srcset::candidate_for_scrubbing;use crate::url::scrub_url;@@ -143,34 +141,34 @@ pub fn has_media_src_attr(attrs: &Object<'_>) -> bool {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, ctx.max_collected_image_bytes()).is_some()+ collectable_data_uri_bytes(url, ctx.max_collected_image_bytes()).is_ok()|| canonicalize(url).is_some()})}-/// Blur an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`).+/// Scrub an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`)./// Returns whether it acted.-pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str) -> bool {+pub fn scrub_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str) -> bool {let Some(value) = attrs.get(name).and_then(as_str).map(str::to_string) else {return false;};if !is_image_data_uri(&value) {return false;}- let blurred = ctx.scrub_image_from(+ let scrubbed = ctx.scrub_image_from(&value,ImageFallback::Blank,ImageSource::HtmlAttribute(INLINE_IMAGE_ATTR),);- attrs.insert(Cow::Owned(name.to_string()), string_value(blurred));+ attrs.insert(Cow::Owned(name.to_string()), string_value(scrubbed));true}-/// Replace a media element's source attrs with the blurred image (data URIs) or placeholder (remote+/// Replace a media element's source attrs with the scrubbed image (data URIs) or placeholder (remote/// URLs). A collected remote URL's ref and scrubbed original are stashed under separate namespaced/// attrs. Returns whether it changed any attribute — a media tag with no source attrs (e.g. a bare/// `<img>`) is left untouched.-pub fn apply_blur(+pub fn scrub_media_sources(ctx: &Ctx<'_>,attrs: &mut Object<'_>,tag: &str,@@ -220,12 +218,12 @@ pub fn apply_blur(continue;};if is_image_data_uri(&selected) {- let blurred = ctx.scrub_image_from(+ let scrubbed = ctx.scrub_image_from(&selected,ImageFallback::Placeholder,ImageSource::HtmlAttribute(key),);- attrs.insert(Cow::Borrowed(*key), string_value(blurred));+ attrs.insert(Cow::Borrowed(*key), string_value(scrubbed));} else {let collected =if !ctx.collects_urls() || !is_fetchable_image_attr(key, tag, parent_is_picture) {diff --git a/rust/replay-anonymizer/src/blur.rs b/rust/replay-anonymizer/src/blur.rsdeleted file mode 100644index 085c2add466f..000000000000--- a/rust/replay-anonymizer/src/blur.rs+++ /dev/null@@ -1,219 +0,0 @@-//! Downsample + blur media/canvas images — scene stays legible, faces/text don't.-//! Runs inline (synchronously). Output is never byte-identical to `sharp` (which the image-scrub-//! sidecar still uses, with matching params), so tests assert structure (decodes to W x H PNG), not bytes.--use base64::Engine;-use image::{DynamicImage, GenericImageView};--const DOWNSAMPLE_RATIO: f32 = 0.12;-const BLUR_SIGMA: f32 = 2.34;-const MAX_LONG_SIDE: f32 = 96.0;--// Bounds on decoding fully untrusted image bytes: a tiny compressed image can declare huge dimensions-// (a decompression bomb). Reject those to the blank/placeholder fallback rather than allocating GBs.-const MAX_IMAGE_SIDE: u32 = 16_384;-const MAX_IMAGE_ALLOC_BYTES: u64 = 256 * 1024 * 1024;--const JPEG_MAGIC: &[u8] = &[0xFF, 0xD8, 0xFF];--/// Decode a JPEG at a reduced DCT scale — the blur target is <= MAX_LONG_SIDE px, so the decoder-/// can skip most IDCT work (it picks the smallest of 1/8..1 still at or above the request).-/// Returns the decoded image plus the ORIGINAL dimensions, so the caller sizes the thumbnail off-/// the true aspect, not the scaled decode. `None` falls back to the full-resolution path-/// (non-JPEG bytes, oversize dimensions, or a pixel format the fast path doesn't map).-fn decode_scaled_jpeg(bytes: &[u8]) -> Option<(DynamicImage, (u32, u32))> {- if !bytes.starts_with(JPEG_MAGIC) {- return None;- }- let mut decoder = jpeg_decoder::Decoder::new(std::io::Cursor::new(bytes));- decoder.read_info().ok()?;- let info = decoder.info()?;- // Baseline only: progressive (and lossless) frames buffer FULL-resolution coefficient planes- // inside decode() regardless of the requested scale, and jpeg-decoder has no allocation-limit- // API — a tiny crafted progressive header declaring 16k x 16k would force gigabytes. The- // fallback path enforces MAX_IMAGE_ALLOC_BYTES via image::Limits and rejects such files.- if info.coding_process != jpeg_decoder::CodingProcess::DctSequential {- return None;- }- let (w, h) = (u32::from(info.width), u32::from(info.height));- if w == 0 || h == 0 || w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE {- return None;- }- // Belt for the sequential path's own buffers: stay well under the fallback's allocation cap.- if u64::from(w) * u64::from(h) * 4 > MAX_IMAGE_ALLOC_BYTES {- return None;- }- decoder- .scale(MAX_LONG_SIDE as u16, MAX_LONG_SIDE as u16)- .ok()?;- let pixels = decoder.decode().ok()?;- let scaled = decoder.info()?;- let (sw, sh) = (u32::from(scaled.width), u32::from(scaled.height));- let img = match scaled.pixel_format {- jpeg_decoder::PixelFormat::RGB24 => {- image::RgbImage::from_raw(sw, sh, pixels).map(DynamicImage::ImageRgb8)- }- jpeg_decoder::PixelFormat::L8 => {- image::GrayImage::from_raw(sw, sh, pixels).map(DynamicImage::ImageLuma8)- }- // CMYK32 / L16 are rare; the generic decoder handles them at full resolution.- _ => None,- }?;- Some((img, (w, h)))-}--fn decode_limited(bytes: &[u8]) -> Option<DynamicImage> {- let mut limits = image::Limits::default();- limits.max_image_width = Some(MAX_IMAGE_SIDE);- limits.max_image_height = Some(MAX_IMAGE_SIDE);- limits.max_alloc = Some(MAX_IMAGE_ALLOC_BYTES);- let reader = image::ImageReader::new(std::io::Cursor::new(bytes))- .with_guessed_format()- .ok()?;- let mut reader = reader;- reader.limits(limits);- reader.decode().ok()-}--/// A 1x1 transparent PNG: the fail-safe stand-in used when the real blur can't be produced.-pub const BLANK_PNG_BASE64: &str =- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";--pub fn blank_image_data_uri() -> String {- format!("data:image/png;base64,{BLANK_PNG_BASE64}")-}--pub fn is_image_data_uri(s: &str) -> bool {- s.starts_with("data:image/")-}--/// Scale to DOWNSAMPLE_RATIO, but never leave the long side above MAX_LONG_SIDE; floored at 1px.-fn target_dims(width: u32, height: u32) -> (u32, u32) {- let w = width.max(1) as f32;- let h = height.max(1) as f32;- let scale = DOWNSAMPLE_RATIO.min(MAX_LONG_SIDE / w.max(h));- (- ((w * scale).round() as u32).max(1),- ((h * scale).round() as u32).max(1),- )-}--fn encode_png_base64(img: &DynamicImage) -> Option<String> {- let mut buf = Vec::new();- img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)- .ok()?;- Some(base64::engine::general_purpose::STANDARD.encode(&buf))-}--/// Downsample a base64 image data URI to a fraction of its size + a blur, as a PNG; None if it can't.-/// On any failure we return None and the caller blanks the image. This intentionally omits the TS-/// fallback ladder (plain downsample-without-blur before giving up): failing toward a blank pixel is-/// strictly safer than emitting an unblurred thumbnail on this unencrypted-bucket path.-pub fn blur_image_data_uri(s: &str) -> Option<String> {- let rest = s.strip_prefix("data:")?;- let (meta, payload) = rest.split_once(',')?;- if !meta.contains("base64") || !meta.starts_with("image/") {- return None;- }- let bytes = base64::engine::general_purpose::STANDARD- .decode(payload.as_bytes())- .ok()?;- let (img, (w, h)) = match decode_scaled_jpeg(&bytes) {- Some(scaled) => scaled,- None => {- let img = decode_limited(&bytes)?; // can't read the header / exceeds limits -> None- let dims = img.dimensions();- (img, dims)- }- };- let (tw, th) = target_dims(w, h);- // Downsample (fit: fill) then Gaussian blur, mirroring the TS pipeline order.- let out = img- .resize_exact(tw, th, image::imageops::FilterType::Triangle)- .blur(BLUR_SIGMA);- let encoded = encode_png_base64(&out)?;- Some(format!("data:image/png;base64,{encoded}"))-}--/// Split a `data:<mime>;...,<base64>` URI into (mime, base64). None if not a data URI.-pub fn split_data_uri(uri: &str) -> Option<(String, String)> {- let rest = uri.strip_prefix("data:")?;- let comma = rest.find(',')?;- let mime = rest[..comma].split(';').next().unwrap_or("image/png");- let mime = if mime.is_empty() { "image/png" } else { mime };- Some((mime.to_string(), rest[comma + 1..].to_string()))-}--#[cfg(test)]-mod tests {- use super::*;- use image::GenericImageView;-- fn png_data_uri(w: u32, h: u32) -> String {- let img = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(- w,- h,- image::Rgba([120, 30, 200, 255]),- ));- let mut buf = Vec::new();- img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)- .unwrap();- format!(- "data:image/png;base64,{}",- base64::engine::general_purpose::STANDARD.encode(&buf)- )- }-- #[test]- fn blur_downsamples_to_target_dims_as_png() {- let uri = png_data_uri(100, 50);- let out = blur_image_data_uri(&uri).expect("blur should succeed for a valid png");- assert!(out.starts_with("data:image/png;base64,"));- let (_, b64) = split_data_uri(&out).unwrap();- let bytes = base64::engine::general_purpose::STANDARD- .decode(&b64)- .unwrap();- let decoded = image::load_from_memory(&bytes).unwrap();- // target_dims(100, 50) with ratio 0.12 -> (12, 6).- assert_eq!(decoded.dimensions(), (12, 6));- }-- #[test]- fn scaled_jpeg_decode_sizes_the_thumbnail_off_the_original_dims() {- // 1024x512 decodes at a reduced DCT scale; the thumbnail must still come out at- // target_dims(1024, 512) = (96, 48), not 0.12x of the scaled decode.- for gray in [false, true] {- let rgb = image::RgbImage::from_fn(1024, 512, |x, y| {- image::Rgb([(x % 251) as u8, (y % 241) as u8, 90])- });- let img = if gray {- image::DynamicImage::ImageLuma8(image::DynamicImage::ImageRgb8(rgb).to_luma8())- } else {- image::DynamicImage::ImageRgb8(rgb)- };- let mut buf = Vec::new();- img.write_to(- &mut std::io::Cursor::new(&mut buf),- image::ImageFormat::Jpeg,- )- .unwrap();- let uri = format!(- "data:image/jpeg;base64,{}",- base64::engine::general_purpose::STANDARD.encode(&buf)- );- let out = blur_image_data_uri(&uri).expect("blur should succeed for a valid jpeg");- let (_, b64) = split_data_uri(&out).unwrap();- let bytes = base64::engine::general_purpose::STANDARD- .decode(&b64)- .unwrap();- let decoded = image::load_from_memory(&bytes).unwrap();- assert_eq!(decoded.dimensions(), (96, 48), "gray={gray}");- }- }-- #[test]- fn blur_rejects_non_image_data_uri() {- assert!(blur_image_data_uri("data:text/plain;base64,aGVsbG8=").is_none());- assert!(blur_image_data_uri("not a data uri").is_none());- }-}diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex 8f9a4fce47b9..596a35986666 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -18,16 +18,16 @@ use crate::assets::{is_media_src_attr, px_length, IMAGE_REF_ATTR_PREFIX, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS,PLACEHOLDER_SRC,};-use crate::blur::is_image_data_uri;use crate::collect::is_image_ref_strict;use crate::context::{CountCheckpoint, Ctx, ImageSource};use crate::css;+use crate::data_uri::is_image_data_uri;+use crate::data_uri::ImageFallback;use crate::dom::{classify_tag, data_attr_looks_sensitive, is_data_attr, is_url_attr, is_user_text_attr,ParentKind, TagKind,};use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL};-use crate::images::ImageFallback;use crate::scan::{self, Span};use crate::srcset::candidate_for_scrubbing;use crate::text::{redact_emails, scrub_text};@@ -237,9 +237,7 @@ fn scrub_cv_snapshot_value(return Some(false);}let content = if changed { &walked } else { &decompressed };- // Through `cv::compress_scrubbed`, never the raw codec: the walk may have substituted deferred- // image tokens into `walked`, and compression is the last moment they can still be resolved.- let zs = crate::cv::compress_scrubbed(ctx, content).ok()?;+ let zs = crate::cv::compress_scrubbed(content).ok()?;write_latin1_json_string(&zs, out);Some(true)}@@ -755,7 +753,7 @@ impl<'c, 'a> Walker<'c, 'a> {out.splice(seg.0..seg.1, tmp.iter().copied());}}- // Attributes with the real tag kind (media blur vs plain scrubs).+ // Attributes with the real tag kind (media sources vs plain scrubs).if let Some((key, v)) = attrs_m {if self.find_member(v.0, b"style").ok()?.is_some()|| self@@ -943,7 +941,7 @@ impl<'c, 'a> Walker<'c, 'a> {Ok(scan::parse_number(self.bytes, span))}- /// An element's `attributes` object (mirrors `dom::scrub_attrs`, including the media blur).+ /// An element's `attributes` object (mirrors `dom::scrub_attrs`, including media sources)./// Namespaced attrs are appended before the closing brace; the tree path inserts them into the/// map instead, which is the same object semantically.fn walk_attrs(@@ -990,7 +988,7 @@ impl<'c, 'a> Walker<'c, 'a> {w.changed = true;return Some(end);}- return w.blur_media_src(+ return w.scrub_media_src(name,vstart,tag,@@ -1050,13 +1048,13 @@ impl<'c, 'a> Walker<'c, 'a> {Some(end)}- /// One media source attribute (mirrors `assets::apply_blur` for a single key): data images are- /// blurred; a remote URL becomes the placeholder. Its fetch-lane ref, when collected, and its+ /// One media source attribute (mirrors `assets::scrub_media_sources` for a single key): data images go to+ /// the image scrub; a remote URL becomes the placeholder. Its fetch-lane ref, when collected, and its/// host-scrubbed original are stashed alongside./// `hidden_pixel` is true for an `img` nobody can see. The collector counts that refusal once/// per URL, so `src` and `srcset` naming one URL, and a re-walk after a fallback, count once.#[allow(clippy::too_many_arguments)]- fn blur_media_src(+ fn scrub_media_src(&mut self,name: &str,vstart: usize,@@ -1068,12 +1066,12 @@ impl<'c, 'a> Walker<'c, 'a> {) -> Option<usize> {let bytes = self.bytes;if bytes.get(vstart) != Some(&b'"') {- // Non-string media source: apply_blur skips it.+ // Non-string media source: scrub_media_sources skips it.return self.copy_value(vstart, out);}let end = scan::skip_string(bytes, vstart).ok()?;let existing = scan::unescape(bytes, (vstart, end)).ok()?;- // See `assets::apply_blur`: only on an explicitly trusted re-scrub, and only for a+ // See `assets::scrub_media_sources`: only on an explicitly trusted re-scrub, and only for a// fully well-formed ref.if self.ctx.keeps_image_refs() && is_image_ref_strict(&existing) {return self.copy_value(vstart, out);@@ -1090,12 +1088,12 @@ impl<'c, 'a> Walker<'c, 'a> {};let property = MEDIA_SRC_ATTRS.iter().copied().find(|attr| *attr == name)?;if is_image_data_uri(&selected) {- let blurred = self.ctx.scrub_image_from(+ let scrubbed = self.ctx.scrub_image_from(&selected,ImageFallback::Placeholder,ImageSource::HtmlAttribute(property),);- scan::write_json_string(&blurred, out);+ scan::write_json_string(&scrubbed, out);} else {let collected = if !is_fetchable_image_attr(name, tag, parent_is_picture) {None@@ -1208,7 +1206,7 @@ impl<'c, 'a> Walker<'c, 'a> {}let content = if changed { &walked } else { &decompressed };// See `scrub_cv_snapshot_value`: the barrier, not the raw codec.- let zs = crate::cv::compress_scrubbed(self.ctx, content).ok()?;+ let zs = crate::cv::compress_scrubbed(content).ok()?;write_latin1_json_string(&zs, out);self.changed = true;Some(send)diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rsindex fa28bd073668..bac089e69319 100644--- a/rust/replay-anonymizer/src/canvas.rs+++ b/rust/replay-anonymizer/src/canvas.rs@@ -7,10 +7,10 @@use simd_json::borrowed::{Object, Value};-use crate::blur::{split_data_uri, BLANK_PNG_BASE64};use crate::collect::{is_image_ref, is_image_ref_strict, normalize_collected_mime};use crate::context::Ctx;-use crate::images::ImageFallback;+use crate::data_uri::ImageFallback;+use crate::data_uri::{split_data_uri, BLANK_PNG_BASE64};use crate::json::{as_array, as_array_mut, as_f64, as_object, as_object_mut, as_str, as_u32, key, string_value,};@@ -218,7 +218,7 @@ fn scrub_frame_blob(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {// A content ref left by an earlier pass. Reassembling it into `data:{mime};base64,image:...`// yields a URI that cannot decode, which `scrub_image` fails safe to a blank pixel — destroying// the join key and stranding the image. Left alone only on an explicitly trusted re-scrub, and- // only when fully well-formed: see `assets::apply_blur`.+ // only when fully well-formed: see `assets::scrub_media_sources`.if ctx.keeps_image_refs() && is_image_ref_strict(&base64) {return false;}diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex 29dc2f2f1391..1817843dfbc1 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -1,12 +1,12 @@//! Collect original image bytes for the out-of-band scrub lane.//!//! With collection enabled (an [`ImageCollection`] on the anonymize call), each inlined image is-//! replaced by a stable content reference, `image:<teamId>:<hash>`, instead of the native-//! blur, and the original bytes ride back to the caller on the message. The caller produces them-//! to the `session_replay_image_scrub` Kafka topic keyed by the ref; the scrub consumer trusts the-//! ref (this producer is the only writer), blurs the bytes out of process, and writes them to the-//! ML bucket indexed by `(team_id, hash)`, so the ref embedded in the mirrored lines is the-//! join key.+//! replaced by a stable content reference, `image:<teamId>:<hash>`, and the original bytes ride+//! back to the caller on the message. An image the lane cannot take is blanked instead. The caller+//! produces them to the `session_replay_image_scrub` Kafka topic keyed by the ref; the scrub+//! consumer trusts the ref (this producer is the only writer), scrubs the bytes out of process, and+//! writes them to the ML bucket indexed by `(team_id, hash)`, so the ref embedded in the mirrored+//! lines is the join key.//!//! The hash is a *keyed* HMAC, not a plain digest: the ML bucket is unencrypted, and a plain//! content hash would let any bucket reader confirm whether specific known bytes appeared in a@@ -118,21 +118,23 @@ fn is_ref_hash(hash: &str) -> bool {.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')}-/// Default per-image cap. Bigger images stay on the inline blur path.+/// Default per-image cap. A bigger image is blanked.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-/// binding constraint for realistic payloads (only sub-64 KB average images can hit it first, and-/// pages with hundreds of tiny icons dedup heavily) — an image-heavy but ordinary snapshot should-/// never fall back on count alone.-///-/// Memory sizing: collection peaks at ~2x the byte cap in Rust per in-flight message (collector-/// vec + packed FFI buffer), and the mirror anonymizes up to its configured concurrency of-/// messages at once. Once produced, only the producer's bounded queue retains copies (the ack-/// closures deliberately capture refs, not bytes), so the cap never compounds into producer-side-/// backlog.-pub const MAX_IMAGES_PER_MESSAGE: usize = 512;-pub const MAX_TOTAL_BYTES_PER_MESSAGE: usize = 32 * 1024 * 1024;+/// Per-message caps bound what one payload can pin in memory and fan out onto the scrub topic.+/// Capture refuses messages over 64 MB, so the byte cap only binds on a payload that cv nesting+/// expanded past that. Collection peaks at about twice the byte cap per in-flight message+/// (collector vec plus the packed FFI buffer).+pub const MAX_IMAGES_PER_MESSAGE: usize = 4096;+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(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";+pub(crate) const DROP_MESSAGE_CAP: &str = "image_message_cap";/// Enables collection for one anonymize call.#[derive(Debug, Clone)]@@ -200,20 +202,18 @@ impl ImageCollector {removed}- /// 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> {+ pub fn collect(&mut self, bytes: Vec<u8>) -> Result<String, &'static str> {if bytes.len() > self.max_image_bytes {- return None;+ return Err(DROP_TOO_LARGE);}let hash = hash_image_bytes(self.content_key.as_bytes(), &bytes);if self.seen.contains(&hash) {- return Some(image_ref(&self.team_id, &hash));+ return Ok(image_ref(&self.team_id, &hash));}if self.images.len() >= MAX_IMAGES_PER_MESSAGE|| self.total_bytes + bytes.len() > MAX_TOTAL_BYTES_PER_MESSAGE{- return None;+ return Err(DROP_MESSAGE_CAP);}self.total_bytes += bytes.len();self.seen.insert(hash.clone());@@ -221,7 +221,7 @@ impl ImageCollector {hash: hash.clone(),bytes,});- Some(image_ref(&self.team_id, &hash))+ Ok(image_ref(&self.team_id, &hash))}/// Drain, sorted by hash — a deterministic order that cannot depend on which scrub engine@@ -235,8 +235,7 @@ impl ImageCollector {/// Raster subtypes preserved on a collected canvas blob's `type` field — downstream replay/// reassembly uses it as the format hint for the image behind the ref. Anything else (unknown/// subtypes, parameters — where client-controlled text could ride through unscrubbed) normalizes-/// to `image/png`. Exact matches only: the old blur path re-encoded and overwrote this field, so-/// no client string ever survived; the ref path must not weaken that.+/// to `image/png`. Exact matches only, so no client string survives in this field.const COLLECTED_MIME_ALLOWLIST: &[&str] = &["image/png", "image/jpeg", "image/gif", "image/webp"];pub fn normalize_collected_mime(mime: &str) -> &'static str {@@ -248,38 +247,53 @@ pub fn normalize_collected_mime(mime: &str) -> &'static str {.unwrap_or("image/png")}-/// Decode the collectable payload of an image data URI. `None` (not collectable) for anything but-/// 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, max_image_bytes: usize) -> Option<Vec<u8>> {- let rest = uri.strip_prefix("data:")?;- let (meta, payload) = rest.split_once(',')?;+/// Decode the collectable payload of an image data URI, or name why it is not one: only a base64+/// raster image the scrub can decode qualifies. 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,+ max_image_bytes: usize,+) -> Result<Vec<u8>, &'static str> {+ let (meta, payload) = uri+ .strip_prefix("data:")+ .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 None;+ 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") || mime_type.contains("bmp") || mime_type.contains("avif")- {- return None;+ if mime_type.starts_with("image/svg") {+ return Err(DROP_SVG);+ }+ if mime_type.contains("bmp") {+ return Err(DROP_BMP);+ }+ if mime_type.contains("avif") {+ return Err(DROP_AVIF);}// 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.+ // be rejected by `collect` — bail on the encoded length instead.if payload.len() > max_image_bytes.div_ceil(3) * 4 {- return None;+ return Err(DROP_TOO_LARGE);}let bytes = base64::engine::general_purpose::STANDARD.decode(payload.as_bytes())- .ok()?;+ .map_err(|_| DROP_NOT_RASTER)?;+ if bytes.starts_with(b"BM") {+ return Err(DROP_BMP);+ }// An ISO-BMFF container (AVIF, HEIC) under any label: the scrub refuses it, so a ref would dangle.- if bytes.starts_with(b"BM") || bytes.get(4..8) == Some(b"ftyp") {- return None;+ if bytes.get(4..8) == Some(b"ftyp") {+ return Err(DROP_AVIF);}- Some(bytes)+ Ok(bytes)}#[cfg(test)]@@ -287,7 +301,7 @@ mod tests {use super::*;fn collectable(uri: &str) -> Option<Vec<u8>> {- collectable_data_uri_bytes(uri, MAX_IMAGE_BYTES)+ collectable_data_uri_bytes(uri, MAX_IMAGE_BYTES).ok()}const TEST_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";@@ -348,7 +362,10 @@ mod tests {#[test]fn collect_rejects_oversized_image() {let mut c = collector();- assert!(c.collect(vec![0u8; MAX_IMAGE_BYTES + 1]).is_none());+ assert_eq!(+ c.collect(vec![0u8; MAX_IMAGE_BYTES + 1]),+ Err(DROP_TOO_LARGE)+ );assert!(c.into_images().is_empty());}@@ -356,19 +373,19 @@ mod tests {fn collect_stops_at_the_per_message_count_cap_but_still_refs_seen_images() {let mut c = collector();for i in 0..MAX_IMAGES_PER_MESSAGE {- assert!(c.collect(i.to_le_bytes().to_vec()).is_some());+ assert!(c.collect(i.to_le_bytes().to_vec()).is_ok());}- assert!(c.collect(b"one too many".to_vec()).is_none());+ assert_eq!(c.collect(b"one too many".to_vec()), Err(DROP_MESSAGE_CAP));// A repeat of an already-collected image still resolves to its ref.- assert!(c.collect(0usize.to_le_bytes().to_vec()).is_some());+ assert!(c.collect(0usize.to_le_bytes().to_vec()).is_ok());assert_eq!(c.into_images().len(), MAX_IMAGES_PER_MESSAGE);}#[test]fn into_images_sorts_by_hash() {let mut c = collector();- c.collect(b"bbb".to_vec());- c.collect(b"aaa".to_vec());+ c.collect(b"bbb".to_vec()).unwrap();+ c.collect(b"aaa".to_vec()).unwrap();let images = c.into_images();assert!(images[0].hash < images[1].hash);}diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 481ad3211e4b..61fc3f8374f9 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -1,9 +1,9 @@-//! Per-message scrub context: the allow lists plus a blur memo.+//! Per-message scrub context: the allow lists plus an image memo.//!//! Within one Kafka message the same image often recurs thousands of times (a canvas redrawing one-//! sprite, a repeated background). Blurring is pure in its input, so we memoize it per message and-//! collapse that fan-out to a single decode+blur — mirroring the TS `blurCache` (also scoped to one-//! message). Scope is one `anonymize_message` call; the map is dropped when it returns.+//! sprite, a repeated background). Its outcome is pure in its input, so we memoize it per message and+//! collapse that fan-out to a single decode and hash. Scope is one `anonymize_message` call; the+//! map is dropped when it returns.use std::cell::{Cell, RefCell};use std::collections::{BTreeMap, HashMap};@@ -13,12 +13,12 @@ use serde::Serialize;use crate::allow_lists::AllowLists;use crate::assets::PLACEHOLDER_SRC;-use crate::blur::{blank_image_data_uri, blur_image_data_uri};use crate::collect::{collectable_data_uri_bytes, is_image_ref, CollectedImage, ImageCollection, ImageCollector,- MAX_IMAGE_BYTES,+ DROP_COLLECTION_OFF, DROP_MESSAGE_CAP, MAX_IMAGE_BYTES,};-use crate::images::{ImageFallback, ImagePolicy, ImageQueue};+use crate::data_uri::blank_image_data_uri;+use crate::data_uri::ImageFallback;use crate::timings::PhaseTimings;use crate::url_collect::{CollectedUrl, UrlCollection, UrlCollector};@@ -48,19 +48,15 @@ pub struct ImageSourceCount {pub count: u32,}-/// Scrub context: the allow lists, the cv decompression budget, the blur memo, the image scrub-/// policy (inline blur, or deferred onto the shared worker pool), and the optional collection lane.+/// Scrub context: the allow lists, the cv decompression budget, the image memo, and the optional+/// collection lanes.pub struct Ctx<'a> {pub allow: &'a AllowLists,pub cv_budget: Cell<usize>,- // key: the original data URI.- // value: the replacement — a content ref (collection lane), a blurred data URI — or `None`- // when neither could be produced (caller falls back to a blank pixel).- blur_cache: RefCell<HashMap<String, Option<String>>>,+ // key: the original data URI. value: its content ref, or why the scrub lane declined it.+ image_memo: RefCell<HashMap<String, Result<String, &'static str>>>,timings: Option<&'a PhaseTimings>,- image_policy: ImagePolicy,- images: ImageQueue,- // `Some` routes collectable images to the scrub lane instead of the blur (inline or pooled).+ // `Some` routes images to the scrub lane. Without it every image is blanked.collector: Option<RefCell<ImageCollector>>,// `Some` routes remote image URLs to the fetch lane and emits refs beside the media placeholder.url_collector: Option<RefCell<UrlCollector>>,@@ -74,35 +70,30 @@ pub struct Ctx<'a> {impl<'a> Ctx<'a> {pub fn new(allow: &'a AllowLists) -> Self {- Self::with_options(allow, None, ImagePolicy::Inline, None)+ Self::with_options(allow, None, None)}pub fn with_timings(allow: &'a AllowLists, timings: Option<&'a PhaseTimings>) -> Self {- Self::with_options(allow, timings, ImagePolicy::Inline, None)+ Self::with_options(allow, timings, None)}pub fn with_image_collection(allow: &'a AllowLists,image_collection: Option<ImageCollection>,) -> Self {- Self::with_options(allow, None, ImagePolicy::Inline, image_collection)+ Self::with_options(allow, None, image_collection)}- // pub(crate): the token-patch barriers live only in the kafka snapshot pipeline, so a- // caller-built Parallel Ctx on the other entry points would emit unresolved tokens.pub(crate) fn with_options(allow: &'a AllowLists,timings: Option<&'a PhaseTimings>,- image_policy: ImagePolicy,image_collection: Option<ImageCollection>,) -> Self {Self {allow,cv_budget: Cell::new(CV_MESSAGE_DECOMPRESSION_BUDGET),- blur_cache: RefCell::new(HashMap::new()),+ image_memo: RefCell::new(HashMap::new()),timings,- image_policy,- images: ImageQueue::default(),collector: image_collection.map(|c| RefCell::new(ImageCollector::new(c))),url_collector: None,image_source_log: RefCell::new(Vec::new()),@@ -128,30 +119,20 @@ impl<'a> Ctx<'a> {self.preserve_image_refs}- /// Scrub one image data URI: the collection lane's content ref when it takes the image (no blur- /// work at all — the original bytes ride back to the caller for the out-of-band scrub), else- /// per the policy — the blurred URI (inline), or a token the patch pass later replaces- /// (parallel). Failures resolve to `fallback` either way. A message that exhausts the- /// queued-bytes budget degrades to inline for the remainder — bounded memory, identical output.+ /// Scrub one image data URI: the collection lane's content ref, whose original bytes ride back+ /// 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 {- if let Some(collected) = self.collect_image(original) {- return collected;- }- if self.image_policy == ImagePolicy::Parallel {- if let Some(token) = self.images.submit(- original,- fallback,- true,- crate::images::MAX_QUEUED_URI_BYTES,- ) {- return token;+ match self.collect_image(original) {+ Ok(reference) => reference,+ Err(reason) => {+ self.record_scrub_drop(reason);+ match fallback {+ ImageFallback::Blank => blank_image_data_uri(),+ ImageFallback::Placeholder => PLACEHOLDER_SRC.to_string(),+ }}}- match (self.blur_data_uri(original), fallback) {- (Some(blurred), _) => blurred,- (None, ImageFallback::Blank) => blank_image_data_uri(),- (None, ImageFallback::Placeholder) => PLACEHOLDER_SRC.to_string(),- }}pub(crate) fn scrub_image_from(@@ -167,21 +148,6 @@ impl<'a> Ctx<'a> {scrubbed}- pub(crate) fn has_pending_images(&self) -> bool {- self.images.has_pending()- }-- /// Replace any outstanding image tokens in serialized output, waiting for their jobs. Must run- /// wherever bytes become immutable: before a cv payload compresses, and on the final lines.- /// Worker-side blur time lands in the timings sink here, as jobs are claimed.- pub(crate) fn patch_pending_images(&self, buf: Vec<u8>) -> Vec<u8> {- let out = self.images.patch(buf);- if let Some(t) = self.timings {- self.images.drain_blur_time_into(t);- }- out- }-fn timed<T>(&self, op: &'static str, f: impl FnOnce() -> T) -> T {match self.timings {Some(t) => t.time_op(op, f),@@ -266,9 +232,11 @@ impl<'a> Ctx<'a> {};let removed = collector.borrow_mut().truncate(checkpoint.images);if !removed.is_empty() {- self.blur_cache- .borrow_mut()- .retain(|_, hit| !hit.as_ref().is_some_and(|r| removed.contains(r)));+ self.image_memo.borrow_mut().retain(|_, hit| match hit {+ Ok(reference) => !removed.contains(reference),+ // The freed room may now take an image the cap refused.+ Err(reason) => *reason != DROP_MESSAGE_CAP,+ });}}@@ -335,7 +303,7 @@ impl<'a> Ctx<'a> {/// Restore the full cv decompression budget. The budget bounds one message; per-line callers/// ([`crate::event::anonymize_line_with_ctx`]) reset it each call so a long session file- /// cannot exhaust it, while the blur memo keeps spanning the whole `Ctx`.+ /// cannot exhaust it, while the image memo keeps spanning the whole `Ctx`.pub fn reset_cv_budget(&self) {self.cv_budget.set(CV_MESSAGE_DECOMPRESSION_BUDGET);}@@ -352,36 +320,20 @@ impl<'a> Ctx<'a> {Ok(out)}- // Borrow discipline: never hold a `blur_cache` borrow across the blur call — the compute runs- // borrow-free, so a future blur helper that re-entered `Ctx` still couldn't double-borrow-panic.-- /// Blur a data-image URI inline, memoized on the URI. `None` → caller falls back to a- /// blank/placeholder.- pub fn blur_data_uri(&self, original: &str) -> Option<String> {- if let Some(hit) = self.blur_cache.borrow().get(original) {+ /// The collection lane's ref for a data URI, or why the lane declined it. Both are memoized,+ /// so a sprite recurring thousands of times decodes and hashes once.+ fn collect_image(&self, original: &str) -> Result<String, &'static str> {+ let collector = self.collector.as_ref().ok_or(DROP_COLLECTION_OFF)?;+ if let Some(hit) = self.image_memo.borrow().get(original) {return hit.clone();}- let result = self.timed("blur", || blur_image_data_uri(original));- self.blur_cache+ let max_image_bytes = collector.borrow().max_image_bytes();+ let outcome = collectable_data_uri_bytes(original, max_image_bytes)+ .and_then(|bytes| collector.borrow_mut().collect(bytes));+ self.image_memo.borrow_mut()- .insert(original.to_string(), result.clone());- result- }-- /// The collection lane's ref for a data URI, or `None` (collection off, non-collectable URI,- /// or a cap hit) — the caller then blurs per the policy as before. Refs are memoized in the- /// blur cache so a sprite recurring thousands of times hashes once.- fn collect_image(&self, original: &str) -> Option<String> {- let collector = self.collector.as_ref()?;- if let Some(Some(hit)) = self.blur_cache.borrow().get(original) {- return Some(hit.clone());- }- let bytes = collectable_data_uri_bytes(original, collector.borrow().max_image_bytes())?;- let collected = collector.borrow_mut().collect(bytes)?;- self.blur_cache- .borrow_mut()- .insert(original.to_string(), Some(collected.clone()));- Some(collected)+ .insert(original.to_string(), outcome.clone());+ outcome}pub(crate) fn max_collected_image_bytes(&self) -> usize {@@ -426,14 +378,73 @@ mod tests {}#[test]- fn blur_memo_is_stable_and_keyed_per_image() {+ fn a_discarded_walk_frees_the_message_cap_for_a_later_image() {+ use base64::Engine;let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());- let ctx = Ctx::new(&allow);- let a = png_data_uri(100, 50, [10, 20, 30, 255]);- let b = png_data_uri(40, 40, [200, 100, 50, 255]);- // Same input → same result twice (a cache hit must not return something different).- assert_eq!(ctx.blur_data_uri(&a), ctx.blur_data_uri(&a));- // Distinct inputs → distinct results (guards against a cache-key collision serving A's blur for B).- assert_ne!(ctx.blur_data_uri(&a), ctx.blur_data_uri(&b));+ let ctx = Ctx::with_image_collection(+ &allow,+ Some(ImageCollection::new("42".to_string(), "k".repeat(32))),+ );+ let uri = |n: usize| {+ let payload = base64::engine::general_purpose::STANDARD.encode(n.to_be_bytes());+ format!("data:image/png;base64,{payload}")+ };+ let checkpoint = ctx.count_checkpoint();+ for n in 0..crate::collect::MAX_IMAGES_PER_MESSAGE {+ assert!(is_image_ref(+ &ctx.scrub_image(&uri(n), ImageFallback::Blank)+ ));+ }+ let late = uri(usize::MAX);+ assert_eq!(+ ctx.scrub_image(&late, ImageFallback::Blank),+ blank_image_data_uri()+ );+ ctx.discard_walk(checkpoint);+ assert!(is_image_ref(&ctx.scrub_image(&late, ImageFallback::Blank)));+ assert_eq!(ctx.into_collected_images().len(), 1);+ }++ #[test]+ fn an_image_the_lane_cannot_take_is_blanked_and_counted() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let png = png_data_uri(8, 8, [10, 20, 30, 255]);+ let lane = || Some(ImageCollection::new("42".to_string(), "k".repeat(32)));+ let tiny_lane = || {+ Some(ImageCollection {+ max_image_bytes: 16,+ ..ImageCollection::new("42".to_string(), "k".repeat(32))+ })+ };+ let cases = [+ (+ Ctx::new(&allow),+ png.clone(),+ crate::collect::DROP_COLLECTION_OFF,+ ),+ (+ Ctx::with_image_collection(&allow, lane()),+ "data:image/svg+xml;base64,PHN2Zz4=".to_string(),+ crate::collect::DROP_SVG,+ ),+ (+ Ctx::with_image_collection(&allow, tiny_lane()),+ png.clone(),+ crate::collect::DROP_TOO_LARGE,+ ),+ ];+ for (ctx, uri, reason) in cases {+ assert_eq!(+ ctx.scrub_image(&uri, ImageFallback::Blank),+ blank_image_data_uri(),+ "{reason}"+ );+ assert_eq!(+ ctx.scrub_image(&uri, ImageFallback::Placeholder),+ PLACEHOLDER_SRC,+ "{reason}"+ );+ assert_eq!(ctx.take_scrub_drops(), vec![(reason, 2)], "{reason}");+ }}}diff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rsindex a91d5b4bf261..98b5c47f30f6 100644--- a/rust/replay-anonymizer/src/css.rs+++ b/rust/replay-anonymizer/src/css.rs@@ -6,10 +6,10 @@ use simd_json::borrowed::{Object, Value};use crate::assets::{is_numbered_placeholder, numbered_placeholder, CSS_IMAGE_REFS_ATTR_PREFIX, PLACEHOLDER_SRC,};-use crate::blur::is_image_data_uri;use crate::collect::{is_image_ref, is_image_ref_strict};use crate::context::{Ctx, ImageSource};-use crate::images::ImageFallback;+use crate::data_uri::is_image_data_uri;+use crate::data_uri::ImageFallback;use crate::json::{as_array_mut, as_object_mut, as_str, string_value};pub const INLINED_STYLESHEET_ATTR: &str = "_cssText";diff --git a/rust/replay-anonymizer/src/cv.rs b/rust/replay-anonymizer/src/cv.rsindex f09dfc1ad79a..2793e5dc7b66 100644--- a/rust/replay-anonymizer/src/cv.rs+++ b/rust/replay-anonymizer/src/cv.rs@@ -11,7 +11,6 @@ use crate::context::Ctx;use crate::dom::{scrub_full_snapshot, scrub_mutation_adds, scrub_mutation_attributes, scrub_mutation_texts,};-use crate::images;use crate::json::{as_array_mut, key, parse_untrusted, reject_if_too_deep, string_value};/// PostHog wire format: each gzip byte stored as its U+00XX codepoint (latin-1). Per-char is@@ -50,33 +49,16 @@ fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<(Vec<u8>, bool)> {Ok((out, was_zstd))}-/// The single way scrubbed bytes may become a compressed cv payload.-///-/// Compression is this payload's point of no return: afterwards the bytes are opaque to every-/// later patch pass, so a deferred-image token still present here would ship as an image no-/// reader can ever resolve (the token marker is random per process). Everything that re-emits a-/// cv payload — this module and the byte walk — goes through here so the patch cannot be-/// forgotten, and the check below fails the payload closed if it ever is.-pub(crate) fn compress_scrubbed(ctx: &Ctx<'_>, json: &[u8]) -> Result<Vec<u8>> {- let patched;- let json = if ctx.has_pending_images() {- patched = ctx.patch_pending_images(json.to_vec());- patched.as_slice()- } else {- json- };- if images::contains_token(json) {- bail!("unresolved image token in a cv payload about to compress");- }+pub(crate) fn compress_scrubbed(json: &[u8]) -> Result<Vec<u8>> {compression::compress_cv(json).context("compress cv payload")}-fn compress_bytes(ctx: &Ctx<'_>, json: &[u8]) -> Result<String> {- Ok(bytes_to_latin1(&compress_scrubbed(ctx, json)?))+fn compress_bytes(json: &[u8]) -> Result<String> {+ Ok(bytes_to_latin1(&compress_scrubbed(json)?))}-fn compress_value(ctx: &Ctx<'_>, value: &Value<'_>) -> Result<String> {- compress_bytes(ctx, value.encode().as_bytes())+fn compress_value(value: &Value<'_>) -> Result<String> {+ compress_bytes(value.encode().as_bytes())}/// Scrub a `cv`-compressed FullSnapshot `data` value (a compressed latin-1 string, gzip or zstd)@@ -97,11 +79,11 @@ pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Reif was_zstd {return Ok(false);}- *data = string_value(compress_bytes(ctx, &scratch)?);+ *data = string_value(compress_bytes(&scratch)?);return Ok(true);}Some(true) => {- *data = string_value(compress_bytes(ctx, &walked)?);+ *data = string_value(compress_bytes(&walked)?);return Ok(true);}None => {}@@ -111,7 +93,7 @@ pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Rereject_if_too_deep(&scratch, "cv payload")?;let mut payload = parse_untrusted(&mut scratch).context("parse cv payload")?;scrub_full_snapshot(ctx, &mut payload);- let recompressed = compress_value(ctx, &payload)?;+ let recompressed = compress_value(&payload)?;*data = string_value(recompressed);Ok(true)}@@ -185,7 +167,7 @@ pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> Result}for (sub_key, json) in recompress {- data.insert(key(sub_key), string_value(compress_bytes(ctx, &json)?));+ data.insert(key(sub_key), string_value(compress_bytes(&json)?));}Ok(changed)diff --git a/rust/replay-anonymizer/src/data_uri.rs b/rust/replay-anonymizer/src/data_uri.rsnew file mode 100644index 000000000000..fb52a1db19fd--- /dev/null+++ b/rust/replay-anonymizer/src/data_uri.rs@@ -0,0 +1,47 @@+//! Data URI helpers, and the stand-ins an image becomes when the scrub lane cannot take it.++/// A 1x1 transparent PNG: what an image the scrub lane cannot take becomes.+pub const BLANK_PNG_BASE64: &str =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNgAAIAAAUAAen63NgAAAAASUVORK5CYII=";++pub fn blank_image_data_uri() -> String {+ format!("data:image/png;base64,{BLANK_PNG_BASE64}")+}++pub fn is_image_data_uri(s: &str) -> bool {+ s.starts_with("data:image/")+}++/// Split a `data:<mime>;...,<base64>` URI into (mime, base64). None if not a data URI.+pub fn split_data_uri(uri: &str) -> Option<(String, String)> {+ let rest = uri.strip_prefix("data:")?;+ let comma = rest.find(',')?;+ let mime = rest[..comma].split(';').next().unwrap_or("image/png");+ let mime = if mime.is_empty() { "image/png" } else { mime };+ Some((mime.to_string(), rest[comma + 1..].to_string()))+}++/// What an image the scrub lane cannot take is replaced with; chosen per occurrence.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum ImageFallback {+ /// Blank 1x1 PNG (inline images, canvas frames, css).+ Blank,+ /// The media placeholder SVG (media `src`-style attributes).+ Placeholder,+}++#[cfg(test)]+mod tests {+ use super::*;+ use base64::Engine;++ #[test]+ fn the_blank_image_decodes_to_one_transparent_pixel() {+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(BLANK_PNG_BASE64)+ .unwrap();+ let image = image::load_from_memory(&bytes).unwrap().to_rgba8();+ assert_eq!(image.dimensions(), (1, 1));+ assert_eq!(image.get_pixel(0, 0).0[3], 0);+ }+}diff --git a/rust/replay-anonymizer/src/dom.rs b/rust/replay-anonymizer/src/dom.rsindex 87476c86d0b4..cf25ab6f4ccb 100644--- a/rust/replay-anonymizer/src/dom.rs+++ b/rust/replay-anonymizer/src/dom.rs@@ -5,8 +5,8 @@use simd_json::borrowed::{Object, Value};use crate::assets::{- apply_blur, blur_inline_image_attr, has_media_src_attr, is_image_ref_attr, is_media_src_attr,- is_media_tag, CSS_IMAGE_REFS_ATTR_PREFIX, INLINE_IMAGE_ATTR,+ has_media_src_attr, is_image_ref_attr, is_media_src_attr, is_media_tag,+ scrub_inline_image_attr, scrub_media_sources, CSS_IMAGE_REFS_ATTR_PREFIX, INLINE_IMAGE_ATTR,};use crate::collect::is_image_ref_strict;use crate::context::Ctx;@@ -218,7 +218,7 @@ fn scrub_attrs() -> bool {let mut changed = false;// Plain string scrubs mutate values in place while iterating — no per-element key Vec. Only the- // helpers that need `&mut Object` (blur inserts sibling keys, css re-reads by key) defer their+ // helpers that need `&mut Object` (media sources insert sibling keys, css re-reads by key) defer their// attr names, which most elements don't have. Each attr is scrubbed independently, so running// the deferred ones after the loop produces the same result as the original in-order pass.let mut deferred: Vec<String> = Vec::new();@@ -241,7 +241,7 @@ fn scrub_attrs(if kind == TagKind::Media && is_media_src_attr(name) {continue;}- // Inlined rendered pixels (`rr_dataURL`): blur the image, on any tag.+ // Inlined rendered pixels (`rr_dataURL`): scrub the image, on any tag.if name == INLINE_IMAGE_ATTR || name == "style" || name == INLINED_STYLESHEET_ATTR {deferred.push(name.to_string());continue;@@ -276,7 +276,7 @@ fn scrub_attrs(for name in deferred {if name == INLINE_IMAGE_ATTR {- changed |= blur_inline_image_attr(ctx, attrs, &name);+ changed |= scrub_inline_image_attr(ctx, attrs, &name);} else if name == "style" {changed |= scrub_css_images(ctx, attrs, &name, CssContext::DeclarationList);} else {@@ -285,7 +285,7 @@ fn scrub_attrs(}if kind == TagKind::Media {- changed |= apply_blur(ctx, attrs, tag, parent_is_picture);+ changed |= scrub_media_sources(ctx, attrs, tag, parent_is_picture);}changed@@ -365,8 +365,11 @@ mod tests {let v = out["node"]["childNodes"][0]["attributes"]["rr_dataURL"].as_str().unwrap();- assert!(v.starts_with("data:image/"), "still an image: {v}");- assert_ne!(v, uri, "raw inline image must not pass through");+ assert_eq!(+ v,+ crate::data_uri::blank_image_data_uri(),+ "blanked without the scrub lane"+ );}#[test]@@ -394,7 +397,7 @@ mod tests {#[test]fn media_tag_without_source_attrs_is_not_marked_changed() {- // A bare <img> (media tag, but no src/href/etc. to blur) must report "unchanged" so the whole+ // A bare <img> (media tag, but no src/href/etc. to scrub) must report "unchanged" so the whole// message isn't needlessly re-serialized just because a media element was present.let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());let ctx = Ctx::new(&allow);@@ -402,7 +405,7 @@ mod tests {let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();assert!(!scrub_full_snapshot(&ctx, &mut data),- "a media tag with nothing to blur should not count as a change"+ "a media tag with nothing to scrub should not count as a change");}}diff --git a/rust/replay-anonymizer/src/event.rs b/rust/replay-anonymizer/src/event.rsindex 35989f701781..39b96d5d4cab 100644--- a/rust/replay-anonymizer/src/event.rs+++ b/rust/replay-anonymizer/src/event.rs@@ -47,8 +47,8 @@ fn contain_panics<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {/// Anonymizes every event in a parsed message (`{ windowId: Event[] }`) in place. `Ok(None)` means/// nothing changed (the caller can keep its original). `Err` means an event could not be anonymized —-/// fail closed, the caller must drop the message. A single `Ctx` spans the whole message so its blur-/// memo is shared across every event (an image recurring across events is blurred once).+/// fail closed, the caller must drop the message. A single `Ctx` spans the whole message so its image+/// memo is shared across every event (an image recurring across events is decoded once).pub fn anonymize_message(allow: &AllowLists, json: &mut [u8]) -> Result<Option<String>> {contain_panics(|| {reject_if_too_deep(json, "eventsByWindowId")?;@@ -105,8 +105,8 @@ fn require_event_type(event: &Value<'_>) -> Result<()> {}}-/// [`anonymize_line`] with a caller-owned [`Ctx`], so one blur memo spans a whole session file-/// (an image recurring across lines is decoded and blurred once, like `anonymize_message` does+/// [`anonymize_line`] with a caller-owned [`Ctx`], so one image memo spans a whole session file+/// (an image recurring across lines is decoded once, like `anonymize_message` does/// across a message's events). The cumulative cv decompression budget is per line — it resets on/// every call, so a long session cannot starve later lines.pub fn anonymize_line_with_ctx(ctx: &Ctx<'_>, line: &mut [u8]) -> Result<Option<String>> {@@ -149,7 +149,7 @@ pub fn anonymize_event_str(allow: &AllowLists, event_json: &str) -> Result<Strin/// Scrubs a single event in place, returning whether it changed. `Err` = "could not anonymize"./// Builds its own `Ctx` (single-event scope); the message path uses [`anonymize_message`] instead so-/// the blur memo is shared across events.+/// the image memo is shared across events.pub fn anonymize_event(allow: &AllowLists, event: &mut Value<'_>) -> Result<bool> {contain_panics(|| route_event(&Ctx::new(allow), event))}@@ -385,7 +385,7 @@ mod tests {}#[test]- fn line_streaming_shares_the_blur_memo_across_lines() {+ fn line_streaming_shares_the_image_memo_across_lines() {use crate::testkit::png_data_uri;let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());let ctx = Ctx::new(&allow);@@ -407,7 +407,7 @@ mod tests {let second_out = anonymize_line_with_ctx(&ctx, &mut second).unwrap().unwrap();assert_eq!(first_out, second_out,- "a recurring image must blur identically through the shared memo"+ "a recurring image must scrub identically through the shared memo");}@@ -434,11 +434,10 @@ mod tests {#[test]fn recurring_inline_image_is_neutralized_across_windows() {- // An inline image can recur across events/windows in one message (the case the per-message blur+ // An inline image can recur across events/windows in one message (the case the per-message image// memo targets). Every occurrence must be neutralized to a data-image — never the raw original —// and identical inputs must yield identical output. This drives the real `anonymize_message`- // entry (route -> full snapshot -> dom -> blur), which the deterministic JSON fixtures can't- // cover (blurred bytes differ from the TS `sharp` output, so image parity is Rust-only).+ // entry (route -> full snapshot -> dom -> image scrub).use crate::testkit::png_data_uri;use serde_json::json;let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());@@ -464,8 +463,11 @@ mod tests {.unwrap().to_string()};- assert!(img("w1").starts_with("data:image/"), "still an image");- assert_ne!(img("w1"), uri, "raw inline image must not pass through");+ assert_eq!(+ img("w1"),+ crate::data_uri::blank_image_data_uri(),+ "blanked without the scrub lane"+ );assert_eq!(img("w1"),img("w2"),diff --git a/rust/replay-anonymizer/src/images.rs b/rust/replay-anonymizer/src/images.rsdeleted file mode 100644index 1ca167100ae7..000000000000--- a/rust/replay-anonymizer/src/images.rs+++ /dev/null@@ -1,457 +0,0 @@-//! Deferred image scrubbing: the walk swaps each image data URI for a token and queues the-//! decode+blur+encode on a small shared worker pool, so pixel work overlaps the rest of the walk.-//! Serialized output is patched wherever it becomes immutable — before each cv payload compresses,-//! and over the final block lines.-//!-//! Dedup is preserved: the job map is keyed on the original URI per message (the same role the-//! inline blur memo plays), so a recurring image submits one job and every occurrence patches to-//! the same result. Fail-safe matches the inline path: a failed or panicked job patches to the-//! occurrence's fallback (blank pixel or media placeholder), carried in the token.-//!-//! Tokens are plain base64-alphabet text (`xph<marker><id><fallback>`), optionally wrapped as a-//! `data:image/png;base64,…` URI, so they survive JSON serialization byte-for-byte; the marker is-//! random per process, so real payload bytes cannot collide with a live token.--use std::cell::{Cell, RefCell};-use std::collections::hash_map::RandomState;-use std::collections::HashMap;-use std::hash::{BuildHasher, Hasher};-use std::panic::{catch_unwind, AssertUnwindSafe};-use std::sync::{mpsc, Arc, LazyLock, Mutex};-use std::time::Instant;--use crate::assets::PLACEHOLDER_SRC;-use crate::blur::{blur_image_data_uri, BLANK_PNG_BASE64};-use crate::timings::PhaseTimings;--/// How images found during the walk are scrubbed.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]-pub enum ImagePolicy {- /// Blur synchronously on the walk thread (the original behavior).- #[default]- Inline,- /// Queue blurs on the shared worker pool and patch tokens into the serialized output.- Parallel,-}--/// What a failed blur resolves to; chosen per occurrence, matching the inline call sites.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(crate) enum ImageFallback {- /// Blank 1x1 PNG (inline images, canvas args, css).- Blank,- /// The media placeholder SVG (media `src`-style attributes).- Placeholder,-}--const DATA_URI_PREFIX: &[u8] = b"data:image/png;base64,";-const ID_HEX_LEN: usize = 8;--/// Cap on the URI bytes one message may have queued: each job clones its data URI, so an-/// image-stuffed message would otherwise retain a second copy of its whole payload while the-/// fixed-size pool catches up. Past the cap, `submit` declines and the caller blurs inline —-/// slower, bounded, identical output. Global memory stays bounded at (concurrent messages x cap).-pub(crate) const MAX_QUEUED_URI_BYTES: usize = 32 * 1024 * 1024;--/// Cap on distinct queued images per message: the byte budget alone under-counts tiny URIs, whose-/// per-job overhead (job struct, result channel, map entries) dominates their payload. Real-/// messages hold at most dozens of distinct images — repeats dedup — so past this the caller-/// scrubs inline. With bounded scrub concurrency this also bounds the global channel depth.-pub(crate) const MAX_QUEUED_IMAGES_PER_MESSAGE: u32 = 512;--/// Generous ceiling on one blur job (worst real decodes are hundreds of ms); see `resolve`.-const IMAGE_JOB_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);--/// Random 128 bits per process: payload bytes can't be crafted (or fluked, at any volume) to-/// collide with a live token — a false match needs this exact 35-char ASCII run in the payload.-static TOKEN_MARKER: LazyLock<String> = LazyLock::new(|| {- let state = RandomState::new();- let mut a = state.build_hasher();- a.write_u32(std::process::id());- let mut b = state.build_hasher();- b.write_u64(a.finish());- b.write_u32(std::process::id());- format!("xph{:016x}{:016x}", a.finish(), b.finish())-});--fn worker_count() -> usize {- std::env::var("REPLAY_ANONYMIZER_IMAGE_THREADS")- .ok()- .and_then(|v| v.parse::<usize>().ok())- .unwrap_or_else(|| {- std::thread::available_parallelism()- .map(|n| n.get().min(4))- .unwrap_or(2)- })- .clamp(1, 64)-}--struct Job {- uri: String,- result_tx: mpsc::SyncSender<JobResult>,-}--struct JobResult {- /// PNG base64 (no `data:` prefix); `None` = the image could not be blurred.- b64: Option<String>,- elapsed_ns: u64,-}--/// One shared pool for the whole process: total blur parallelism stays bounded no matter how many-/// messages scrub concurrently on the libuv threadpool. `None` when no worker could be spawned —-/// submission then declines and every image scrubs inline instead.-static POOL: LazyLock<Option<mpsc::Sender<Job>>> = LazyLock::new(|| {- let (tx, rx) = mpsc::channel::<Job>();- let rx = Arc::new(Mutex::new(rx));- let mut spawned = 0usize;- for i in 0..worker_count() {- let rx = Arc::clone(&rx);- let spawn_result = std::thread::Builder::new()- .name(format!("replay-img-scrub-{i}"))- .spawn(move || loop {- let job = match rx.lock() {- Ok(guard) => match guard.recv() {- Ok(job) => job,- Err(_) => break,- },- Err(_) => break,- };- let start = Instant::now();- // A panic on a hostile image fails that one job closed, not the worker.- let b64 = catch_unwind(AssertUnwindSafe(|| blur_image_data_uri(&job.uri)))- .unwrap_or(None)- .and_then(|uri| {- uri.strip_prefix("data:image/png;base64,")- .map(str::to_string)- });- let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX - 1);- // The queue side may already have given up on this job; a send error is fine.- job.result_tx.send(JobResult { b64, elapsed_ns }).ok();- });- if spawn_result.is_ok() {- spawned += 1;- }- }- (spawned > 0).then_some(tx)-});--enum JobState {- Pending(mpsc::Receiver<JobResult>),- /// Resolved blur output (PNG base64) plus the worker-side elapsed time, `0` once reported.- Resolved(Option<String>),-}--/// Per-message queue: URI-keyed dedup plus id-keyed job states for the patch pass.-#[derive(Default)]-pub struct ImageQueue {- ids_by_uri: RefCell<HashMap<String, u32>>,- jobs: RefCell<HashMap<u32, JobState>>,- next_id: Cell<u32>,- queued_uri_bytes: Cell<usize>,- /// Worker-side blur time and job count, accumulated as results are claimed.- pub(crate) blur_ns: Cell<u64>,- pub(crate) blur_count: Cell<u32>,-}--impl ImageQueue {- /// Submits (or dedups) a blur job and returns the occurrence's token, `data:`-wrapped when the- /// call site substitutes a full URI. `None` = the per-message byte budget is spent and the- /// caller must scrub this occurrence inline.- pub(crate) fn submit(- &self,- uri: &str,- fallback: ImageFallback,- wrapped: bool,- max_queued_uri_bytes: usize,- ) -> Option<String> {- let known = self.ids_by_uri.borrow().get(uri).copied();- let id = if let Some(id) = known {- id- } else {- let queued = self.queued_uri_bytes.get().saturating_add(uri.len());- if queued > max_queued_uri_bytes || self.next_id.get() >= MAX_QUEUED_IMAGES_PER_MESSAGE- {- return None;- }- let (result_tx, result_rx) = mpsc::sync_channel(1);- // A missing or wedged pool declines instead of panicking; the caller scrubs inline.- POOL.as_ref()?- .send(Job {- uri: uri.to_string(),- result_tx,- })- .ok()?;- self.queued_uri_bytes.set(queued);- let id = self.next_id.get();- self.next_id.set(id + 1);- self.ids_by_uri.borrow_mut().insert(uri.to_string(), id);- self.jobs- .borrow_mut()- .insert(id, JobState::Pending(result_rx));- id- };- let fb = match fallback {- ImageFallback::Blank => 'b',- ImageFallback::Placeholder => 'p',- };- let core = format!("{}{id:08x}{fb}", &*TOKEN_MARKER);- Some(if wrapped {- format!(- "{}{core}",- std::str::from_utf8(DATA_URI_PREFIX).expect("static prefix is utf-8")- )- } else {- core- })- }-- /// Move blur time accumulated by claimed jobs into the timings sink (idempotent via reset).- pub(crate) fn drain_blur_time_into(&self, timings: &PhaseTimings) {- let (ns, count) = (self.blur_ns.replace(0), self.blur_count.replace(0));- if count > 0 {- timings.add_blur(ns, count);- }- }-- /// Whether any jobs were queued for this message (tokens may be present in output).- pub(crate) fn has_pending(&self) -> bool {- !self.jobs.borrow().is_empty()- }-- /// Blocks until the job's result is in (the patch barrier); `None` = blur failed.- fn resolve(&self, id: u32) -> Option<String> {- let mut jobs = self.jobs.borrow_mut();- let state = jobs.get_mut(&id)?;- if let JobState::Pending(rx) = state {- // Bounded wait: a wedged worker fails this image closed instead of stalling the- // partition; a straggler's late result lands in the buffered channel and is dropped.- let result = match rx.recv_timeout(IMAGE_JOB_TIMEOUT) {- Ok(r) => r,- Err(_) => JobResult {- b64: None,- elapsed_ns: 0,- },- };- self.blur_ns- .set(self.blur_ns.get().saturating_add(result.elapsed_ns));- self.blur_count.set(self.blur_count.get().saturating_add(1));- *state = JobState::Resolved(result.b64);- }- match state {- JobState::Resolved(b64) => b64.clone(),- JobState::Pending(_) => unreachable!("state was just resolved"),- }- }-- /// Replaces every token in `buf` with its blur result (waiting for stragglers), returning the- /// input untouched when nothing was queued or nothing matches. Call wherever serialized bytes- /// become immutable: before a cv payload compresses, and on the final block lines.- pub(crate) fn patch(&self, buf: Vec<u8>) -> Vec<u8> {- if !self.has_pending() {- return buf;- }- let needle = TOKEN_MARKER.as_bytes();- let token_len = needle.len() + ID_HEX_LEN + 1;- let mut out: Option<Vec<u8>> = None;- let mut copied_to = 0usize;- let mut search_from = 0usize;- while let Some(rel) = memchr::memmem::find(&buf[search_from..], needle) {- let start = search_from + rel;- if start + token_len > buf.len() {- break;- }- let Some(id) =- parse_hex_id(&buf[start + needle.len()..start + needle.len() + ID_HEX_LEN])- else {- search_from = start + needle.len();- continue;- };- let fallback = match buf[start + token_len - 1] {- b'b' => ImageFallback::Blank,- b'p' => ImageFallback::Placeholder,- _ => {- search_from = start + needle.len();- continue;- }- };- // An id this queue never issued still gets substituted, deliberately. Leaving it would- // put a live token in output, which is unrecoverable: the marker is random per process,- // so nothing downstream can turn it back into an image. Payload bytes cannot realistically- // carry this process's 128-bit marker, so an unknown id means a token reached a buffer its- // own queue did not patch — a bug — and the fallback is the safe way to fail it.- let known = self.jobs.borrow().contains_key(&id);- let wrapped = start >= DATA_URI_PREFIX.len()- && &buf[start - DATA_URI_PREFIX.len()..start] == DATA_URI_PREFIX;- let span_start = if wrapped {- start - DATA_URI_PREFIX.len()- } else {- start- };- let span_end = start + token_len;- let resolved = if known { self.resolve(id) } else { None };- let replacement: String = match (resolved, fallback) {- (Some(b64), _) => {- if wrapped {- format!("data:image/png;base64,{b64}")- } else {- b64- }- }- (None, ImageFallback::Placeholder) => PLACEHOLDER_SRC.to_string(),- (None, ImageFallback::Blank) => {- if wrapped {- format!("data:image/png;base64,{BLANK_PNG_BASE64}")- } else {- BLANK_PNG_BASE64.to_string()- }- }- };- let out = out.get_or_insert_with(|| Vec::with_capacity(buf.len()));- out.extend_from_slice(&buf[copied_to..span_start]);- out.extend_from_slice(replacement.as_bytes());- copied_to = span_end;- search_from = span_end;- }- match out {- Some(mut out) => {- out.extend_from_slice(&buf[copied_to..]);- out- }- None => buf,- }- }-}--fn parse_hex_id(bytes: &[u8]) -> Option<u32> {- let s = std::str::from_utf8(bytes).ok()?;- u32::from_str_radix(s, 16).ok()-}--/// True if `buf` still carries this process's token marker.-///-/// The barrier check. `patch` can only fix what it is handed, so every point where scrubbed bytes-/// stop being patchable — a cv payload about to compress, the finished block lines — asserts this-/// is false before letting them past. A hit means some serialization path reached that point-/// without patching, which is silent, unrecoverable data loss if it ships (the marker is random-/// per process, so no reader can ever resolve the token back to an image). Cheap: one memmem over-/// bytes that are about to be compressed or written anyway.-pub(crate) fn contains_token(buf: &[u8]) -> bool {- memchr::memmem::find(buf, TOKEN_MARKER.as_bytes()).is_some()-}--#[cfg(test)]-mod tests {- use super::*;- use crate::testkit::png_data_uri;-- #[test]- fn submit_dedups_by_uri_and_patch_replaces_every_occurrence() {- let q = ImageQueue::default();- let uri = png_data_uri(64, 32, [10, 20, 30, 255]);- let t1 = q- .submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)- .unwrap();- let t2 = q- .submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)- .unwrap();- assert_eq!(t1, t2);- assert_eq!(q.next_id.get(), 1);-- let raw = q- .submit(&uri, ImageFallback::Blank, false, MAX_QUEUED_URI_BYTES)- .unwrap();- assert!(t1.ends_with(&raw));-- let buf = format!("{{\"a\":\"{t1}\",\"b\":\"{t2}\",\"c\":\"{raw}\"}}").into_bytes();- let patched = String::from_utf8(q.patch(buf)).unwrap();- let expected = blur_image_data_uri(&uri).unwrap();- let expected_b64 = expected.strip_prefix("data:image/png;base64,").unwrap();- assert_eq!(- patched,- format!("{{\"a\":\"{expected}\",\"b\":\"{expected}\",\"c\":\"{expected_b64}\"}}")- );- assert_eq!(q.blur_count.get(), 1);- assert!(q.blur_ns.get() > 0);- }-- #[test]- fn failed_blur_patches_to_the_occurrence_fallback() {- let q = ImageQueue::default();- let bad = "data:image/png;base64,bm90IGFuIGltYWdl";- let wrapped = q- .submit(bad, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)- .unwrap();- let placeholder = q- .submit(bad, ImageFallback::Placeholder, true, MAX_QUEUED_URI_BYTES)- .unwrap();- let raw = q- .submit(bad, ImageFallback::Blank, false, MAX_QUEUED_URI_BYTES)- .unwrap();-- let buf = format!("[\"{wrapped}\",\"{placeholder}\",\"{raw}\"]").into_bytes();- let patched = String::from_utf8(q.patch(buf)).unwrap();- assert_eq!(- patched,- format!("[\"data:image/png;base64,{BLANK_PNG_BASE64}\",\"{PLACEHOLDER_SRC}\",\"{BLANK_PNG_BASE64}\"]")- );- assert_eq!(q.blur_count.get(), 1);- }-- #[test]- fn submissions_over_the_count_cap_decline() {- let q = ImageQueue::default();- q.next_id.set(MAX_QUEUED_IMAGES_PER_MESSAGE);- let uri = png_data_uri(8, 8, [7, 7, 7, 255]);- assert_eq!(- q.submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES),- None- );- }-- #[test]- fn over_budget_submissions_decline_but_known_uris_still_dedup() {- let q = ImageQueue::default();- let a = png_data_uri(16, 16, [1, 2, 3, 255]);- let b = png_data_uri(16, 16, [4, 5, 6, 255]);- let budget = a.len() + 1;- let t1 = q.submit(&a, ImageFallback::Blank, true, budget).unwrap();- // A new URI over the budget declines; the caller scrubs it inline.- assert_eq!(q.submit(&b, ImageFallback::Blank, true, budget), None);- // An already-queued URI still resolves to its token, budget notwithstanding.- assert_eq!(q.submit(&a, ImageFallback::Blank, true, budget), Some(t1));- }-- #[test]- fn replacements_never_need_json_escaping() {- // patch() splices replacements into already-serialized JSON without escaping, which is- // only sound while every possible replacement is escape-free.- let needs_escape = |s: &str| s.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20);- assert!(!needs_escape(PLACEHOLDER_SRC));- assert!(!needs_escape(BLANK_PNG_BASE64));- let blurred = blur_image_data_uri(&png_data_uri(32, 32, [9, 9, 9, 255])).unwrap();- assert!(!needs_escape(&blurred));- }-- #[test]- fn patch_is_a_no_op_without_queued_jobs() {- let q = ImageQueue::default();- let buf = b"{\"text\":\"no tokens here\"}".to_vec();- assert_eq!(q.patch(buf.clone()), buf);- }-- #[test]- fn a_token_this_queue_never_issued_still_never_survives() {- // A token reaching a buffer whose queue did not mint it is a bug, but it must degrade to- // the fallback rather than ship a live token: the marker is per-process, so a token in- // output is an image nothing can ever resolve.- let q = ImageQueue::default();- let uri = png_data_uri(8, 8, [1, 2, 3, 255]);- q.submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)- .unwrap();- let foreign = format!("{}{:08x}p", &*TOKEN_MARKER, 0xdead_beefu32);- let buf = format!("{{\"src\":\"data:image/png;base64,{foreign}\"}}").into_bytes();-- let patched = String::from_utf8(q.patch(buf)).unwrap();- assert_eq!(patched, format!("{{\"src\":\"{PLACEHOLDER_SRC}\"}}"));- assert!(!patched.contains(&*TOKEN_MARKER));- }-}diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 35ee92a325e6..e006a04f427c 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -1,6 +1,6 @@//! Session-replay anonymizer: PII-scrubs rrweb events for PostHog's ml-mirror pipelines.//!-//! The scrubbers cover text/URL redaction, native image blur, and `cv` de/recompression. Behavior+//! The scrubbers cover text/URL redaction, image collection for an out-of-band scrub, and `cv` de/recompression. Behavior//! is pinned by the shared JSON fixtures under `tests/fixtures/`, which both `tests/parity.rs` and//! the Node addon's Jest suite (through `replay-anonymizer-node`) run against.//!@@ -28,8 +28,6 @@ pub mod allow_lists;#[doc(hidden)]pub mod assets;#[doc(hidden)]-pub mod blur;-#[doc(hidden)]pub mod bytewalk;#[doc(hidden)]pub mod canvas;@@ -43,9 +41,10 @@ pub mod css;#[doc(hidden)]pub mod cv;#[doc(hidden)]+pub mod data_uri;+#[doc(hidden)]pub mod dom;pub mod event;-pub mod images;#[doc(hidden)]pub mod json;mod json_ld;@@ -76,7 +75,6 @@ pub use event::{anonymize_event, anonymize_event_str, anonymize_line, anonymize_line_with_ctx,anonymize_message,};-pub use images::ImagePolicy;pub use snapshot::{anonymize_kafka_payload, anonymize_kafka_payload_collecting, anonymize_kafka_payload_opts,anonymize_kafka_payload_timed, AnonymizeOpts, AnonymizedMessage, FailKind, Failure, Route,diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 935a2dbe8707..f09510b0b204 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -34,7 +34,6 @@ use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META, TYPE_PLUGIN,};-use crate::images::ImagePolicy;use crate::json::{as_array, as_f64, as_object, as_small_uint, as_str, parse_untrusted,parse_untrusted_with_buffers, reject_if_too_deep,@@ -236,17 +235,11 @@ pub struct AnonymizeOpts {/// ([`crate::bytewalk`]) instead of a simd-json tree; anything the walk can't prove safe falls/// back to the parse per event. The differential tests pin both engines by toggling this.pub byte_walk: bool,- /// How images are scrubbed: inline on the walk thread, or deferred onto the shared worker- /// pool with a token-patch pass over the serialized output. The differential tests pin both.- pub image_policy: ImagePolicy,}impl Default for AnonymizeOpts {fn default() -> Self {- Self {- byte_walk: true,- image_policy: ImagePolicy::Inline,- }+ Self { byte_walk: true }}}@@ -549,8 +542,8 @@ fn anonymize_snapshot_data_inner(// No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines// past its limit, and every recursive parse below is preceded by a span-local// reject_if_too_deep — so the common all-walked path never pays a depth scan at all.- let mut ctx = Ctx::with_options(allow, timings, opts.image_policy, image_collection)- .collecting_urls(url_collection);+ let mut ctx =+ Ctx::with_options(allow, timings, image_collection).collecting_urls(url_collection);let counts = ctx.count_checkpoint();let mut msg = match stream_message(&ctx, distinct_id, inner, opts)? {Some(msg) => msg,@@ -988,16 +981,6 @@ fn finish(lines.extend_from_slice(&sink.lines[sink.line_starts[i]..body_end]);lines.extend_from_slice(b"]\n");}- // Deferred image jobs resolve here: the block lines are the last surface tokens can be on.- let lines = ctx.patch_pending_images(lines);- // Nothing downstream can fix a token that gets past this point, and a shipped one is an image- // no reader can ever recover (the marker is random per process). Fail closed instead.- if crate::images::contains_token(&lines) {- return Err(Failure::new(- FailKind::AnonymizeFailed,- "internal: unresolved image token in anonymized output",- ));- }Ok(AnonymizedMessage {lines,route,diff --git a/rust/replay-anonymizer/src/timings.rs b/rust/replay-anonymizer/src/timings.rsindex 6c5eb441bd8d..d9854f8fc96d 100644--- a/rust/replay-anonymizer/src/timings.rs+++ b/rust/replay-anonymizer/src/timings.rs@@ -1,5 +1,5 @@//! Phase-timing sink for the snapshot pipeline: contiguous phase boundaries plus accumulated-//! in-scrub op totals (cv de/recompression, image blur), all as nanosecond offsets from one+//! in-scrub op totals (cv de/recompression), all as nanosecond offsets from one//! monotonic origin captured when the sink is created.//!//! `Cell`-based so the caller can own it outside a `catch_unwind` boundary: whatever completed@@ -21,8 +21,6 @@ pub struct PhaseTimings {scrub_end_ns: Cell<u64>,cv_total_ns: Cell<u64>,cv_count: Cell<u32>,- blur_total_ns: Cell<u64>,- blur_count: Cell<u32>,last_op: Cell<&'static str>,}@@ -37,8 +35,6 @@ pub struct PhaseTimingsSnapshot {pub scrub_end_ns: Option<u64>,pub cv_total_ns: u64,pub cv_count: u32,- pub blur_total_ns: u64,- pub blur_count: u32,pub last_op: &'static str,}@@ -54,8 +50,6 @@ impl PhaseTimings {scrub_end_ns: Cell::new(UNSET),cv_total_ns: Cell::new(0),cv_count: Cell::new(0),- blur_total_ns: Cell::new(0),- blur_count: Cell::new(0),last_op: Cell::new("queued"),}}@@ -91,21 +85,10 @@ impl PhaseTimings {self.last_op.set(op);}- /// Fold in blur work measured elsewhere (the parallel image workers time their own jobs).- pub fn add_blur(&self, elapsed_ns: u64, count: u32) {- self.blur_total_ns- .set(self.blur_total_ns.get().saturating_add(elapsed_ns));- self.blur_count- .set(self.blur_count.get().saturating_add(count));- }-- /// Times one in-scrub op into the `cv` or `blur` totals. Restores the `"scrub"` marker only on+ /// Times one in-scrub op into the `cv` totals. Restores the `"scrub"` marker only on/// clean exit, so after a panic `last_op` names the op that died.pub(crate) fn time_op<T>(&self, op: &'static str, f: impl FnOnce() -> T) -> T {- let (total, count) = match op {- "cv" => (&self.cv_total_ns, &self.cv_count),- _ => (&self.blur_total_ns, &self.blur_count),- };+ let (total, count) = (&self.cv_total_ns, &self.cv_count);self.last_op.set(op);let start = Instant::now();let out = f();@@ -126,8 +109,6 @@ impl PhaseTimings {scrub_end_ns: opt(&self.scrub_end_ns),cv_total_ns: self.cv_total_ns.get(),cv_count: self.cv_count.get(),- blur_total_ns: self.blur_total_ns.get(),- blur_count: self.blur_count.get(),last_op: self.last_op.get(),}}@@ -146,16 +127,14 @@ mod tests {t.decompress_finished();t.scrub_started();t.time_op("cv", || {});- t.time_op("blur", || {});- t.time_op("blur", || {});+ t.time_op("cv", || {});t.scrub_finished();let snap = t.snapshot();assert!(snap.task_start_ns.unwrap() <= snap.decompress_start_ns.unwrap());assert!(snap.decompress_start_ns.unwrap() <= snap.decompress_end_ns.unwrap());assert!(snap.scrub_start_ns.unwrap() <= snap.scrub_end_ns.unwrap());- assert_eq!(snap.cv_count, 1);- assert_eq!(snap.blur_count, 2);+ assert_eq!(snap.cv_count, 2);assert_eq!(snap.last_op, "scrub");}@@ -169,7 +148,7 @@ mod tests {t.time_op("cv", || {});let result = contain_unwind(|| -> Result<(), String> {- t.time_op("blur", || panic!("image decode exploded"));+ t.time_op("cv", || panic!("cv decode exploded"));Ok(())},|m| m,@@ -181,6 +160,6 @@ mod tests {assert!(snap.scrub_start_ns.is_some());assert_eq!(snap.scrub_end_ns, None);assert_eq!(snap.cv_count, 1);- assert_eq!(snap.last_op, "blur");+ assert_eq!(snap.last_op, "cv");}}diff --git a/rust/replay-anonymizer/tests/bench_images.rs b/rust/replay-anonymizer/tests/bench_images.rsdeleted file mode 100644index abefd676d07e..000000000000--- a/rust/replay-anonymizer/tests/bench_images.rs+++ /dev/null@@ -1,137 +0,0 @@-//! Manual benchmark for inline vs deferred-parallel image scrubbing. Ignored in CI (timing is-//! machine-dependent); run with:-//!-//! ```sh-//! cargo test --release -p posthog-replay-anonymizer --test bench_images -- --ignored --nocapture-//! ```--use std::time::Instant;--use base64::Engine;-use posthog_replay_anonymizer::snapshot::{anonymize_kafka_payload_opts, AnonymizeOpts};-use posthog_replay_anonymizer::{AllowLists, ImagePolicy};-use serde_json::json;--fn image_data_uri(side: u32, seed: u8, format: image::ImageFormat) -> String {- let mut img = image::RgbaImage::new(side, side);- for (x, y, px) in img.enumerate_pixels_mut() {- *px = image::Rgba([- (x as u8).wrapping_mul(seed),- (y as u8).wrapping_add(seed),- seed,- 255,- ]);- }- let img = if format == image::ImageFormat::Jpeg {- // JPEG has no alpha channel.- image::DynamicImage::ImageRgb8(image::DynamicImage::ImageRgba8(img).to_rgb8())- } else {- image::DynamicImage::ImageRgba8(img)- };- let mut buf = Vec::new();- img.write_to(&mut std::io::Cursor::new(&mut buf), format)- .unwrap();- let mime = if format == image::ImageFormat::Jpeg {- "jpeg"- } else {- "png"- };- format!(- "data:image/{mime};base64,{}",- base64::engine::general_purpose::STANDARD.encode(buf)- )-}--fn payload(images: usize, side: u32, duplicates: usize, format: image::ImageFormat) -> Vec<u8> {- let mut children = Vec::new();- for i in 0..images {- let uri = image_data_uri(side, (i + 1) as u8, format);- for d in 0..=duplicates {- children.push(json!({- "type": 2,- "id": 10 + children.len(),- "tagName": "img",- "attributes": { "src": uri, "alt": format!("img-{i}-{d}") },- "childNodes": [],- }));- }- }- let inner = json!({- "event": "$snapshot_items",- "properties": {- "$session_id": "bench-session",- "$window_id": "w",- "$snapshot_items": [{- "type": 2,- "timestamp": 1_700_000_000_000u64,- "data": {- "node": { "type": 0, "id": 1, "childNodes": children },- "initialOffset": { "top": 0, "left": 0 },- },- }],- },- });- serde_json::to_string(&json!({- "distinct_id": "d",- "data": inner.to_string(),- }))- .unwrap()- .into_bytes()-}--fn run(allow: &AllowLists, payload: &[u8], policy: ImagePolicy, iters: usize) -> Vec<u128> {- let mut samples = Vec::with_capacity(iters);- for _ in 0..iters {- let mut bytes = payload.to_vec();- let start = Instant::now();- let out = anonymize_kafka_payload_opts(- allow,- &mut bytes,- AnonymizeOpts {- image_policy: policy,- ..Default::default()- },- None,- )- .expect("bench payload must anonymize");- samples.push(start.elapsed().as_micros());- assert!(!out.lines.is_empty());- }- samples.sort_unstable();- samples-}--#[test]-#[ignore = "manual benchmark; run in release with --nocapture"]-fn bench_inline_vs_parallel_images() {- let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());- println!(- "image workers: REPLAY_ANONYMIZER_IMAGE_THREADS={}",- std::env::var("REPLAY_ANONYMIZER_IMAGE_THREADS").unwrap_or_else(|_| "(default)".into())- );- for (images, side, duplicates, format) in [- (4usize, 256u32, 0usize, image::ImageFormat::Png),- (16, 256, 0, image::ImageFormat::Png),- (16, 512, 0, image::ImageFormat::Png),- (16, 256, 3, image::ImageFormat::Png),- (4, 512, 0, image::ImageFormat::Jpeg),- (16, 1024, 0, image::ImageFormat::Jpeg),- (4, 2048, 0, image::ImageFormat::Jpeg),- ] {- let payload = payload(images, side, duplicates, format);- // Warm both paths (decoder init, worker pool spawn) before sampling.- run(&allow, &payload, ImagePolicy::Inline, 1);- run(&allow, &payload, ImagePolicy::Parallel, 1);- let inline = run(&allow, &payload, ImagePolicy::Inline, 7);- let parallel = run(&allow, &payload, ImagePolicy::Parallel, 7);- let median = |s: &Vec<u128>| s[s.len() / 2];- println!(- "{images:2} distinct {side}x{side} {format:?} x{} occurrences ({:6} KB payload): inline {:7}us parallel {:7}us ({:.2}x)",- duplicates + 1,- payload.len() / 1024,- median(&inline),- median(¶llel),- median(&inline) as f64 / median(¶llel) as f64,- );- }-}diff --git a/rust/replay-anonymizer/tests/fixtures/events.json b/rust/replay-anonymizer/tests/fixtures/events.jsonindex 8dfa0cd5e5c7..ebc2da89e3ca 100644--- a/rust/replay-anonymizer/tests/fixtures/events.json+++ b/rust/replay-anonymizer/tests/fixtures/events.json@@ -410,7 +410,7 @@{ "property": "clearRect", "args": [0, 0, 8, 8] },{"property": "drawImage",- "args": [{ "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png", "data": [{ "rr_type": "ArrayBuffer", "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" }] }] }, 0, 0]+ "args": [{ "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png", "data": [{ "rr_type": "ArrayBuffer", "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNgAAIAAAUAAen63NgAAAAASUVORK5CYII=" }] }] }, 0, 0]}]}diff --git a/rust/replay-anonymizer/tests/image_token_fuzz.rs b/rust/replay-anonymizer/tests/image_token_fuzz.rsdeleted file mode 100644index 3896ce793bc9..000000000000--- a/rust/replay-anonymizer/tests/image_token_fuzz.rs+++ /dev/null@@ -1,252 +0,0 @@-//! Randomized hunt for the deferred-image token leak.-//!-//! Sweeps the axes the hand-written invariant test does not: the gzip wire format the SDK actually-//! sends (not just the anonymizer's own zstd re-emit), images too large for the collection lane,-//! several image-bearing events sharing one message (and so one `ImageQueue`), canvas blobs, and-//! repeated URIs that dedup to a single job.--use base64::Engine;-use posthog_replay_anonymizer::{- anonymize_kafka_payload_opts, compression, AllowLists, AnonymizeOpts, ImageCollection,- ImagePolicy,-};-use serde_json::{json, Value};--const TS0: f64 = 1_700_000_000_000.0;--struct Rng(u64);--impl Rng {- fn next(&mut self) -> u64 {- self.0 ^= self.0 << 13;- self.0 ^= self.0 >> 7;- self.0 ^= self.0 << 17;- self.0- }- fn below(&mut self, n: u64) -> u64 {- self.next() % n- }- fn chance(&mut self, one_in: u64) -> bool {- self.below(one_in) == 0- }-}--fn tokens_in(bytes: &[u8]) -> Vec<String> {- let text = String::from_utf8_lossy(bytes);- let mut found = Vec::new();- for (i, _) in text.match_indices("xph") {- let tail: String = text[i..].chars().take(44).collect();- if tail.len() == 44- && tail[3..43].chars().all(|c| c.is_ascii_hexdigit())- && matches!(tail.as_bytes()[43], b'b' | b'p')- {- found.push(tail);- }- }- found-}--/// Tokens anywhere in the output, including inside compressed cv payloads — a token sealed into a-/// zstd frame does not appear verbatim, so the payloads have to be decompressed before scanning.-fn leaked_tokens(lines: &[u8]) -> Vec<String> {- let mut found = tokens_in(lines);- for line in lines.split(|&b| b == b'\n') {- if line.is_empty() {- continue;- }- let Ok(parsed) = serde_json::from_slice::<Value>(line) else {- continue;- };- let event = parsed.get(1).unwrap_or(&parsed);- let Some(data) = event.get("data") else {- continue;- };- let mut payloads: Vec<&str> = Vec::new();- if let Some(s) = data.as_str() {- payloads.push(s);- } else if let Some(obj) = data.as_object() {- payloads.extend(obj.values().filter_map(|v| v.as_str()));- }- for payload in payloads {- let raw: Vec<u8> = payload.chars().map(|c| c as u32 as u8).collect();- if let Ok(plain) = compression::decompress_by_magic(&raw) {- found.extend(tokens_in(&plain));- }- }- }- 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 `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]);- }- let mut buf = Vec::new();- image::DynamicImage::ImageRgba8(img)- .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)- .expect("png encode");- format!(- "data:image/png;base64,{}",- base64::engine::general_purpose::STANDARD.encode(&buf)- )-}--fn svg_uri(seed: u8) -> String {- let svg = format!("<svg xmlns='http://www.w3.org/2000/svg'><text>t{seed}</text></svg>");- format!(- "data:image/svg+xml;base64,{}",- base64::engine::general_purpose::STANDARD.encode(svg)- )-}--/// The image shapes that can reach the deferred path, by whether the collection lane takes them.-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 `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),- // Decodes as base64 but is not an image.- _ => "data:image/png;base64,bm90IGFuIGltYWdl".to_string(),- }-}--fn cv_wire(rng: &mut Rng, value: &Value) -> String {- let json = value.to_string();- let raw = if rng.chance(2) {- // What the SDK actually sends.- compression::gzip(json.as_bytes()).expect("gzip")- } else {- compression::compress_cv(json.as_bytes()).expect("zstd")- };- raw.iter().map(|&b| b as char).collect()-}--fn img_node(id: u64, src: &str) -> Value {- json!({- "parentId": 1, "nextId": null,- "node": { "type": 2, "tagName": "img", "id": id,- "attributes": { "src": src }, "childNodes": [] }- })-}--fn make_event(rng: &mut Rng, small: &[String], large: &[String], ts: f64) -> Value {- let n = 1 + rng.below(4);- let adds: Vec<Value> = (0..n)- .map(|i| img_node(100 + i, &image_uri(rng, small, large)))- .collect();-- match rng.below(5) {- 0 => json!({ "type": 3, "timestamp": ts, "data": { "source": 0, "adds": adds } }),- 1 => {- let attr_src = image_uri(rng, small, large);- let attrs = json!([{ "id": 42, "attributes": { "src": attr_src } }]);- json!({ "type": 3, "timestamp": ts, "cv": "2024-10", "data": {- "source": 0,- "adds": cv_wire(rng, &json!(adds)),- "texts": cv_wire(rng, &json!([{ "id": 3, "value": "hello" }])),- "attributes": cv_wire(rng, &attrs),- "removes": cv_wire(rng, &json!([{ "parentId": 1, "id": 9 }])),- }})- }- 2 => {- let node = json!({ "node": { "type": 0, "id": 1, "childNodes": adds.iter()- .map(|a| a["node"].clone()).collect::<Vec<_>>() },- "initialOffset": { "top": 0, "left": 0 } });- json!({ "type": 2, "timestamp": ts, "cv": "2024-10", "data": cv_wire(rng, &node) })- }- 3 => json!({ "type": 2, "timestamp": ts, "data": { "node": { "type": 0, "id": 1,- "childNodes": adds.iter().map(|a| a["node"].clone()).collect::<Vec<_>>() },- "initialOffset": { "top": 0, "left": 0 } } }),- // Canvas snapshot frame: the other `scrub_image` caller, with the Blank fallback.- _ => json!({ "type": 3, "timestamp": ts, "data": { "source": 9, "id": 5, "type": 0,- "commands": [- { "property": "clearRect", "args": [0, 0, 8, 8] },- { "property": "drawImage", "args": [{- "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png",- "data": [{ "rr_type": "ArrayBuffer", "base64":- image_uri(rng, small, large).split(',').nth(1).unwrap_or("").to_string() }] }] },- 0, 0, 8, 8] }] } }),- }-}--#[test]-fn 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();- 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();- let mut messages = 0usize;-- for round in 0..240 {- let events: Vec<Value> = (0..(1 + rng.below(4)))- .map(|i| make_event(&mut rng, &small, &large, TS0 + i as f64 * 100.0))- .collect();- let message = json!({- "event": "$snapshot_items",- "properties": { "$session_id": "s", "$window_id": "w", "$snapshot_items": events },- });- let payload = serde_json::to_string(&json!({- "distinct_id": "d",- "data": serde_json::to_string(&message).unwrap(),- }))- .unwrap();-- let collect = rng.chance(2);- let byte_walk = rng.chance(2);- let mut bytes = payload.into_bytes();- let out = anonymize_kafka_payload_opts(- &allow,- &mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Parallel,- },- collect.then(|| ImageCollection {- max_image_bytes: FUZZ_MAX_IMAGE_BYTES,- ..ImageCollection::new(- "a".repeat(32),- "0123456789abcdef0123456789abcdef".to_string(),- )- }),- );- messages += 1;- let Ok(msg) = out else { continue };- let tokens = leaked_tokens(&msg.lines);- if !tokens.is_empty() {- failures.push(format!(- "round {round} (collect={collect}, byte_walk={byte_walk}): {} token(s), e.g. {}",- tokens.len(),- tokens[0]- ));- }- }-- assert!(- failures.is_empty(),- "deferred-image tokens reached output in {}/{messages} messages:\n {}",- failures.len(),- failures.join("\n ")- );-}diff --git a/rust/replay-anonymizer/tests/image_token_leak.rs b/rust/replay-anonymizer/tests/image_token_leak.rsdeleted file mode 100644index 7d863421fb3e..000000000000--- a/rust/replay-anonymizer/tests/image_token_leak.rs+++ /dev/null@@ -1,275 +0,0 @@-//! No anonymizer output may ever carry a deferred-image token.-//!-//! `ImagePolicy::Parallel` substitutes an `xph<marker><id><fallback>` token for each image and-//! relies on `ImageQueue::patch` running wherever those bytes become immutable. A token that-//! reaches output is unrecoverable data loss: the marker is random per process, so nothing-//! downstream can resolve it back to an image, and the pixels are gone.-//!-//! The differential test in `snapshot.rs` compares Inline against Parallel, so it only catches a-//! leak in a shape its fixtures happen to cover. This asserts the invariant directly instead.--use base64::Engine;-use posthog_replay_anonymizer::{- anonymize_kafka_payload_opts, compression, AllowLists, AnonymizeOpts, ImageCollection,- ImagePolicy,-};-use serde_json::{json, Value};--const TS0: f64 = 1_700_000_000_000.0;--/// Any `xph` run shaped like a token, in a plain byte buffer.-fn tokens_in(bytes: &[u8]) -> Vec<String> {- let text = String::from_utf8_lossy(bytes);- let mut found = Vec::new();- for (i, _) in text.match_indices("xph") {- let tail: String = text[i..].chars().take(44).collect();- if tail.len() == 44- && tail[3..43].chars().all(|c| c.is_ascii_hexdigit())- && matches!(tail.as_bytes()[43], b'b' | b'p')- {- found.push(tail);- }- }- found-}--/// A latin-1 JSON string back to the bytes it carries (the cv wire encoding).-fn latin1_bytes(s: &str) -> Vec<u8> {- s.chars().map(|c| c as u32 as u8).collect()-}--/// Tokens anywhere in the output, **including inside compressed cv payloads**.-///-/// Scanning the raw lines is not enough and quietly misses the real bug: a token sealed into a-/// zstd frame does not appear verbatim (its repeated id digits fold into the frame's sequences),-/// so the payloads have to be decompressed before the scan.-fn leaked_tokens(lines: &[u8]) -> Vec<String> {- let mut found = tokens_in(lines);- for line in lines.split(|&b| b == b'\n') {- if line.is_empty() {- continue;- }- let Ok(parsed) = serde_json::from_slice::<Value>(line) else {- continue;- };- let event = parsed.get(1).unwrap_or(&parsed);- let Some(data) = event.get("data") else {- continue;- };- let mut payloads: Vec<&str> = Vec::new();- if let Some(s) = data.as_str() {- payloads.push(s);- } else if let Some(obj) = data.as_object() {- payloads.extend(obj.values().filter_map(|v| v.as_str()));- }- for payload in payloads {- let raw = latin1_bytes(payload);- if let Ok(plain) = compression::decompress_by_magic(&raw) {- found.extend(tokens_in(&plain));- }- }- }- found-}--fn png_data_uri() -> String {- let png = base64::engine::general_purpose::STANDARD- .decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",- )- .unwrap();- format!(- "data:image/png;base64,{}",- base64::engine::general_purpose::STANDARD.encode(&png)- )-}--/// An SVG data URI is deliberately not collectable (a text format's PII has to be scrubbed in-/// place), so with collection on it is the shape that still takes the deferred-token route.-fn svg_data_uri() -> String {- let svg = "<svg xmlns='http://www.w3.org/2000/svg'><text>hello</text></svg>";- format!(- "data:image/svg+xml;base64,{}",- base64::engine::general_purpose::STANDARD.encode(svg)- )-}--fn collection() -> ImageCollection {- ImageCollection::new(- "a".repeat(32),- "0123456789abcdef0123456789abcdef".to_string(),- )-}--fn snapshot_message(items: serde_json::Value) -> serde_json::Value {- json!({- "event": "$snapshot_items",- "properties": { "$session_id": "s", "$window_id": "w", "$snapshot_items": items },- })-}--fn run(inner: &serde_json::Value, collect: bool, byte_walk: bool) -> Vec<u8> {- let allow = AllowLists::default();- let payload = serde_json::to_string(&json!({- "distinct_id": "d",- "data": serde_json::to_string(inner).unwrap(),- }))- .unwrap();- let mut bytes = payload.into_bytes();- anonymize_kafka_payload_opts(- &allow,- &mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Parallel,- },- collect.then(collection),- )- .expect("anonymize should succeed")- .lines-}--/// A `cv` payload as the SDK sends it: the sub-value compressed and carried as a latin-1 string.-fn cv_string(value: &serde_json::Value) -> String {- let compressed = compression::compress_cv(value.to_string().as_bytes()).unwrap();- compressed.iter().map(|&b| b as char).collect()-}--fn img_add(src: &str) -> serde_json::Value {- json!([{- "parentId": 1,- "nextId": null,- "node": {- "type": 2, "tagName": "img", "id": 42,- "attributes": { "src": src },- "childNodes": []- }- }])-}--fn cases(src: &str, label: &str) -> Vec<(String, serde_json::Value)> {- vec![- (- format!("{label}: plain mutation add"),- snapshot_message(json!([- { "type": 3, "timestamp": TS0, "data": { "source": 0, "adds": img_add(src) } }- ])),- ),- (- format!("{label}: cv mutation add"),- snapshot_message(json!([- { "type": 3, "timestamp": TS0, "cv": "2024-10",- "data": { "source": 0, "adds": cv_string(&img_add(src)) } }- ])),- ),- (- format!("{label}: cv mutation attributes"),- snapshot_message(json!([- { "type": 3, "timestamp": TS0, "cv": "2024-10",- "data": { "source": 0,- "attributes": cv_string(&json!([{ "id": 42, "attributes": { "src": src } }])) } }- ])),- ),- (- format!("{label}: plain full snapshot"),- snapshot_message(json!([- { "type": 2, "timestamp": TS0, "data": { "node": {- "type": 0, "id": 1, "childNodes": [{- "type": 2, "tagName": "img", "id": 42,- "attributes": { "src": src }, "childNodes": [] }] },- "initialOffset": { "top": 0, "left": 0 } } }- ])),- ),- (- format!("{label}: cv full snapshot"),- snapshot_message(json!([- { "type": 2, "timestamp": TS0, "cv": "2024-10",- "data": cv_string(&json!({ "node": {- "type": 0, "id": 1, "childNodes": [{- "type": 2, "tagName": "img", "id": 42,- "attributes": { "src": src }, "childNodes": [] }] },- "initialOffset": { "top": 0, "left": 0 } })) }- ])),- ),- ]-}--/// A distinct 1x1 PNG per index, so each one is its own job rather than a dedup hit.-fn distinct_png_data_uri(i: usize) -> String {- let mut png = base64::engine::general_purpose::STANDARD- .decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",- )- .unwrap();- // Perturb the trailing bytes: still a distinct payload, still decodes as a PNG header.- let n = png.len();- png[n - 5] = (i % 251) as u8;- png[n - 6] = ((i / 251) % 251) as u8;- format!(- "data:image/png;base64,{}",- base64::engine::general_purpose::STANDARD.encode(&png)- )-}--/// The production shape: one `cv` mutation whose `adds` carries many distinct images.-#[test]-fn no_token_leaks_from_a_cv_mutation_full_of_images() {- for count in [8usize, 40, 120] {- for collect in [true, false] {- for byte_walk in [true, false] {- let adds: Vec<serde_json::Value> = (0..count)- .map(|i| {- json!({- "parentId": 1, "nextId": null,- "node": {- "type": 2, "tagName": "img", "id": 100 + i,- "attributes": { "src": distinct_png_data_uri(i) },- "childNodes": []- }- })- })- .collect();- let inner = snapshot_message(json!([- { "type": 3, "timestamp": TS0, "cv": "2024-10",- "data": { "source": 0, "adds": cv_string(&json!(adds)) } }- ]));- let out = run(&inner, collect, byte_walk);- let tokens = leaked_tokens(&out);- assert!(- tokens.is_empty(),- "{} token(s) leaked from a {count}-image cv mutation \- (collect={collect}, byte_walk={byte_walk}), e.g. {}",- tokens.len(),- tokens[0]- );- }- }- }-}--#[test]-fn no_deferred_image_token_reaches_output() {- let mut failures = Vec::new();- for (src, kind) in [(png_data_uri(), "png"), (svg_data_uri(), "svg")] {- for (label, inner) in cases(&src, kind) {- for collect in [true, false] {- for byte_walk in [true, false] {- let out = run(&inner, collect, byte_walk);- let tokens = leaked_tokens(&out);- if !tokens.is_empty() {- failures.push(format!(- "{label} (collect={collect}, byte_walk={byte_walk}): {} token(s), e.g. {}",- tokens.len(),- tokens[0]- ));- }- }- }- }- }- assert!(- failures.is_empty(),- "deferred-image tokens reached output:\n {}",- failures.join("\n ")- );-}diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rsindex 36190e219b20..2bf56143dbea 100644--- a/rust/replay-anonymizer/tests/ref_idempotence.rs+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs@@ -13,7 +13,6 @@use posthog_replay_anonymizer::{anonymize_kafka_payload_opts, anonymize_line_with_ctx, AllowLists, AnonymizeOpts, Ctx,- ImagePolicy,};use serde_json::{json, Value};@@ -92,10 +91,7 @@ fn scrub_ingestion(line: &Value, byte_walk: bool) -> String {let out = anonymize_kafka_payload_opts(&AllowLists::default(),&mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Parallel,- },+ AnonymizeOpts { byte_walk },None,).expect("anonymize should succeed");diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex 2fe14048ab5d..6619fd8eebee 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -13,7 +13,7 @@ use posthog_replay_anonymizer::snapshot::{AnonymizedMessage, FailKind, Failure, FLAG_ACTIVE, FLAG_CLICK, FLAG_KEYPRESS,FLAG_MOUSE_ACTIVITY,};-use posthog_replay_anonymizer::{Ctx, ImageCollection, ImagePolicy};+use posthog_replay_anonymizer::{Ctx, ImageCollection};use serde_json::{json, Value};use std::path::Path;@@ -452,45 +452,33 @@ fn assert_stream_matches_tree(allow: &AllowLists, inner_json: &str, label: &str)let ctx = Ctx::new(allow);let tree = anonymize_via_tree(&ctx, "d", inner_json.as_bytes());- // Every engine combination is pinned against the tree reference: the parse-free byte walk- // (with its per-event fallbacks) vs the simd path, and inline vs deferred-parallel images.+ // Both engines are pinned against the tree reference: the parse-free byte walk (with its+ // per-event fallbacks) vs the simd path.for byte_walk in [true, false] {- for image_policy in [ImagePolicy::Inline, ImagePolicy::Parallel] {- let mut bytes = payload.as_bytes().to_vec();- let stream = anonymize_kafka_payload_opts(- allow,- &mut bytes,- AnonymizeOpts {- byte_walk,- image_policy,- },- None,- );- match (&stream, &tree) {- (Ok(s), Ok(t)) => {- let s_lines = parse_lines(&s.lines);- let t_lines = parse_lines(&t.lines);- assert_eq!(- s_lines, t_lines,- "lines diverged (walk={byte_walk}, images={image_policy:?}): {label}"- );- assert_eq!(- s.meta, t.meta,- "meta diverged (walk={byte_walk}, images={image_policy:?}): {label}"- );- }- (Err(s), Err(t)) => {- assert_eq!(- s.kind, t.kind,- "failure kind diverged (walk={byte_walk}, images={image_policy:?}): {label}"- );- }- (s, t) => panic!(- "outcome diverged (walk={byte_walk}, images={image_policy:?}) for {label}: stream={:?} tree={:?}",- s.as_ref().map(|m| parse_lines(&m.lines)),- t.as_ref().map(|m| parse_lines(&m.lines)),- ),+ let mut bytes = payload.as_bytes().to_vec();+ let stream =+ anonymize_kafka_payload_opts(allow, &mut bytes, AnonymizeOpts { byte_walk }, None);+ match (&stream, &tree) {+ (Ok(s), Ok(t)) => {+ let s_lines = parse_lines(&s.lines);+ let t_lines = parse_lines(&t.lines);+ assert_eq!(+ s_lines, t_lines,+ "lines diverged (walk={byte_walk}): {label}"+ );+ assert_eq!(s.meta, t.meta, "meta diverged (walk={byte_walk}): {label}");+ }+ (Err(s), Err(t)) => {+ assert_eq!(+ s.kind, t.kind,+ "failure kind diverged (walk={byte_walk}): {label}"+ );}+ (s, t) => panic!(+ "outcome diverged (walk={byte_walk}) for {label}: stream={:?} tree={:?}",+ s.as_ref().map(|m| parse_lines(&m.lines)),+ t.as_ref().map(|m| parse_lines(&m.lines)),+ ),}}}@@ -618,7 +606,7 @@ fn differential_stream_vs_tree() {fn stylesheet_data_images_are_neutralized_and_engines_agree() {// CSS reaches the anonymizer as an inlined `<link>` `_cssText` attribute and as the incremental// stylesheet events (StyleSheetRule/StyleDeclaration/AdoptedStyleSheet); a data-image in any of- // them must be blurred like a `style` attribute, and the byte walk must match the tree on these+ // them must be scrubbed like a `style` attribute, and the byte walk must match the tree on these// arms (the shared fixture corpus carries no CSS cases, so the differential alone never hits them).const ONE_PX: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg==";let css = format!(".a{{background:url({ONE_PX})}}");@@ -910,10 +898,7 @@ fn both_engines_count_and_collect_an_image_once_or_not_at_all() {let out = anonymize_kafka_payload_opts(&allow,&mut bytes,- AnonymizeOpts {- byte_walk,- ..Default::default()- },+ AnonymizeOpts { byte_walk },Some(ImageCollection::new("42".to_string(),"fedcba9876543210fedcba9876543210".to_string(),@@ -948,70 +933,63 @@ fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {.unwrap();let expected_ref = image_ref(&team_id, &hash_image_bytes(content_key.as_bytes(), &png));- // Both image policies: collection must take precedence over the parallel worker pool — a- // collected image needs no blur, so it must come back as a ref, never a pool token.for byte_walk in [true, false] {- for image_policy in [ImagePolicy::Inline, ImagePolicy::Parallel] {- let mut bytes = collect_payload().into_bytes();- let out = anonymize_kafka_payload_opts(- &allow,- &mut bytes,- AnonymizeOpts {- byte_walk,- image_policy,- },- Some(ImageCollection::new(team_id.clone(), content_key.clone())),- )- .expect("anonymizes (walk={byte_walk})");+ let mut bytes = collect_payload().into_bytes();+ let out = anonymize_kafka_payload_opts(+ &allow,+ &mut bytes,+ AnonymizeOpts { byte_walk },+ Some(ImageCollection::new(team_id.clone(), content_key.clone())),+ )+ .expect("anonymizes (walk={byte_walk})");- let lines = String::from_utf8(out.lines.clone()).unwrap();- assert!(- !lines.contains(COLLECT_PNG_B64),- "original image must not pass through (walk={byte_walk} images={image_policy:?})"- );- assert_eq!(- lines.matches(&expected_ref).count(),- 4,- "img src, rr_dataURL, css background, and canvas blob all carry the ref (walk={byte_walk} images={image_policy:?}): {lines}"+ let lines = String::from_utf8(out.lines.clone()).unwrap();+ assert!(+ !lines.contains(COLLECT_PNG_B64),+ "original image must not pass through (walk={byte_walk})");+ assert_eq!(+ lines.matches(&expected_ref).count(),+ 4,+ "img src, rr_dataURL, css background, and canvas blob all carry the ref (walk={byte_walk}): {lines}"+ );- // One image (deduped across all four funnels), bytes returned verbatim.- assert_eq!(out.meta.images.len(), 1, "walk={byte_walk}");- let entry = &out.meta.images[0];- assert_eq!(entry.hash, hash_image_bytes(content_key.as_bytes(), &png));- assert_eq!(entry.offset, 0);- assert_eq!(entry.len, png.len());- assert_eq!(out.image_bytes, png, "walk={byte_walk}");- assert_eq!(- out.meta.image_sources,- vec![- ImageSourceCount {- source: "css",- property: "background",- kind: "inline",- count: 1,- },- ImageSourceCount {- source: "html",- property: "rr_dataURL",- kind: "inline",- count: 1,- },- ImageSourceCount {- source: "html",- property: "src",- kind: "inline",- count: 1,- },- ],- "walk={byte_walk} images={image_policy:?}"- );- }+ // One image (deduped across all four funnels), bytes returned verbatim.+ assert_eq!(out.meta.images.len(), 1, "walk={byte_walk}");+ let entry = &out.meta.images[0];+ assert_eq!(entry.hash, hash_image_bytes(content_key.as_bytes(), &png));+ assert_eq!(entry.offset, 0);+ assert_eq!(entry.len, png.len());+ assert_eq!(out.image_bytes, png, "walk={byte_walk}");+ assert_eq!(+ out.meta.image_sources,+ vec![+ ImageSourceCount {+ source: "css",+ property: "background",+ kind: "inline",+ count: 1,+ },+ ImageSourceCount {+ source: "html",+ property: "rr_dataURL",+ kind: "inline",+ count: 1,+ },+ ImageSourceCount {+ source: "html",+ property: "src",+ kind: "inline",+ count: 1,+ },+ ],+ "walk={byte_walk}"+ );}}#[test]-fn image_collection_off_blurs_inline_and_returns_no_bytes() {+fn image_collection_off_blanks_images_and_returns_no_bytes() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());let mut bytes = collect_payload().into_bytes();let out = anonymize_kafka_payload_opts(&allow, &mut bytes, AnonymizeOpts::default(), None)@@ -1024,10 +1002,21 @@ fn image_collection_off_blurs_inline_and_returns_no_bytes() {assert!(!lines.contains("image:"), "no refs without collection");assert!(out.meta.images.is_empty());assert!(out.image_bytes.is_empty());+ let drops: Vec<_> = out+ .meta+ .scrub_drops+ .iter()+ .map(|d| (d.reason, d.count))+ .collect();+ assert_eq!(+ drops,+ vec![("image_collection_off", 4)],+ "img, rr_dataURL, css and canvas"+ );}#[test]-fn image_collection_svg_stays_on_the_inline_scrub_path() {+fn image_collection_blanks_svg() {// SVG is text — PII inside it must not ride to the scrub topic as an "image".let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());use base64::Engine;@@ -1059,4 +1048,11 @@ fn image_collection_svg_stays_on_the_inline_scrub_path() {assert!(out.meta.images.is_empty(), "svg must not be collected");assert!(out.meta.image_sources.is_empty());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)]);}diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex 7fab9aedfcc5..c30325f1062f 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -6,7 +6,7 @@//! copy is still stashed alongside.use posthog_replay_anonymizer::{- anonymize_kafka_payload_collecting, AllowLists, AnonymizeOpts, ImagePolicy, UrlCollection,+ anonymize_kafka_payload_collecting, AllowLists, AnonymizeOpts, UrlCollection,};use serde_json::{json, Value};@@ -46,10 +46,7 @@ fn collect_urls_of(tag: &str, attrs: Value) -> Vec<String> {let msg = anonymize_kafka_payload_collecting(&allow,&mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Inline,- },+ AnonymizeOpts { byte_walk },None,None,Some(UrlCollection {@@ -159,10 +156,7 @@ fn picture_source_srcset_is_collected_when_its_parent_is_known() {let message = anonymize_kafka_payload_collecting(&AllowLists::default(),&mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Inline,- },+ AnonymizeOpts { byte_walk },None,None,Some(UrlCollection {@@ -218,10 +212,7 @@ fn run(attrs: Value, collect: bool) -> Vec<(String, Value)> {let msg = anonymize_kafka_payload_collecting(&allow,&mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Inline,- },+ AnonymizeOpts { byte_walk },None,None,collection,@@ -397,10 +388,7 @@ fn an_escaped_or_repeated_dimension_key_still_declines_a_hidden_pixel() {let message = anonymize_kafka_payload_collecting(&AllowLists::default(),&mut bytes,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Inline,- },+ AnonymizeOpts { byte_walk },None,None,Some(UrlCollection {@@ -661,10 +649,7 @@ fn monthly_refs_survive_compressed_snapshot_fields() {let output = anonymize_kafka_payload_collecting(&AllowLists::default(),&mut payload,- AnonymizeOpts {- byte_walk,- image_policy: ImagePolicy::Inline,- },+ AnonymizeOpts { byte_walk },None,Some(ImageCollection::new(namespace.to_string(),