Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ai-research): preserve remote image placeholders (#84099)

Nicholas Waltzcc1beebcc919
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
index 6be571e7a95b..54f8fc0eb3eb 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
@@ -10,8 +10,8 @@ code is written against. Where the code and this file disagree, one of them is a
| Part | What it is |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Mirror | The upstream lane. It replaces each image in a recording with a ref, and publishes the URLs it collected to the frontier. |
-| Ref | What the mirror writes into the recording in place of an image, built from a hash of the image URL. It is how a fetched image is later matched back to the recording that wanted it. |
+| Mirror | The upstream lane. It keeps the media placeholder, writes the image URL ref into a `data-anon-image-ref-<attribute>` sibling, and publishes the URLs it collected to the frontier. |
+| Ref | What the mirror writes into the namespaced sibling attribute, built from a hash of the image URL. It is how a fetched image is later matched back to the recording that wanted it. |
| Frontier | The topic `session_replay_image_fetch`. It holds the URLs waiting to be fetched. |
| Back queue | The URLs of one registrable domain. The topic key is the domain, so a partition holds whole back queues. |
| Pass | The fetching for one Kafka poll batch. Every back queue in the batch runs at the same time, and wall time bounds the pass rather than work. |
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 93d4d4c55c3a..a7320ee51025 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -47,11 +47,11 @@ export type MlMirrorConfig = {
/**
* Collect the URLs of remote images as well, so the fetch lane can download them later.
*
- * Enabling changes the mirrored JSONL shape a second time: a remote image's `src` carries an
- * `imageurl:<pseudoTeam>:<hash>` ref instead of the grey placeholder. The prefix differs from
- * the image lane's `image:` on purpose, because this hash names the URL rather than the bytes
- * behind it. Nothing fetches those URLs yet, so every such ref is dangling, and a dangling ref
- * renders as the same placeholder it replaced. What this buys is the measurement of how many
+ * Enabling changes the mirrored JSONL shape a second time: a remote image keeps its grey
+ * placeholder and a `data-anon-image-ref-<attribute>` sibling carries its
+ * `imageurl:<pseudoTeam>:<hash>` ref. The prefix differs from the image lane's `image:` on
+ * purpose, because this hash names the URL rather than the bytes behind it. Nothing fetches
+ * those URLs yet, so every such ref is dangling. What this buys is the measurement of how many
* URLs and how many distinct hosts real traffic carries.
*/
SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: boolean
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
index bee0cde5e745..faaf8d7a8fbd 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
@@ -76,8 +76,8 @@ export interface CollectedUrlsMessage {
* would then lose them. The group-by-host step already removes most of the record count, `linger.ms`
* makes the batches on the wire, and the ref cache stops a repeated image before it produces at all.
*
- * Delivery is not awaited and never fails the message. The mirrored lines already carry the refs,
- * and a ref with no image behind it renders as a placeholder.
+ * Delivery is not awaited and never fails the message. The mirrored lines already carry the refs
+ * in namespaced sibling attributes, while media sources keep their placeholders.
*
* The `url` field is the original, unscrubbed URL. It is as sensitive as the raw replay payload, so
* it goes only into the Kafka value. Log lines and metrics carry hosts and counts only.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
index d64d71707213..08f1ac6b52fc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -57,7 +57,7 @@ export interface CollectedImage {
* label, or any destination outside the fetch topic.
*/
export interface CollectedUrl {
- /** `imageurl:<pseudoTeam>:<hash>` — the ref the mirrored line carries for this URL. */
+ /** `imageurl:<pseudoTeam>:<hash>` stored in the mirrored line's namespaced ref attribute. */
ref: string
url: string
/** The host the request goes to. robots.txt and the connection limit are scoped to this. */
@@ -78,7 +78,7 @@ export interface ImageCollectionConfig {
/** Replace inlined images with refs and return their bytes for the scrub topic. */
collectImages: boolean
/**
- * Replace a remote image's `src` with a ref and return its URL for the fetch lane.
+ * Keep a remote image's placeholder, stash its ref, and return its URL for the fetch lane.
*
* Independent of `collectImages`. The two lanes have separate destinations and separate
* rollouts, so tying them together would make the URL measurement wait on the scrub lane.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index e419c70c3fba..85c69693b768 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8973,7 +8973,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.4.4"
+version = "0.4.5"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index 1ef6d1e1b4e3..f0092e6d833a 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -30,7 +30,7 @@ export interface AnonymizeImageEntry {
/** One collected remote image URL, ready for the fetch lane. */
export interface AnonymizeUrlEntry {
/** First 22 base64url chars of `HMAC-SHA256(urlKey, dedupUrl)`, where the dedup URL is the
- * canonical URL minus its volatile parameters. The ref in the mirrored line ends with this. */
+ * canonical URL minus its volatile parameters. The namespaced ref attribute ends with this. */
hash: string
/** The canonical URL with every parameter intact — what the fetcher requests. A signed URL only
* works in this form, which is why it is not the value the hash was taken over. */
@@ -137,9 +137,9 @@ export function initAnonymizer(allow: AllowListsInput): void {
* blur, and the original bytes come back in `images`/`meta.images` for the caller to produce to
* the scrub topic.
*
- * `urlKey` enables the URL-collection lane alongside it: a remote image's `src` is replaced with a
- * ref of the same shape, and its original URL comes back in `meta.urls` for the caller to hand to
- * the fetch lane.
+ * `urlKey` enables the URL-collection lane alongside it: a remote image's `src` keeps the media
+ * placeholder, a namespaced sibling attribute carries its ref, and its original URL comes back in
+ * `meta.urls` for the caller to hand to the fetch lane.
*
* The two lanes are independent: either, both, or neither. Both need `pseudoTeam`, because the ref
* embeds it, so a `contentKey` or a `urlKey` without one throws.
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 69c826fe0a96..c7d2d1ba9c05 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.4"
+version = "0.4.5"
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.rs
index 7b8d9ce1793e..bcb5337be3eb 100644
--- a/rust/replay-anonymizer/src/assets.rs
+++ b/rust/replay-anonymizer/src/assets.rs
@@ -19,6 +19,7 @@ pub const INLINE_IMAGE_ATTR: &str = "rr_dataURL";
pub const PLACEHOLDER_SRC: &str = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>";
pub const MEDIA_SRC_ATTRS: &[&str] = &["src", "rr_src", "srcset", "href", "xlink:href", "poster"];
+pub(crate) const IMAGE_REF_ATTR_PREFIX: &str = "data-anon-image-ref-";
pub fn is_media_tag(tag: &str) -> bool {
matches!(
@@ -31,6 +32,10 @@ pub fn is_media_src_attr(name: &str) -> bool {
MEDIA_SRC_ATTRS.contains(&name)
}
+pub(crate) fn is_image_ref_attr(name: &str) -> bool {
+ name.starts_with(IMAGE_REF_ATTR_PREFIX)
+}
+
/// True for a tag whose `src` names an image.
///
/// `TagKind::Media` is too broad to decide this. It also covers `video`, `audio`, `track` and
@@ -93,8 +98,9 @@ pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str)
}
/// Replace a media element's source attrs with the blurred image (data URIs) or placeholder (remote
-/// URLs, whose scrubbed original is stashed under a namespaced attr). Returns whether it changed any
-/// attribute — a media tag with no source attrs (e.g. a bare `<img>`) is left untouched.
+/// 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(ctx: &Ctx<'_>, attrs: &mut Object<'_>, tag_src_is_image: bool) -> bool {
let mut acted = false;
for key in MEDIA_SRC_ATTRS {
@@ -114,22 +120,21 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>, tag_src_is_image: bool)
let blurred = ctx.scrub_image(&existing, ImageFallback::Placeholder);
attrs.insert(Cow::Borrowed(*key), string_value(blurred));
} else {
- // A ref here means the fetch lane downloads this URL and scrubs it out of band. The
- // attribute can therefore carry a join key instead of the placeholder. Until those bytes
- // land the ref is dangling, which readers already render as the placeholder, so the
- // worst case matches the behaviour this replaces.
let collected = is_fetchable_src_attr(key, tag_src_is_image)
.then(|| ctx.collect_url(&existing))
.flatten();
- // Stashed under a namespaced attr that won't collide with an app `data-original-*`.
let scrubbed = scrub_url(ctx, &existing).unwrap_or(existing);
- match collected {
- Some(url_ref) => attrs.insert(Cow::Borrowed(*key), string_value(url_ref)),
- None => attrs.insert(
- Cow::Borrowed(*key),
- Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),
- ),
- };
+ // Fetch completion must not change how an ordinary replay renders this element.
+ attrs.insert(
+ Cow::Borrowed(*key),
+ Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),
+ );
+ if let Some(url_ref) = collected {
+ attrs.insert(
+ Cow::Owned(format!("{IMAGE_REF_ATTR_PREFIX}{key}")),
+ string_value(url_ref),
+ );
+ }
attrs.insert(
Cow::Owned(format!("data-anon-original-{key}")),
string_value(scrubbed),
diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rs
index 9f743abbd0ef..da4db9cb60af 100644
--- a/rust/replay-anonymizer/src/bytewalk.rs
+++ b/rust/replay-anonymizer/src/bytewalk.rs
@@ -14,7 +14,8 @@
//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.
use crate::assets::{
- is_fetchable_src_attr, is_media_src_attr, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC,
+ is_fetchable_src_attr, is_image_ref_attr, is_media_src_attr, 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;
@@ -826,8 +827,8 @@ impl<'c, 'a> Walker<'c, 'a> {
}
/// An element's `attributes` object (mirrors `dom::scrub_attrs`, including the media blur).
- /// Stash attrs (`data-anon-original-*`) are appended before the closing brace; the tree path
- /// inserts them into the map instead, which is the same object semantically.
+ /// 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(
&mut self,
start: usize,
@@ -843,6 +844,12 @@ impl<'c, 'a> Walker<'c, 'a> {
let stashes = &mut stashes;
self.walk_object(start, out, &mut |w, key, vstart, out| {
let name = std::str::from_utf8(&w.bytes[key.0..key.1]).ok()?;
+ // Existing internal refs need provenance validation and may need removing. The
+ // object emitter cannot omit one member, so let the tree path handle this rare
+ // input shape rather than risk duplicate or attacker-controlled join keys.
+ if is_image_ref_attr(name) {
+ return None;
+ }
if kind == TagKind::Media && is_media_src_attr(name) {
return w.blur_media_src(name, vstart, tag_src_is_image, out, stashes);
}
@@ -893,8 +900,8 @@ impl<'c, 'a> Walker<'c, 'a> {
}
/// One media source attribute (mirrors `assets::apply_blur` for a single key): data images are
- /// blurred; a remote URL becomes a fetch-lane ref when collection is on, and the placeholder
- /// otherwise. Either way the host-scrubbed original is stashed alongside.
+ /// blurred; a remote URL becomes the placeholder. Its fetch-lane ref, when collected, and its
+ /// host-scrubbed original are stashed alongside.
fn blur_media_src(
&mut self,
name: &str,
@@ -923,9 +930,9 @@ impl<'c, 'a> Walker<'c, 'a> {
.then(|| self.ctx.collect_url(&existing))
.flatten();
let scrubbed = scrub_url(self.ctx, &existing).unwrap_or_else(|| existing.into_owned());
- match collected {
- Some(url_ref) => scan::write_json_string(&url_ref, out),
- None => scan::write_json_string(PLACEHOLDER_SRC, out),
+ scan::write_json_string(PLACEHOLDER_SRC, out);
+ if let Some(url_ref) = collected {
+ stashes.push((format!("{IMAGE_REF_ATTR_PREFIX}{name}"), url_ref));
}
stashes.push((format!("data-anon-original-{name}"), scrubbed));
}
diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rs
index cf4d95a3aca0..86c50a364394 100644
--- a/rust/replay-anonymizer/src/context.rs
+++ b/rust/replay-anonymizer/src/context.rs
@@ -37,7 +37,7 @@ 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>>,
- // `Some` routes remote image URLs to the fetch lane instead of the media placeholder.
+ // `Some` routes remote image URLs to the fetch lane and emits refs beside the media placeholder.
url_collector: Option<RefCell<UrlCollector>>,
// 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`.
@@ -81,8 +81,7 @@ impl<'a> Ctx<'a> {
}
}
- /// Leave well-formed `image:<pseudo_team>:<hash>` refs already present in the input alone
- /// instead of scrubbing them.
+ /// Leave well-formed image 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
@@ -147,8 +146,8 @@ impl<'a> Ctx<'a> {
}
}
- /// Route remote image URLs to the fetch lane. Off unless set, exactly like image collection,
- /// so a caller that does not opt in keeps the media placeholder it has today.
+ /// Route remote image URLs to the fetch lane. Off unless set, exactly like image collection.
+ /// The media source keeps its placeholder either way.
pub fn collecting_urls(mut self, url_collection: Option<UrlCollection>) -> Self {
self.url_collector = url_collection.map(|c| RefCell::new(UrlCollector::new(c)));
self
@@ -157,7 +156,8 @@ impl<'a> Ctx<'a> {
/// The fetch lane's ref for a remote image URL.
///
/// `None` when collection is off, when the URL is not fetchable, or when the per-message cap
- /// is reached. The caller then writes the placeholder, as before.
+ /// is reached. The caller writes the placeholder regardless and stashes a returned ref beside
+ /// it.
pub(crate) fn collect_url(&self, original: &str) -> Option<String> {
let collector = self.url_collector.as_ref()?;
collector.borrow_mut().collect(original)
diff --git a/rust/replay-anonymizer/src/dom.rs b/rust/replay-anonymizer/src/dom.rs
index 1e2b6536bdac..e5501bb98486 100644
--- a/rust/replay-anonymizer/src/dom.rs
+++ b/rust/replay-anonymizer/src/dom.rs
@@ -5,9 +5,10 @@
use simd_json::borrowed::{Object, Value};
use crate::assets::{
- apply_blur, blur_inline_image_attr, has_media_src_attr, is_media_src_attr, is_media_tag,
- INLINE_IMAGE_ATTR,
+ apply_blur, blur_inline_image_attr, has_media_src_attr, is_image_ref_attr, is_media_src_attr,
+ is_media_tag, INLINE_IMAGE_ATTR,
};
+use crate::collect::is_image_ref_strict;
use crate::context::Ctx;
use crate::css::{scrub_css_images, INLINED_STYLESHEET_ATTR};
use crate::json::{
@@ -215,9 +216,17 @@ fn scrub_attrs(
// 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();
+ let mut rejected_image_refs: Vec<String> = Vec::new();
for (name, value) in attrs.iter_mut() {
let name: &str = name.as_ref();
+ if is_image_ref_attr(name) {
+ let keep = ctx.keeps_image_refs() && as_str(value).is_some_and(is_image_ref_strict);
+ if !keep {
+ rejected_image_refs.push(name.to_string());
+ }
+ continue;
+ }
if kind == TagKind::Media && is_media_src_attr(name) {
continue;
}
@@ -249,6 +258,11 @@ fn scrub_attrs(
}
}
+ for name in rejected_image_refs {
+ attrs.remove(name.as_str());
+ changed = true;
+ }
+
for name in deferred {
if name == INLINE_IMAGE_ATTR {
changed |= blur_inline_image_attr(ctx, attrs, &name);
@@ -282,7 +296,9 @@ pub(crate) fn is_user_text_attr(name: &str) -> bool {
}
pub(crate) fn is_data_attr(name: &str) -> bool {
- name.starts_with("data-") && !name.starts_with("data-anon-original-")
+ name.starts_with("data-")
+ && !name.starts_with("data-anon-original-")
+ && !is_image_ref_attr(name)
}
pub(crate) fn data_attr_looks_sensitive(value: &str) -> bool {
diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rs
index fad7ada3a84e..eb4eb8db16fa 100644
--- a/rust/replay-anonymizer/src/snapshot.rs
+++ b/rust/replay-anonymizer/src/snapshot.rs
@@ -291,9 +291,9 @@ pub fn anonymize_kafka_payload_timed(
/// [`anonymize_kafka_payload_timed`] with the URL-collection lane as well.
///
-/// A remote image's `src` becomes a ref, and its original URL comes back in `meta.urls`. The
-/// caller passes those to the fetch lane. `None` leaves a remote image on the media placeholder,
-/// which is what every other entry point here does.
+/// A remote image keeps its placeholder while a namespaced sibling attribute carries its ref. Its
+/// original URL comes back in `meta.urls`, which the caller passes to the fetch lane. `None` omits
+/// the sibling ref and leaves the placeholder unchanged.
pub fn anonymize_kafka_payload_collecting(
allow: &AllowLists,
payload: &mut [u8],
diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rs
index 79b4dd6ea5d9..2ce0352f0089 100644
--- a/rust/replay-anonymizer/src/url_collect.rs
+++ b/rust/replay-anonymizer/src/url_collect.rs
@@ -2,8 +2,9 @@
//!
//! The sibling of [`crate::collect`]. That module handles an image the page inlined into the
//! recording; this one handles an image the page referred to by URL. With collection enabled, a
-//! media source attribute holding an `http(s)` URL is replaced by a content ref instead of the
-//! media placeholder. The message then carries the original URL back to the caller.
+//! media source attribute holding an `http(s)` URL keeps the media placeholder and a namespaced
+//! sibling attribute carries the content ref. The message also carries the original URL back to
+//! the caller.
//!
//! **Two URLs come out of this module. Do not confuse them.**
//!
diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rs
index bcafb703ac4d..0c2e57696fff 100644
--- a/rust/replay-anonymizer/tests/ref_idempotence.rs
+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs
@@ -2,10 +2,9 @@
//! 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.
+//! bytes out of band, so that ref is the only join key back to them. Remote images keep a media
+//! placeholder and carry an `imageurl:<pseudo_team>:<hash>` ref in a namespaced sibling attribute.
+//! Scrubbing mirrored output a second time must not destroy either join key.
//!
//! 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
@@ -20,6 +19,7 @@ use serde_json::{json, Value};
const TS0: f64 = 1_700_000_000_000.0;
const REF: &str = "image:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";
+const URL_REF: &str = "imageurl:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";
fn img_line(value: &str, attr: &str) -> Value {
json!(["w", { "type": 3, "timestamp": TS0, "data": {
@@ -102,6 +102,19 @@ fn a_ref_survives_a_trusted_rescrub() {
);
}
+#[test]
+fn a_namespaced_url_ref_survives_only_a_trusted_rescrub() {
+ let line = img_line(URL_REF, "data-anon-image-ref-src");
+ assert!(scrub_trusted(&line).contains(URL_REF));
+ assert!(!scrub_default(&line).contains("data-anon-image-ref-src"));
+ for byte_walk in [true, false] {
+ assert!(
+ !scrub_ingestion(&line, byte_walk).contains("data-anon-image-ref-src"),
+ "a captured internal ref attribute survived ingestion (byte_walk={byte_walk})"
+ );
+ }
+}
+
#[test]
fn a_trusted_rescrub_leaves_a_ref_attribute_exactly_as_it_was() {
let out = scrub_trusted(&img_line(REF, "src"));
@@ -155,6 +168,7 @@ fn a_well_formed_ref_is_still_scrubbed_without_the_opt_in() {
fn a_malformed_ref_is_scrubbed_even_when_trusted() {
let cases = [
"image:short:AAAAAAAAAAAAAAAAAAAAAA",
+ "imageurl:short:AAAAAAAAAAAAAAAAAAAAAA",
"image:0123456789ABCDEF0123456789ABCDEF:AAAAAAAAAAAAAAAAAAAAAA", // uppercase team
"image:0123456789abcdef0123456789abcdef:tooshort",
"image:0123456789abcdef0123456789abcdef:has spaces in the hash!",
@@ -162,8 +176,13 @@ fn a_malformed_ref_is_scrubbed_even_when_trusted() {
"image:",
];
for case in cases {
- let out = scrub_trusted(&img_line(case, "src"));
- assert!(!out.contains(case), "malformed ref preserved: {case}");
+ for attr in ["src", "data-anon-image-ref-src"] {
+ let out = scrub_trusted(&img_line(case, attr));
+ assert!(
+ !out.contains(case),
+ "malformed ref preserved in {attr}: {case}"
+ );
+ }
}
}
diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rs
index 1e2637d8fe15..87b18eead1a9 100644
--- a/rust/replay-anonymizer/tests/url_collection.rs
+++ b/rust/replay-anonymizer/tests/url_collection.rs
@@ -1,9 +1,9 @@
//! The URL-collection lane, end to end through a real Kafka payload.
//!
//! The unit tests in `url_collect` pin canonicalization and the collector in isolation. These pin
-//! the parts only the whole pipeline can show: that a remote `src` comes out as a ref rather than
-//! the placeholder, that the original URL reaches `meta.urls`, that the scrubbed copy is still
-//! stashed alongside, and that a caller who does not opt in sees exactly what it saw before.
+//! the parts only the whole pipeline can show: that a remote `src` stays on the placeholder, that
+//! the ref is stashed separately, that the original URL reaches `meta.urls`, and that the scrubbed
+//! copy is still stashed alongside.
use posthog_replay_anonymizer::{
anonymize_kafka_payload_collecting, AllowLists, AnonymizeOpts, ImagePolicy, UrlCollection,
@@ -162,7 +162,7 @@ fn attrs_of(line: &Value) -> &Value {
}
#[test]
-fn a_remote_src_becomes_a_ref_and_its_url_reaches_meta() {
+fn a_remote_src_keeps_its_placeholder_and_stashes_the_ref() {
for (engine, result) in run(
json!({ "src": "https://cdn.example.com/hero.png?w=200" }),
true,
@@ -170,8 +170,15 @@ fn a_remote_src_becomes_a_ref_and_its_url_reaches_meta() {
let (line, meta) = (&result[0], &result[1]);
let src = attrs_of(line)["src"].as_str().expect("src is a string");
assert!(
- src.starts_with(&format!("imageurl:{PSEUDO_TEAM}:")),
- "{engine}: expected a url ref, got {src}"
+ src.starts_with("data:image/svg+xml"),
+ "{engine}: expected the placeholder, got {src}"
+ );
+ let url_ref = attrs_of(line)["data-anon-image-ref-src"]
+ .as_str()
+ .expect("the URL ref is stashed");
+ assert!(
+ url_ref.starts_with(&format!("imageurl:{PSEUDO_TEAM}:")),
+ "{engine}: expected a URL ref, got {url_ref}"
);
let urls = meta["urls"].as_array().expect("meta.urls present");
@@ -179,12 +186,10 @@ fn a_remote_src_becomes_a_ref_and_its_url_reaches_meta() {
assert_eq!(urls[0]["url"], "https://cdn.example.com/hero.png?w=200");
assert_eq!(urls[0]["host"], "cdn.example.com");
assert!(
- src.ends_with(urls[0]["hash"].as_str().expect("hash is a string")),
+ url_ref.ends_with(urls[0]["hash"].as_str().expect("hash is a string")),
"{engine}: the ref must carry the hash meta reports"
);
- // The scrubbed copy still rides along, so a reader that never resolves the ref keeps what
- // it has today.
assert!(
attrs_of(line)["data-anon-original-src"].is_string(),
"{engine}: the scrubbed original should still be stashed"
@@ -205,6 +210,10 @@ fn without_a_collection_a_remote_src_is_still_the_placeholder() {
meta.get("urls").is_none(),
"{engine}: meta.urls should be absent when nothing was collected"
);
+ assert!(
+ attrs_of(line).get("data-anon-image-ref-src").is_none(),
+ "{engine}: no ref should be stashed when nothing was collected"
+ );
}
}
@@ -215,10 +224,9 @@ fn an_inlined_image_is_untouched_by_the_url_lane() {
let inlined = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
for (engine, result) in run(json!({ "src": inlined }), true) {
let (line, meta) = (&result[0], &result[1]);
- let src = attrs_of(line)["src"].as_str().expect("src is a string");
assert!(
- !src.starts_with("imageurl:"),
- "{engine}: an inlined image must not take the URL lane, got {src}"
+ attrs_of(line).get("data-anon-image-ref-src").is_none(),
+ "{engine}: an inlined image must not take the URL lane"
);
assert!(meta.get("urls").is_none(), "{engine}");
}
@@ -233,6 +241,7 @@ fn a_non_fetchable_scheme_keeps_the_placeholder() {
src.starts_with("data:image/svg+xml"),
"{engine}: expected the placeholder, got {src}"
);
+ assert!(attrs_of(line).get("data-anon-image-ref-src").is_none());
assert!(meta.get("urls").is_none(), "{engine}");
}
}
@@ -253,6 +262,10 @@ fn srcset_stays_out_of_scope_and_keeps_the_placeholder() {
srcset.starts_with("data:image/svg+xml"),
"{engine}: expected the placeholder, got {srcset}"
);
+ assert!(
+ attrs_of(line).get("data-anon-image-ref-srcset").is_none(),
+ "{engine}"
+ );
assert!(meta.get("urls").is_none(), "{engine}");
}
}