: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
fix(replay): never let a deferred-image token reach anonymizer output (#73862)
Robbie098a1462a023
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 927a8dc09e59..f2b30927ee05 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8213,7 +8213,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.0"+version = "0.4.1"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex ea05dee2ff5a..401f5e78fe37 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.4.0"+version = "0.4.1"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rsindex ef39bb52b76c..b8dd6984bb2c 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -7,6 +7,7 @@ use std::borrow::Cow;use simd_json::borrowed::{Object, Value};use crate::blur::is_image_data_uri;+use crate::collect::is_image_ref_strict;use crate::context::Ctx;use crate::images::ImageFallback;use crate::json::{as_str, string_value};@@ -58,6 +59,14 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {continue;};+ // A content ref from an earlier pass over already-mirrored output: opaque, carrying no+ // content of its own, with its bytes scrubbed out of band. Re-scrubbing would redact it+ // into the placeholder and strand that image beyond recovery, so a caller re-scrubbing+ // mirrored output opts into keeping it. Gated on the caller's own assertion of+ // provenance, never on the shape alone — the format is forgeable by a captured page.+ if ctx.keeps_image_refs() && is_image_ref_strict(&existing) {+ continue;+ }acted = true;if is_image_data_uri(&existing) {let blurred = ctx.scrub_image(&existing, ImageFallback::Placeholder);diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex f6e1ebc64336..851b87699120 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -15,6 +15,7 @@use crate::assets::{is_media_src_attr, 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::Ctx;use crate::css;use crate::dom::{@@ -231,7 +232,9 @@ fn scrub_cv_snapshot_value(return Some(false);}let content = if changed { &walked } else { &decompressed };- let zs = crate::compression::compress_cv(content).ok()?;+ // 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()?;write_latin1_json_string(&zs, out);Some(true)}@@ -895,6 +898,11 @@ impl<'c, 'a> Walker<'c, 'a> {}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+ // fully well-formed ref.+ if self.ctx.keeps_image_refs() && is_image_ref_strict(&existing) {+ return self.copy_value(vstart, out);+ }if is_image_data_uri(&existing) {let blurred = self.ctx.scrub_image(&existing, ImageFallback::Placeholder);scan::write_json_string(&blurred, out);@@ -995,7 +1003,8 @@ impl<'c, 'a> Walker<'c, 'a> {return Some(send);}let content = if changed { &walked } else { &decompressed };- let zs = crate::compression::compress_cv(content).ok()?;+ // See `scrub_cv_snapshot_value`: the barrier, not the raw codec.+ let zs = crate::cv::compress_scrubbed(self.ctx, 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 cabf68b9dd8f..c5ef851875a4 100644--- a/rust/replay-anonymizer/src/canvas.rs+++ b/rust/replay-anonymizer/src/canvas.rs@@ -6,7 +6,7 @@ use base64::Engine;use simd_json::borrowed::{Object, Value};use crate::blur::{is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};-use crate::collect::{is_image_ref, normalize_collected_mime};+use crate::collect::{is_image_ref, is_image_ref_strict, normalize_collected_mime};use crate::context::Ctx;use crate::images::ImageFallback;use crate::json::{@@ -170,6 +170,13 @@ fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {Some(s) => s.to_string(),None => return false,};+ // A content ref left by an earlier pass. Reassembling it into `data:{mime};base64,image:...`+ // below 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`.+ if ctx.keeps_image_refs() && is_image_ref_strict(&base64) {+ return false;+ }let original = format!("data:{mime};base64,{base64}");// scrub_image never fails outward (fallbacks are baked in). The collection lane's ref// replaces the payload wholesale (it is the consumer's join key, not decodable bytes); thediff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rsindex ed1982097892..64a144601760 100644--- a/rust/replay-anonymizer/src/collect.rs+++ b/rust/replay-anonymizer/src/collect.rs@@ -36,10 +36,37 @@ pub fn image_ref(pseudo_team: &str, hash: &str) -> String {/// True for strings shaped like a content ref. The `image:` prefix cannot collide with a data URI,/// a URL (no scheme is registered as `image`), or base64 payloads (`:` is not in the alphabet).+///+/// Only sound on values this crate produced. To decide whether a value *read back out of a payload*+/// may skip scrubbing, use [`is_image_ref_strict`]: capture input is attacker-controlled and this+/// prefix is trivial to forge.pub fn is_image_ref(s: &str) -> bool {s.starts_with("image:")}+/// True only for a fully well-formed ref: `image:` + 32 lowercase hex (the team pseudonym) + `:`+/// + 22 base64url chars (the truncated HMAC).+///+/// The loose prefix check would let a captured page set a media attribute to `image:<anything>` and+/// have it copied verbatim into anonymized output. This bounds what can survive to a fixed-width+/// opaque token with no room for readable content.+pub fn is_image_ref_strict(s: &str) -> bool {+ let Some(rest) = s.strip_prefix("image:") else {+ return false;+ };+ let Some((team, hash)) = rest.split_once(':') else {+ return false;+ };+ team.len() == 32+ && team+ .bytes()+ .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase() && b <= b'f')+ && hash.len() == 22+ && hash+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}+/// Per-image cap: a collected image must fit in one Kafka message on the scrub topic with headroom/// under the broker's 1 MB default. Bigger images stay on the inline blur path.pub const MAX_IMAGE_BYTES: usize = 900 * 1024;diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 65de575cb4d0..b846cfd6a35a 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -36,6 +36,9 @@ pub struct Ctx<'a> {images: ImageQueue,// `Some` routes collectable images to the scrub lane instead of the blur (inline or pooled).collector: Option<RefCell<ImageCollector>>,+ // Whether a well-formed ref already present in the *input* is left alone. Off unless the+ // caller vouches for the input's provenance; see `preserving_image_refs`.+ preserve_image_refs: bool,}impl<'a> Ctx<'a> {@@ -70,9 +73,28 @@ impl<'a> Ctx<'a> {image_policy,images: ImageQueue::default(),collector: image_collection.map(|c| RefCell::new(ImageCollector::new(c))),+ preserve_image_refs: false,}}+ /// Leave well-formed `image:<pseudo_team>:<hash>` refs already present in the input alone+ /// instead of scrubbing them.+ ///+ /// Off by default, and it must stay off for anything scrubbing untrusted capture input: the+ /// ref format is not a secret, so a page could set a media attribute to a forged one and have+ /// it copied into output unscrubbed. Enable it only where the input is known to be this+ /// anonymizer's own mirrored output being re-scrubbed — there a ref is a join key whose bytes+ /// were already scrubbed out of band, and re-scrubbing it destroys the only route back to them.+ pub fn preserving_image_refs(mut self) -> Self {+ self.preserve_image_refs = true;+ self+ }++ /// Whether an input-side ref may skip scrubbing (see [`Self::preserving_image_refs`]).+ pub(crate) fn keeps_image_refs(&self) -> bool {+ 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 replacesdiff --git a/rust/replay-anonymizer/src/cv.rs b/rust/replay-anonymizer/src/cv.rsindex b615df7fb279..f09dfc1ad79a 100644--- a/rust/replay-anonymizer/src/cv.rs+++ b/rust/replay-anonymizer/src/cv.rs@@ -11,6 +11,7 @@ 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@@ -49,9 +50,14 @@ fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<(Vec<u8>, bool)> {Ok((out, was_zstd))}-/// Compress a scrubbed cv payload, patching any deferred-image tokens first — after this the bytes-/// are opaque to the final patch pass over the block lines.-fn compress_bytes(ctx: &Ctx<'_>, json: &[u8]) -> Result<String> {+/// 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());@@ -59,9 +65,14 @@ fn compress_bytes(ctx: &Ctx<'_>, json: &[u8]) -> Result<String> {} else {json};- Ok(bytes_to_latin1(- &compression::compress_cv(json).context("compress cv payload")?,- ))+ if images::contains_token(json) {+ bail!("unresolved image token in a cv payload about to compress");+ }+ 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_value(ctx: &Ctx<'_>, value: &Value<'_>) -> Result<String> {diff --git a/rust/replay-anonymizer/src/images.rs b/rust/replay-anonymizer/src/images.rsindex 2292f2180f33..1ca167100ae7 100644--- a/rust/replay-anonymizer/src/images.rs+++ b/rust/replay-anonymizer/src/images.rs@@ -273,11 +273,12 @@ impl ImageQueue {continue;}};- if !self.jobs.borrow().contains_key(&id) {- // Marker collision with real payload bytes; astronomically unlikely — leave as-is.- 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 {@@ -286,7 +287,8 @@ impl ImageQueue {start};let span_end = start + token_len;- let replacement: String = match (self.resolve(id), fallback) {+ 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}")@@ -324,6 +326,18 @@ fn parse_hex_id(bytes: &[u8]) -> Option<u32> {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::*;@@ -423,4 +437,21 @@ mod tests {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/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 292a444729eb..cf13a20b79c2 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -870,6 +870,14 @@ fn finish(}// 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/tests/image_token_fuzz.rs b/rust/replay-anonymizer/tests/image_token_fuzz.rsnew file mode 100644index 000000000000..9aa7ed40f6c4--- /dev/null+++ b/rust/replay-anonymizer/tests/image_token_fuzz.rs@@ -0,0 +1,234 @@+//! 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+}++fn png_of(width: u32, height: u32, seed: u8) -> String {+ let mut img = image::RgbaImage::new(width, height);+ for (x, y, px) in img.enumerate_pixels_mut() {+ // Noise, so the encoder cannot collapse it — a large image has to stay large enough to+ // exceed the collection lane's per-image cap.+ 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 the collection lane's per-image cap, 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 blob: the other `scrub_image` caller, with the Blank fallback.+ _ => json!({ "type": 3, "timestamp": ts, "data": { "source": 9, "id": 5, "type": 0,+ "commands": [{ "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() }] }] }] }] } }),+ }+}++#[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();+ // Comfortably over the collection lane's 900 KB per-image cap.+ let large: Vec<String> = (0..2).map(|i| png_of(900, 900, i as u8 + 7)).collect();++ 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 {+ pseudo_team: "a".repeat(32),+ content_key: "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.rsnew file mode 100644index 000000000000..b17c5a035864--- /dev/null+++ b/rust/replay-anonymizer/tests/image_token_leak.rs@@ -0,0 +1,275 @@+//! 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 {+ pseudo_team: "a".repeat(32),+ content_key: "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.rsnew file mode 100644index 000000000000..bcafb703ac4d--- /dev/null+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs@@ -0,0 +1,203 @@+//! Re-scrubbing already-mirrored output must preserve its image content refs — but only when the+//! caller vouches for where that input came from.+//!+//! The mirror replaces each inlined image with an `image:<pseudo_team>:<hash>` ref and ships the+//! bytes out of band, so that ref is the only join key back to them. Scrubbing that output a second+//! time used to destroy the key: a canvas blob's ref was reassembled into a data URI that cannot+//! decode and failed safe to a blank pixel, and a ref in a media-source attribute took the+//! remote-URL branch and was redacted into the placeholder.+//!+//! The ref format is not a secret, though, so preserving anything `image:`-shaped found in a+//! payload would hand a captured page a way to copy arbitrary text into anonymized output. Two+//! things therefore have to hold, and both are pinned here: refs survive on a path the caller marks+//! trusted, and a forged one never survives on the ingestion path that sees untrusted capture data.++use posthog_replay_anonymizer::{+ anonymize_kafka_payload_opts, anonymize_line_with_ctx, AllowLists, AnonymizeOpts, Ctx,+ ImagePolicy,+};+use serde_json::{json, Value};++const TS0: f64 = 1_700_000_000_000.0;+const REF: &str = "image:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";++fn img_line(value: &str, attr: &str) -> Value {+ json!(["w", { "type": 3, "timestamp": TS0, "data": {+ "source": 0, "adds": [{ "parentId": 1, "nextId": null, "node": {+ "type": 2, "tagName": "img", "id": 42,+ "attributes": { attr: value }, "childNodes": [] } }] } }])+}++fn canvas_line(value: &str) -> Value {+ json!(["w", { "type": 3, "timestamp": TS0, "data": {+ "source": 9, "id": 5, "type": 0, "commands": [{+ "property": "drawImage",+ "args": [{ "rr_type": "ImageBitmap", "args": [{+ "rr_type": "Blob", "type": "image/png",+ "data": [{ "rr_type": "ArrayBuffer", "base64": value }] }] }] }] } }])+}++/// What a caller of the line API actually writes out: the rewritten line, or the input verbatim+/// when the scrub reports nothing changed (which is itself the idempotent outcome).+fn scrub_line(line: &Value, trusted: bool) -> String {+ let allow = AllowLists::default();+ let ctx = if trusted {+ Ctx::new(&allow).preserving_image_refs()+ } else {+ Ctx::new(&allow)+ };+ let original = line.to_string();+ let mut bytes = original.clone().into_bytes();+ anonymize_line_with_ctx(&ctx, &mut bytes)+ .expect("anonymize should succeed")+ .unwrap_or(original)+}++/// The offline re-scrub path (`prepare` and friends), which vouches for its input.+fn scrub_trusted(line: &Value) -> String {+ scrub_line(line, true)+}++/// The same path without the opt-in — what any caller gets by default.+fn scrub_default(line: &Value) -> String {+ scrub_line(line, false)+}++/// The production ingestion path, which sees untrusted capture input.+fn scrub_ingestion(line: &Value, byte_walk: bool) -> String {+ let inner = json!({+ "event": "$snapshot_items",+ "properties": { "$session_id": "s", "$window_id": "w", "$snapshot_items": [line[1]] },+ });+ let payload = serde_json::to_string(&json!({+ "distinct_id": "d",+ "data": serde_json::to_string(&inner).unwrap(),+ }))+ .unwrap();+ let mut bytes = payload.into_bytes();+ let out = anonymize_kafka_payload_opts(+ &AllowLists::default(),+ &mut bytes,+ AnonymizeOpts {+ byte_walk,+ image_policy: ImagePolicy::Parallel,+ },+ None,+ )+ .expect("anonymize should succeed");+ String::from_utf8_lossy(&out.lines).into_owned()+}++#[test]+fn a_ref_survives_a_trusted_rescrub() {+ for attr in ["src", "xlink:href", "rr_src", "poster", "rr_dataURL"] {+ assert!(+ scrub_trusted(&img_line(REF, attr)).contains(REF),+ "ref destroyed in {attr}"+ );+ }+ assert!(+ scrub_trusted(&canvas_line(REF)).contains(REF),+ "ref destroyed in a canvas blob"+ );+}++#[test]+fn a_trusted_rescrub_leaves_a_ref_attribute_exactly_as_it_was() {+ let out = scrub_trusted(&img_line(REF, "src"));+ assert!(out.contains(REF));+ assert!(+ !out.contains("data-anon-original-src"),+ "a stash was invented for a ref"+ );+ assert!(+ !out.contains("data:image/svg+xml"),+ "the ref was replaced by the placeholder"+ );+}++/// The bypass this guard must not become: the ref format is forgeable, so a value that merely+/// looks ref-ish must still be scrubbed on any path that has not opted in.+#[test]+fn a_forged_ref_is_scrubbed_on_the_untrusted_path() {+ let forged = "image:this is a secret the page wants to smuggle out";+ for byte_walk in [true, false] {+ let out = scrub_ingestion(&img_line(forged, "src"), byte_walk);+ assert!(+ !out.contains("secret the page wants"),+ "attacker-controlled value survived ingestion (byte_walk={byte_walk})"+ );+ }+ assert!(+ !scrub_default(&img_line(forged, "src")).contains("secret the page wants"),+ "attacker-controlled value survived a default re-scrub"+ );+}++/// Even a *well-formed* ref must not be preserved by a caller that has not vouched for its input:+/// provenance is the caller's assertion, never inferred from the value.+#[test]+fn a_well_formed_ref_is_still_scrubbed_without_the_opt_in() {+ for byte_walk in [true, false] {+ assert!(+ !scrub_ingestion(&img_line(REF, "src"), byte_walk).contains(REF),+ "a ref was preserved on the ingestion path (byte_walk={byte_walk})"+ );+ }+ assert!(+ !scrub_default(&img_line(REF, "src")).contains(REF),+ "a ref was preserved without the opt-in"+ );+}++/// Malformed refs are scrubbed even on the trusted path — the opt-in relaxes provenance, not shape.+#[test]+fn a_malformed_ref_is_scrubbed_even_when_trusted() {+ let cases = [+ "image:short:AAAAAAAAAAAAAAAAAAAAAA",+ "image:0123456789ABCDEF0123456789ABCDEF:AAAAAAAAAAAAAAAAAAAAAA", // uppercase team+ "image:0123456789abcdef0123456789abcdef:tooshort",+ "image:0123456789abcdef0123456789abcdef:has spaces in the hash!",+ "image:0123456789abcdef0123456789abcdef",+ "image:",+ ];+ for case in cases {+ let out = scrub_trusted(&img_line(case, "src"));+ assert!(!out.contains(case), "malformed ref preserved: {case}");+ }+}++/// A real image sitting next to a ref must still be scrubbed — the guard is not a bypass.+#[test]+fn the_guard_does_not_let_a_real_image_through() {+ use base64::Engine;+ let png = base64::engine::general_purpose::STANDARD+ .decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==")+ .unwrap();+ let src = format!(+ "data:image/png;base64,{}",+ base64::engine::general_purpose::STANDARD.encode(&png)+ );+ let line = json!(["w", { "type": 3, "timestamp": TS0, "data": {+ "source": 0, "adds": [+ { "parentId": 1, "nextId": null, "node": { "type": 2, "tagName": "img", "id": 42,+ "attributes": { "src": REF }, "childNodes": [] } },+ { "parentId": 1, "nextId": null, "node": { "type": 2, "tagName": "img", "id": 43,+ "attributes": { "src": src }, "childNodes": [] } }] } }]);+ let out = scrub_trusted(&line);+ assert!(out.contains(REF), "ref lost");+ assert!(+ !out.contains(&src),+ "a real image passed through unscrubbed"+ );+}++/// A remote URL is still placeholdered on every path.+#[test]+fn a_remote_url_is_still_placeholdered() {+ let line = img_line("https://cdn.example.com/logo.png", "src");+ assert!(scrub_trusted(&line).contains("data:image/svg+xml"));+ for byte_walk in [true, false] {+ assert!(scrub_ingestion(&line, byte_walk).contains("data:image/svg+xml"));+ }+}