: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): collect images from more replay fields (#89121)
Robbie7a6d1846fb63
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex 78293b5b3888..c46dd4473bce 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -16,6 +16,8 @@ export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' |* ships. */export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'+export type MlImageSource = 'css' | 'html'+export type MlImageSourceKind = 'inline' | 'url'const URL_BYTES_SAMPLE_RATE = 16@@ -97,6 +99,12 @@ export class SessionRecordingIngesterMetrics {labelNames: ['outcome'],})+ private static readonly mlImageReferencesByProperty = new Counter({+ name: 'recording_blob_ingestion_v2_ml_image_references_by_property',+ help: 'Collected CSS and HTML image ref occurrences by bounded source, property, and lane. Counts references before per-message content or URL deduplication',+ labelNames: ['source', 'property', 'kind'],+ })+private static readonly mlUrlCrawlHistory = new Counter({name: 'recording_blob_ingestion_v2_ml_url_crawl_history_total',help: 'URL jobs checked by the mirror before Kafka: fresh jobs are suppressed, misses are produced, and errors fail open',@@ -187,6 +195,17 @@ export class SessionRecordingIngesterMetrics {this.mlImagesCollected.labels(outcome).inc(count)}+ public static incrementMlImageReferencesByProperty(+ source: MlImageSource,+ property: string,+ kind: MlImageSourceKind,+ count: number+ ): void {+ if (count > 0) {+ this.mlImageReferencesByProperty.labels(source, property, kind).inc(count)+ }+ }+private static readonly mlUrlBytes = new Histogram({name: 'recording_blob_ingestion_v2_ml_url_bytes',help: 'Bytes in one collected remote image URL, sampled. The tail sizes the per-record packing budget, because a record is filled by bytes rather than by a fixed number of URLs. Read the shape, not the count: one URL in URL_BYTES_SAMPLE_RATE is observed',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.mdindex d5deac1d7afe..3effb040febf 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@@ -463,6 +463,8 @@ It counts transient retry causes as `timeout`, `error`, `rate_limited`, or `serv**11.9** Alerts use frontier-topic lag, pass-budget saturation, active batch age, delivery failures, and invalid frontier or retry input. Durable log alerts cover one-shot failures that can stop a pod before Prometheus scrapes its counters. Requirement 16.6 still prohibits alerts on delay-topic lag.+**11.10** The mirror counts collected image ref occurrences by `css` or `html` source, canonical property name, and `inline` or `url` lane. It counts before per-message ref deduplication. Every property label comes from the fixed HTML attribute set in requirement 13.11 or the fixed CSS property allowlist in the anonymizer.+### 12. Conditional requests**12.1** The lane stores the request time, response time, `ETag`, `Last-Modified`, `Date`, `Age`, `Cache-Control`, and `Expires` metadata in the crawl history for that URL.@@ -497,11 +499,21 @@ The fetch URL keeps the original query verbatim. The global ref uses a canonical**13.5** A URL ref has the form `imageurl:<hash>`. The producer calculates `GLOBAL_URL_KEY` with the existing `pseudonymize(ml_pseudonymization_secret, "image-url-key", "global-v1")` construction. The hash is the first 22 base64url characters of `HMAC-SHA256(GLOBAL_URL_KEY, canonical_url)`. Every producer must use this construction. The DynamoDB crawl-history key for the original URL is the same `imageurl:<hash>` string.-**13.6** The mirror stores the ref in a sibling attribute named `data-anon-image-ref-<attribute>`. For example, the ref for `src` is stored in `data-anon-image-ref-src`. The source attribute keeps its image placeholder.+**13.6** For a direct image attribute, the mirror stores the ref in a sibling attribute named `data-anon-image-ref-<attribute>`. For example, the ref for `src` is stored in `data-anon-image-ref-src`. The source attribute keeps its image placeholder.++**13.7** For a CSS field, the mirror stores refs in a sibling attribute named `data-anon-image-refs-<field>`. Its value is a JSON object that maps each decimal slot number to one image ref.++**13.8** The mirror replaces each collected CSS image with the existing valid SVG placeholder. It adds `<metadata id='anon-image-slot-<slot>'/>` before the closing `</svg>` to identify the corresponding ref without changing the rendered placeholder.++**13.9** Data preparation uses the suffix of a direct ref attribute to find its source attribute. It uses each CSS slot number to find the matching numbered placeholder. If the ref resolves, data preparation replaces the placeholder with the scrubbed image.++**13.10** Data preparation removes direct ref attributes and CSS ref maps whether or not their refs resolve. It removes the slot metadata from unresolved CSS placeholders, so the remaining CSS still contains a valid, unnumbered placeholder.++**13.11** The mirror collects remote images from `img[src]`, `img[rr_src]`, `img[srcset]`, SVG `image[href]`, SVG `image[xlink:href]`, `video[poster]`, and `source[srcset]` below a `picture` element. It does not infer a `source` parent from a tagless attribute mutation.-**13.7** Data preparation uses the suffix of the ref attribute to find the source attribute. If the ref resolves, data preparation replaces the placeholder with the scrubbed image.+**13.12** For `srcset` and CSS `image-set()`, the mirror selects the candidate with the largest width or pixel density. It declines a malformed or mixed `srcset`. The first candidate wins a tie.-**13.8** Data preparation removes the ref attribute whether or not the ref resolves. The ref is a hash that has no meaning in training data and would appear as random noise.+**13.13** The mirror processes inline base64 images and remote URLs in image-bearing CSS properties. It keeps same-document fragment URLs unchanged and does not collect font or import URLs.### 14. HTTP request/responsediff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.tsindex b6681243a9f6..eea6bae910f9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts@@ -47,12 +47,10 @@ 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 keeps its grey- * placeholder and a `data-anon-image-ref-<attribute>` sibling carries its- * `imageurl:<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.+ * Enabling changes the mirrored JSONL shape a second time. A direct remote image keeps its+ * placeholder and a `data-anon-image-ref-<attribute>` sibling carries its `imageurl:<hash>`+ * ref. CSS keeps numbered placeholders and a `data-anon-image-refs-<field>` sibling carries a+ * JSON slot-to-ref map. The URL hash names the URL rather than the bytes behind it.*/SESSION_RECORDING_ML_URL_COLLECTION_ENABLED: booleandiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.tsindex ca6f96bde3a1..6d60013b58f3 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts@@ -1,5 +1,6 @@import { Message } from 'node-rdkafka'import { promisify } from 'node:util'+import { register } from 'prom-client'import { gzip } from 'zlib'import { PipelineResultType } from '~/ingestion/framework/results'@@ -16,6 +17,21 @@ import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'import { SessionReplayHeaders } from './pipeline-types'const compressWithGzip = promisify(gzip)+const IMAGE_SOURCE_METRIC = 'recording_blob_ingestion_v2_ml_image_references_by_property'++async function imageSourceMetricValue(source: string, property: string, kind: string): Promise<number> {+ const metric = register.getSingleMetric(IMAGE_SOURCE_METRIC)+ if (!metric) {+ return 0+ }+ const { values } = await metric.get()+ return (+ values.find(+ (value) =>+ value.labels.source === source && value.labels.property === property && value.labels.kind === kind+ )?.value ?? 0+ )+}// The native addon is the mocked boundary: these tests pin the TS side of the fused step — failure// classification (dlq vs drop), the timestamp window, header/body agreement, and the ParsedMessageData@@ -217,7 +233,8 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {function addonSuccessWithImages(images: Buffer | null,- imageEntries?: { hash: string; offset: number; len: number }[]+ imageEntries?: { hash: string; offset: number; len: number }[],+ imageSources?: { source: 'css' | 'html'; property: string; kind: 'inline' | 'url'; count: number }[]): void {mockAnonymizeKafkaPayload.mockResolvedValue({failed: false,@@ -238,6 +255,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {consoleErrorCount: 0,events: [{ ts: now, flags: 0 }],images: imageEntries,+ imageSources,}),})}@@ -291,6 +309,24 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {expect(result.type).toBe(PipelineResultType.OK)expect((result as any).value.collectedImages).toBeUndefined()})++ it('records bounded CSS and HTML image source counts', async () => {+ const cssBefore = await imageSourceMetricValue('css', 'background-image', 'inline')+ const htmlBefore = await imageSourceMetricValue('html', 'src', 'url')+ addonSuccessWithImages(+ Buffer.from('a'),+ [{ hash: 'hashA', offset: 0, len: 1 }],+ [+ { source: 'css', property: 'background-image', kind: 'inline', count: 3 },+ { source: 'html', property: 'src', kind: 'url', count: 2 },+ ]+ )++ await step({ message: kafkaMessage(), headers, team })++ await expect(imageSourceMetricValue('css', 'background-image', 'inline')).resolves.toBe(cssBefore + 3)+ await expect(imageSourceMetricValue('html', 'src', 'url')).resolves.toBe(htmlBefore + 2)+ })})describe('createParseAndAnonymizeMessageStep with url collection', () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.tsindex 2d6af0bdc81b..911de63e7c2f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts@@ -277,10 +277,22 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp? unpackCollectedImages(teamKeys.pseudoTeam, meta, result.images): undefinedconst collectedUrls = globalUrlKey && teamKeys ? unpackCollectedUrls(teamKeys.pseudoTeam, meta) : undefined+ recordImageSources(meta)return ok({ ...input, parsedMessage, collectedImages, collectedUrls })}}+function recordImageSources(meta: AnonymizeMeta): void {+ for (const imageSource of meta.imageSources ?? []) {+ SessionRecordingIngesterMetrics.incrementMlImageReferencesByProperty(+ imageSource.source,+ imageSource.property,+ imageSource.kind,+ imageSource.count+ )+ }+}+/*** Slice the addon's packed image buffer into per-image produce records. The lines already carry the* refs, so a skipped slice only means that ref stays dangling (same outcome as a failed produce) —diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex b00fbb1c98b4..177c0f85525f 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8979,7 +8979,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.6"+version = "0.4.7"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 6a4af3528b70..85c80174e3cd 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -42,6 +42,13 @@ export interface AnonymizeUrlEntry {domain: string}+export interface AnonymizeImageSourceCount {+ source: 'css' | 'html'+ property: string+ kind: 'inline' | 'url'+ count: number+}+/** Envelope + per-event metadata parsed from {@link AnonymizeKafkaPayloadResult.meta}. */export interface AnonymizeMeta {distinctId: string@@ -63,6 +70,8 @@ export interface AnonymizeMeta {images?: AnonymizeImageEntry[]/** Collected remote image URLs (hash-sorted); present only when the URL lane was enabled and URLs were collected. */urls?: AnonymizeUrlEntry[]+ /** Collected ref occurrences by bounded replay location, property, and inline or URL lane. */+ imageSources?: AnonymizeImageSourceCount[]/** Counts by reason for the URLs the collector refused. Absent when it refused none. */urlDeclines?: { reason: string; count: number }[]}diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 1e3f78820e07..fee40e209e01 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.6"+version = "0.4.7"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 75dfb7087c9e..779650760b1a 100644--- a/rust/replay-anonymizer/src/assets.rs+++ b/rust/replay-anonymizer/src/assets.rs@@ -8,9 +8,10 @@ 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::context::{Ctx, ImageSource};use crate::images::ImageFallback;use crate::json::{as_str, string_value};+use crate::srcset::largest_candidate;use crate::url::scrub_url;// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute.@@ -20,6 +21,7 @@ pub const PLACEHOLDER_SRC: &str = "data:image/svg+xml;utf8,<svg xmlns='http://wwpub 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(crate) const CSS_IMAGE_REFS_ATTR_PREFIX: &str = "data-anon-image-refs-";pub fn is_media_tag(tag: &str) -> bool {matches!(@@ -33,40 +35,38 @@ pub fn is_media_src_attr(name: &str) -> bool {}pub(crate) fn is_image_ref_attr(name: &str) -> bool {- name.starts_with(IMAGE_REF_ATTR_PREFIX)+ name.starts_with(IMAGE_REF_ATTR_PREFIX) || name.starts_with(CSS_IMAGE_REFS_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-/// `source`. Their `src` is a movie, a sound file, or a WebVTT subtitle document.-///-/// `source` is excluded because its meaning depends on its parent, and the walk does not carry-/// one.-pub(crate) fn tag_src_is_image(tag: &str) -> bool {- matches!(- tag.to_ascii_lowercase().as_str(),- "img" | "image" | "picture"- )+pub(crate) fn numbered_placeholder(slot: usize) -> String {+ let before_close = PLACEHOLDER_SRC+ .strip_suffix("</svg>")+ .expect("the static image placeholder is SVG");+ format!("{before_close}<metadata id='anon-image-slot-{slot}'/></svg>")+}++pub(crate) fn is_numbered_placeholder(value: &str) -> bool {+ let Some(before_close) = PLACEHOLDER_SRC.strip_suffix("</svg>") else {+ return false;+ };+ let Some(slot) = value+ .strip_prefix(before_close)+ .and_then(|value| value.strip_prefix("<metadata id='anon-image-slot-"))+ .and_then(|value| value.strip_suffix("'/></svg>"))+ else {+ return false;+ };+ !slot.is_empty() && slot.bytes().all(|byte| byte.is_ascii_digit())}-/// Whether the fetch lane may collect the URL in this attribute.-///-/// A subset of [`MEDIA_SRC_ATTRS`], because the rest do not name one fetchable image.-///-/// `src` needs the tag as well as the name.-///-/// Without the tag check, the lane collects the `src` of a `<video>`, an `<audio>` or a `<track>`.-/// The mutation path is worse: rrweb sends attributes with no tag, so any `src` passes, including-/// one from an `<iframe>` or a `<script>`.-///-/// The fetch lane is sized to download images. Video, subtitle text and third-party JavaScript are-/// a different workload and a different data-classification question. `tag_src_is_image` is false-/// on the tagless mutation path, so that path declines rather than guesses.-///-/// The other media attributes remain out of scope until the fetcher specification includes them.-pub(crate) fn is_fetchable_src_attr(name: &str, tag_src_is_image: bool) -> bool {- name == "src" && tag_src_is_image+pub(crate) fn is_fetchable_image_attr(name: &str, tag: &str, parent_is_picture: bool) -> bool {+ match tag.to_ascii_lowercase().as_str() {+ "img" => matches!(name, "src" | "rr_src" | "srcset"),+ "image" => matches!(name, "href" | "xlink:href"),+ "video" => name == "poster",+ "source" => parent_is_picture && name == "srcset",+ _ => false,+ }}/// True if an attribute map contains any media-source attribute.@@ -83,7 +83,11 @@ pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str)if !is_image_data_uri(&value) {return false;}- let blurred = ctx.scrub_image(&value, ImageFallback::Blank);+ let blurred = ctx.scrub_image_from(+ &value,+ ImageFallback::Blank,+ ImageSource::HtmlAttribute(INLINE_IMAGE_ATTR),+ );attrs.insert(Cow::Owned(name.to_string()), string_value(blurred));true}@@ -92,7 +96,12 @@ pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str)/// 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 {+pub fn apply_blur(+ ctx: &Ctx<'_>,+ attrs: &mut Object<'_>,+ tag: &str,+ parent_is_picture: bool,+) -> bool {let mut acted = false;for key in MEDIA_SRC_ATTRS {let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {@@ -107,14 +116,30 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>, tag_src_is_image: bool)continue;}acted = true;- if is_image_data_uri(&existing) {- let blurred = ctx.scrub_image(&existing, ImageFallback::Placeholder);+ let selected = if *key == "srcset" {+ largest_candidate(&existing).map(str::to_string)+ } else {+ Some(existing.clone())+ };+ let Some(selected) = selected else {+ attrs.insert(+ Cow::Borrowed(*key),+ Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),+ );+ continue;+ };+ if is_image_data_uri(&selected) {+ let blurred = ctx.scrub_image_from(+ &selected,+ ImageFallback::Placeholder,+ ImageSource::HtmlAttribute(key),+ );attrs.insert(Cow::Borrowed(*key), string_value(blurred));} else {- let collected = is_fetchable_src_attr(key, tag_src_is_image)- .then(|| ctx.collect_url(&existing))+ let collected = is_fetchable_image_attr(key, tag, parent_is_picture)+ .then(|| ctx.collect_url_from(&selected, ImageSource::HtmlAttribute(key))).flatten();- let scrubbed = scrub_url(ctx, &existing).unwrap_or(existing);+ let scrubbed = scrub_url(ctx, &selected).unwrap_or_else(|| selected.clone());// Fetch completion must not change how an ordinary replay renders this element.attrs.insert(Cow::Borrowed(*key),diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex da4db9cb60af..35bc563d6170 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -14,12 +14,12 @@//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.use crate::assets::{- is_fetchable_src_attr, is_image_ref_attr, is_media_src_attr, IMAGE_REF_ATTR_PREFIX,+ is_fetchable_image_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;-use crate::context::Ctx;+use crate::context::{Ctx, ImageSource};use crate::css;use crate::dom::{classify_tag, data_attr_looks_sensitive, is_data_attr, is_url_attr, is_user_text_attr,@@ -28,6 +28,7 @@ use crate::dom::{use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL};use crate::images::ImageFallback;use crate::scan::{self, Span};+use crate::srcset::largest_candidate;use crate::text::{redact_emails, scrub_text};use crate::url::scrub_url;@@ -718,7 +719,6 @@ impl<'c, 'a> Walker<'c, 'a> {_ => String::new(),};let kind = classify_tag(&tag);- let tag_src_is_image = crate::assets::tag_src_is_image(&tag);let node_changed = self.changed != changed_before;match ty {@@ -736,10 +736,27 @@ impl<'c, 'a> Walker<'c, 'a> {})?;out.splice(seg.0..seg.1, tmp.iter().copied());}+ if tag.eq_ignore_ascii_case("picture") {+ if let Some((seg, _, src)) = children {+ let mut tmp = Vec::with_capacity(src.1 - src.0);+ self.walk_array(src.0, &mut tmp, &mut |w, p, o| {+ w.walk_node(p, ParentKind::Picture, o)+ })?;+ out.splice(seg.0..seg.1, tmp.iter().copied());+ }+ }// Attributes with the real tag kind (media blur vs plain scrubs).if let Some((key, v)) = attrs_m {+ if self.find_member(v.0, b"style").ok()?.is_some()+ || self+ .find_member(v.0, css::INLINED_STYLESHEET_ATTR.as_bytes())+ .ok()?+ .is_some()+ {+ return self.redo_node(start, end, parent, node_mark, out);+ }emit_deferred_key(bytes, key, &mut emitted, out);- self.walk_attrs(v.0, kind, tag_src_is_image, out)?;+ self.walk_attrs(v.0, kind, &tag, parent == ParentKind::Picture, out)?;}for (key, v) in [ty_m, tag_m, is_style_m, text_m].into_iter().flatten() {emit_deferred_key(bytes, key, &mut emitted, out);@@ -763,13 +780,12 @@ impl<'c, 'a> Walker<'c, 'a> {|| is_style_m.map(|(_, v)| bytes.get(v.0..v.1) == Some(b"true")).unwrap_or(false));+ if styled && text_m.is_some() {+ return self.redo_node(start, end, parent, node_mark, out);+ }if let Some((key, v)) = text_m {emit_deferred_key(bytes, key, &mut emitted, out);- if styled {- self.scrub_string_value(v.0, out, |w, s| css::rewrite(w.ctx, s))?;- } else {- self.scrub_string_value(v.0, out, |w, s| scrub_text(w.ctx.allow, s))?;- }+ self.scrub_string_value(v.0, out, |w, s| scrub_text(w.ctx.allow, s))?;}for (key, v) in [ty_m, tag_m, is_style_m, attrs_m].into_iter().flatten() {emit_deferred_key(bytes, key, &mut emitted, out);@@ -833,7 +849,8 @@ impl<'c, 'a> Walker<'c, 'a> {&mut self,start: usize,kind: TagKind,- tag_src_is_image: bool,+ tag: &str,+ parent_is_picture: bool,out: &mut Vec<u8>,) -> Option<usize> {if self.bytes.get(start) != Some(&b'{') {@@ -851,18 +868,22 @@ impl<'c, 'a> Walker<'c, 'a> {return None;}if kind == TagKind::Media && is_media_src_attr(name) {- return w.blur_media_src(name, vstart, tag_src_is_image, out, stashes);+ return w.blur_media_src(name, vstart, tag, parent_is_picture, out, stashes);}if name == INLINE_IMAGE_ATTR {return w.scrub_string_value(vstart, out, |w, s| {if !is_image_data_uri(s) {return None;}- Some(w.ctx.scrub_image(s, ImageFallback::Blank))+ Some(w.ctx.scrub_image_from(+ s,+ ImageFallback::Blank,+ ImageSource::HtmlAttribute(INLINE_IMAGE_ATTR),+ ))});}if name == "style" || name == css::INLINED_STYLESHEET_ATTR {- return w.scrub_string_value(vstart, out, |w, s| css::rewrite(w.ctx, s));+ return None;}if is_url_attr(name) {return w.scrub_string_value(vstart, out, |w, s| scrub_url(w.ctx, s));@@ -906,7 +927,8 @@ impl<'c, 'a> Walker<'c, 'a> {&mut self,name: &str,vstart: usize,- tag_src_is_image: bool,+ tag: &str,+ parent_is_picture: bool,out: &mut Vec<u8>,stashes: &mut Vec<(String, String)>,) -> Option<usize> {@@ -922,14 +944,32 @@ impl<'c, 'a> Walker<'c, 'a> {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);+ let selected = if name == "srcset" {+ largest_candidate(existing.as_ref()).map(str::to_string)+ } else {+ Some(existing.into_owned())+ };+ let Some(selected) = selected else {+ scan::write_json_string(PLACEHOLDER_SRC, out);+ self.changed = true;+ return Some(end);+ };+ let property = MEDIA_SRC_ATTRS.iter().copied().find(|attr| *attr == name)?;+ if is_image_data_uri(&selected) {+ let blurred = self.ctx.scrub_image_from(+ &selected,+ ImageFallback::Placeholder,+ ImageSource::HtmlAttribute(property),+ );scan::write_json_string(&blurred, out);} else {- let collected = is_fetchable_src_attr(name, tag_src_is_image)- .then(|| self.ctx.collect_url(&existing))+ let collected = is_fetchable_image_attr(name, tag, parent_is_picture)+ .then(|| {+ self.ctx+ .collect_url_from(&selected, ImageSource::HtmlAttribute(property))+ }).flatten();- let scrubbed = scrub_url(self.ctx, &existing).unwrap_or_else(|| existing.into_owned());+ let scrubbed = scrub_url(self.ctx, &selected).unwrap_or_else(|| selected.clone());scan::write_json_string(PLACEHOLDER_SRC, out);if let Some(url_ref) = collected {stashes.push((format!("{IMAGE_REF_ATTR_PREFIX}{name}"), url_ref));@@ -987,7 +1027,7 @@ impl<'c, 'a> Walker<'c, 'a> {};// Mutation attributes carry no tag, so a `src` here is not known to be// an image. Decline rather than guess.- w.walk_attrs(vstart, kind, false, out)+ w.walk_attrs(vstart, kind, "", false, out)}_ => w.copy_value(vstart, out),},diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 86c50a364394..1c1924bc4ca2 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -6,14 +6,17 @@//! message). Scope is one `anonymize_message` call; the map is dropped when it returns.use std::cell::{Cell, RefCell};-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap};use anyhow::{bail, Result};+use serde::Serialize;use crate::allow_lists::AllowLists;use crate::assets::PLACEHOLDER_SRC;use crate::blur::{blank_image_data_uri, blur_image_data_uri, pixelate_raw_rgba};-use crate::collect::{collectable_data_uri_bytes, CollectedImage, ImageCollection, ImageCollector};+use crate::collect::{+ collectable_data_uri_bytes, is_image_ref, CollectedImage, ImageCollection, ImageCollector,+};use crate::images::{ImageFallback, ImagePolicy, ImageQueue};use crate::timings::PhaseTimings;use crate::url_collect::{CollectedUrl, UrlCollection, UrlCollector};@@ -23,6 +26,20 @@ use crate::url_collect::{CollectedUrl, UrlCollection, UrlCollector};/// fields can't decompress gigabytes serially. Real messages total under 10 MB.const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub(crate) enum ImageSource {+ CssProperty(&'static str),+ HtmlAttribute(&'static str),+}++#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct ImageSourceCount {+ pub source: &'static str,+ pub property: &'static str,+ pub kind: &'static str,+ 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.pub struct Ctx<'a> {@@ -39,6 +56,7 @@ pub struct Ctx<'a> {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>>,+ image_source_counts: RefCell<BTreeMap<(ImageSource, &'static str), u32>>,// 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,@@ -77,6 +95,7 @@ impl<'a> Ctx<'a> {images: ImageQueue::default(),collector: image_collection.map(|c| RefCell::new(ImageCollector::new(c))),url_collector: None,+ image_source_counts: RefCell::new(BTreeMap::new()),preserve_image_refs: false,}}@@ -124,6 +143,19 @@ impl<'a> Ctx<'a> {}}+ pub(crate) fn scrub_image_from(+ &self,+ original: &str,+ fallback: ImageFallback,+ source: ImageSource,+ ) -> String {+ let scrubbed = self.scrub_image(original, fallback);+ if is_image_ref(&scrubbed) {+ self.record_image_source(source, "inline");+ }+ scrubbed+ }+pub(crate) fn has_pending_images(&self) -> bool {self.images.has_pending()}@@ -163,6 +195,37 @@ impl<'a> Ctx<'a> {collector.borrow_mut().collect(original)}+ pub(crate) fn collect_url_from(&self, original: &str, source: ImageSource) -> Option<String> {+ let reference = self.collect_url(original)?;+ self.record_image_source(source, "url");+ Some(reference)+ }++ fn record_image_source(&self, source: ImageSource, kind: &'static str) {+ let mut counts = self.image_source_counts.borrow_mut();+ let count = counts.entry((source, kind)).or_default();+ *count = count.saturating_add(1);+ }++ pub fn take_image_source_counts(&self) -> Vec<ImageSourceCount> {+ let counts = std::mem::take(&mut *self.image_source_counts.borrow_mut());+ counts+ .into_iter()+ .map(|((source, kind), count)| {+ let (source, property) = match source {+ ImageSource::CssProperty(property) => ("css", property),+ ImageSource::HtmlAttribute(property) => ("html", property),+ };+ ImageSourceCount {+ source,+ property,+ kind,+ count,+ }+ })+ .collect()+ }+/// Drain the collected URLs (hash-sorted). Empty when URL collection was off.////// Takes the collector rather than `self`, because the caller drains the images afterwards anddiff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rsindex 1508210dd801..2bf9c6b77942 100644--- a/rust/replay-anonymizer/src/css.rs+++ b/rust/replay-anonymizer/src/css.rs@@ -1,52 +1,104 @@-//! Blur inline `url(data:image/...;base64,...)` backgrounds in CSS, using a single linear-//! left-to-right scan (no backtracking regex). `None` means "unchanged".-use std::borrow::Cow;+use std::collections::BTreeMap;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::context::Ctx;+use crate::collect::{is_image_ref, is_image_ref_strict};+use crate::context::{Ctx, ImageSource};use crate::images::ImageFallback;use crate::json::{as_array_mut, as_object_mut, as_str, string_value};-// rrweb inlines a same-origin/CORS-readable `<link rel="stylesheet">` into this attribute-// at snapshot time, so it holds full stylesheet text and needs the same CSS treatment as `style`.pub const INLINED_STYLESHEET_ATTR: &str = "_cssText";-/// Scrub `container[key]` if it is a CSS string; returns whether it changed.-pub fn scrub_css_images(ctx: &Ctx<'_>, container: &mut Object<'_>, key: &str) -> bool {+#[derive(Clone, Copy)]+pub enum CssContext<'a> {+ DeclarationList,+ Property(&'a str),+ Stylesheet,+}++pub struct CssRewrite {+ pub css: String,+ pub refs: BTreeMap<String, String>,+}++struct DeclarationRange {+ start: usize,+ end: usize,+ property: &'static str,+ collect_remote_urls: bool,+}++struct UrlFunctionScan {+ resume_at: usize,+ source: Option<String>,+}++const OTHER_CSS_PROPERTY: &str = "other";+const CUSTOM_CSS_PROPERTY: &str = "custom-property";++pub fn is_strict_css_refs(value: &Value<'_>) -> bool {+ let Some(encoded) = as_str(value) else {+ return false;+ };+ let Ok(refs) = serde_json::from_str::<BTreeMap<String, String>>(encoded) else {+ return false;+ };+ !refs.is_empty()+ && refs+ .values()+ .all(|reference| is_image_ref_strict(reference))+ && (0..refs.len()).all(|slot| refs.contains_key(&slot.to_string()))+}++pub fn scrub_css_images(+ ctx: &Ctx<'_>,+ container: &mut Object<'_>,+ key: &str,+ context: CssContext<'_>,+) -> bool {let Some(css) = container.get(key).and_then(as_str).map(str::to_string) else {return false;};- match rewrite(ctx, &css) {- Some(v) => {- container.insert(Cow::Owned(key.to_string()), string_value(v));- true- }- None => false,+ let Some(rewrite) = rewrite(ctx, &css, context) else {+ return false;+ };+ container.insert(Cow::Owned(key.to_string()), string_value(rewrite.css));+ if !rewrite.refs.is_empty() {+ let encoded = serde_json::to_string(&rewrite.refs).expect("string map serializes");+ container.insert(+ Cow::Owned(format!("{CSS_IMAGE_REFS_ATTR_PREFIX}{key}")),+ string_value(encoded),+ );}+ true}-/// rrweb StyleSheetRule (source 8): CSS lives in `adds[].rule` and whole-sheet `replace`/`replaceSync`.pub fn scrub_style_sheet_rule(ctx: &Ctx<'_>, data: &mut Object<'_>) -> bool {- let mut changed = scrub_css_images(ctx, data, "replace");- changed |= scrub_css_images(ctx, data, "replaceSync");+ let mut changed = scrub_css_images(ctx, data, "replace", CssContext::Stylesheet);+ changed |= scrub_css_images(ctx, data, "replaceSync", CssContext::Stylesheet);if let Some(adds) = data.get_mut("adds").and_then(as_array_mut) {changed |= scrub_rule_list(ctx, adds);}changed}-/// rrweb StyleDeclaration (source 13): CSS value lives in `set.value`.pub fn scrub_style_declaration(ctx: &Ctx<'_>, data: &mut Object<'_>) -> bool {- match data.get_mut("set").and_then(as_object_mut) {- Some(set) => scrub_css_images(ctx, set, "value"),- None => false,- }+ let Some(set) = data.get_mut("set").and_then(as_object_mut) else {+ return false;+ };+ let property = set+ .get("property")+ .and_then(as_str)+ .unwrap_or("")+ .to_string();+ scrub_css_images(ctx, set, "value", CssContext::Property(&property))}-/// rrweb AdoptedStyleSheet (source 15): CSS lives in `styles[].rules[].rule`.pub fn scrub_adopted_style_sheet(ctx: &Ctx<'_>, data: &mut Object<'_>) -> bool {let Some(styles) = data.get_mut("styles").and_then(as_array_mut) else {return false;@@ -66,138 +118,703 @@ fn scrub_rule_list(ctx: &Ctx<'_>, rules: &mut Vec<Value<'_>>) -> bool {let mut changed = false;for rule in rules.iter_mut() {if let Some(rule) = as_object_mut(rule) {- changed |= scrub_css_images(ctx, rule, "rule");+ changed |= scrub_css_images(ctx, rule, "rule", CssContext::Stylesheet);}}changed}-pub(crate) fn rewrite(ctx: &Ctx<'_>, css: &str) -> Option<String> {- let bytes = css.as_bytes();- let mut out = String::new();- let mut last = 0usize;- let mut i = 0usize;+pub(crate) fn rewrite(ctx: &Ctx<'_>, css: &str, context: CssContext<'_>) -> Option<CssRewrite> {+ let ranges = declaration_value_ranges(css, context);+ let mut refs = BTreeMap::new();+ let mut output = String::with_capacity(css.len());+ let mut copied_to = 0;let mut changed = false;- while let Some(start) = find_url_open(bytes, i) {- if let Some(m) = parse_url_data_image(bytes, start) {- out.push_str(&css[last..start]);- // Blur (or fall back to a blank pixel) and re-wrap; no async placeholder needed since we- // resolve the image inline, so the final string matches the TS post-blur state.- let replacement = ctx.scrub_image(&css[m.data_start..m.data_end], ImageFallback::Blank);- out.push_str("url(");- if let Some(q) = m.quote {- out.push(q as char);+ for range in ranges {+ let (rewritten, value_changed) = rewrite_value(+ ctx,+ &css[copied_to..range.start],+ OTHER_CSS_PROPERTY,+ false,+ &mut refs,+ );+ output.push_str(&rewritten);+ changed |= value_changed;+ let (rewritten, value_changed) = rewrite_value(+ ctx,+ &css[range.start..range.end],+ range.property,+ range.collect_remote_urls,+ &mut refs,+ );+ output.push_str(&rewritten);+ copied_to = range.end;+ changed |= value_changed;+ }+ let (rewritten, value_changed) =+ rewrite_value(ctx, &css[copied_to..], OTHER_CSS_PROPERTY, false, &mut refs);+ output.push_str(&rewritten);+ changed |= value_changed;+ if !changed {+ return None;+ }+ Some(CssRewrite { css: output, refs })+}++fn declaration_value_ranges(css: &str, context: CssContext<'_>) -> Vec<DeclarationRange> {+ if let CssContext::Property(property) = context {+ return css_property(property)+ .map(|(property, collect_remote_urls)| DeclarationRange {+ start: 0,+ end: css.len(),+ property,+ collect_remote_urls,+ })+ .into_iter()+ .collect();+ }++ let bytes = css.as_bytes();+ let mut ranges = Vec::new();+ let mut segment_start = 0;+ let mut brace_depth = 0usize;+ let mut paren_depth = 0usize;+ let mut bracket_depth = 0usize;+ let mut position = 0;+ while position < bytes.len() {+ if starts_with(bytes, position, b"/*") {+ position = skip_comment(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ if matches!(bytes[position], b'\'' | b'"') {+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ match bytes[position] {+ b'(' => paren_depth += 1,+ b')' => paren_depth = paren_depth.saturating_sub(1),+ b'[' => bracket_depth += 1,+ b']' => bracket_depth = bracket_depth.saturating_sub(1),+ b'{' if paren_depth == 0 && bracket_depth == 0 => {+ brace_depth += 1;+ segment_start = position + 1;}- out.push_str(&replacement);- if let Some(q) = m.quote {- out.push(q as char);+ b'}' if paren_depth == 0 && bracket_depth == 0 => {+ brace_depth = brace_depth.saturating_sub(1);+ segment_start = position + 1;}- out.push(')');- last = m.end;- i = m.end;- changed = true;- } else {- i = start + 1;+ b';' if paren_depth == 0 && bracket_depth == 0 => {+ segment_start = position + 1;+ }+ b':' if paren_depth == 0 && bracket_depth == 0 => {+ if let Some((property, collect_remote_urls)) =+ css_property(css[segment_start..position].trim())+ {+ ranges.push(DeclarationRange {+ start: position + 1,+ end: declaration_end(bytes, position + 1, brace_depth),+ property,+ collect_remote_urls,+ });+ }+ }+ _ => {}}+ position += 1;}- if !changed {- return None;+ ranges+}++fn css_property(property: &str) -> Option<(&'static str, bool)> {+ image_property(property)+ .map(|property| (property, true))+ .or_else(|| {+ property+ .trim()+ .starts_with("--")+ .then_some((CUSTOM_CSS_PROPERTY, false))+ })+}++fn declaration_end(bytes: &[u8], start: usize, brace_depth: usize) -> usize {+ let mut position = start;+ let mut paren_depth = 0usize;+ let mut bracket_depth = 0usize;+ while position < bytes.len() {+ if starts_with(bytes, position, b"/*") {+ position = skip_comment(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ if matches!(bytes[position], b'\'' | b'"') {+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ match bytes[position] {+ b'(' => paren_depth += 1,+ b')' => paren_depth = paren_depth.saturating_sub(1),+ b'[' => bracket_depth += 1,+ b']' => bracket_depth = bracket_depth.saturating_sub(1),+ b';' if paren_depth == 0 && bracket_depth == 0 => return position,+ b'}' if paren_depth == 0 && bracket_depth == 0 && brace_depth > 0 => return position,+ _ => {}+ }+ position += 1;}- out.push_str(&css[last..]);- Some(out)+ bytes.len()}-struct Match {- end: usize,- quote: Option<u8>,- data_start: usize,- data_end: usize,-}--fn find_url_open(bytes: &[u8], from: usize) -> Option<usize> {- let mut i = from;- while i + 4 <= bytes.len() {- if bytes[i].eq_ignore_ascii_case(&b'u')- && bytes[i + 1].eq_ignore_ascii_case(&b'r')- && bytes[i + 2].eq_ignore_ascii_case(&b'l')- && bytes[i + 3] == b'('+fn image_property(property: &str) -> Option<&'static str> {+ match property.trim().to_ascii_lowercase().as_str() {+ "background" => Some("background"),+ "background-image" => Some("background-image"),+ "border-image" => Some("border-image"),+ "border-image-source" => Some("border-image-source"),+ "content" => Some("content"),+ "cursor" => Some("cursor"),+ "list-style" => Some("list-style"),+ "list-style-image" => Some("list-style-image"),+ "mask" => Some("mask"),+ "mask-border" => Some("mask-border"),+ "mask-border-source" => Some("mask-border-source"),+ "mask-image" => Some("mask-image"),+ "shape-outside" => Some("shape-outside"),+ "symbols" => Some("symbols"),+ "-webkit-border-image" => Some("-webkit-border-image"),+ "-webkit-border-image-source" => Some("-webkit-border-image-source"),+ "-webkit-box-reflect" => Some("-webkit-box-reflect"),+ "-webkit-mask" => Some("-webkit-mask"),+ "-webkit-mask-box-image" => Some("-webkit-mask-box-image"),+ "-webkit-mask-box-image-source" => Some("-webkit-mask-box-image-source"),+ "-webkit-mask-image" => Some("-webkit-mask-image"),+ _ => None,+ }+}++fn rewrite_value(+ ctx: &Ctx<'_>,+ value: &str,+ property: &'static str,+ collect_remote_urls: bool,+ refs: &mut BTreeMap<String, String>,+) -> (String, bool) {+ let bytes = value.as_bytes();+ let mut output = String::with_capacity(value.len());+ let mut copied_to = 0;+ let mut position = 0;+ let mut changed = false;+ while position < bytes.len() {+ if starts_with(bytes, position, b"/*") {+ position = skip_comment(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ if matches!(bytes[position], b'\'' | b'"') {+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());+ continue;+ }+ if function_at(bytes, position, b"image-set")+ || function_at(bytes, position, b"-webkit-image-set"){- return Some(i);+ let name_len = if bytes[position] == b'-' {+ b"-webkit-image-set".len()+ } else {+ b"image-set".len()+ };+ let open = position + name_len;+ let Some(end) = matching_paren(bytes, open) else {+ break;+ };+ let contents = &value[open + 1..end - 1];+ let selected = select_image_set_candidate(contents);+ let replacement = if collect_remote_urls {+ Some(+ selected+ .as_deref()+ .and_then(|source| {+ replacement_url(ctx, source, property, collect_remote_urls, refs)+ })+ .unwrap_or_else(|| format!("url(\"{PLACEHOLDER_SRC}\")")),+ )+ } else if image_set_contains_inline_image(contents) {+ Some(+ selected+ .as_deref()+ .filter(|source| is_image_data_uri(source))+ .and_then(|source| {+ replacement_url(ctx, source, property, collect_remote_urls, refs)+ })+ .unwrap_or_else(|| format!("url(\"{PLACEHOLDER_SRC}\")")),+ )+ } else {+ None+ };+ if let Some(replacement) = replacement {+ output.push_str(&value[copied_to..position]);+ output.push_str(&replacement);+ copied_to = end;+ changed = true;+ }+ position = end;+ continue;}- i += 1;+ if function_at(bytes, position, b"url") {+ let start = position;+ let UrlFunctionScan { resume_at, source } = scan_url_function(value, start);+ position = resume_at;+ let Some(source) = source else {+ continue;+ };+ let original = &value[start..resume_at];+ if let Some(replacement) =+ replacement_url(ctx, &source, property, collect_remote_urls, refs)+ {+ if replacement != original {+ output.push_str(&value[copied_to..start]);+ output.push_str(&replacement);+ copied_to = resume_at;+ changed = true;+ }+ }+ continue;+ }+ position += 1;}- None+ if !changed {+ return (value.to_string(), false);+ }+ output.push_str(&value[copied_to..]);+ (output, true)}-fn parse_url_data_image(bytes: &[u8], start: usize) -> Option<Match> {- let mut pos = start + 4; // past "url("- skip_ws(bytes, &mut pos);- let quote = match bytes.get(pos) {- Some(&c) if c == b'\'' || c == b'"' => {- pos += 1;- Some(c)+fn replacement_url(+ ctx: &Ctx<'_>,+ source: &str,+ property: &'static str,+ collect_remote_urls: bool,+ refs: &mut BTreeMap<String, String>,+) -> Option<String> {+ let source = source.trim();+ if source == PLACEHOLDER_SRC || is_numbered_placeholder(source) {+ return Some(format!("url(\"{source}\")"));+ }+ if source.starts_with('#') {+ return collect_remote_urls.then(|| format!("url(\"{source}\")"));+ }+ if ctx.keeps_image_refs() && is_image_ref_strict(source) {+ return collect_remote_urls.then(|| format!("url(\"{source}\")"));+ }+ let reference = if is_image_data_uri(source) {+ let replacement = ctx.scrub_image_from(+ source,+ ImageFallback::Blank,+ ImageSource::CssProperty(property),+ );+ if is_image_ref(&replacement) {+ Some(replacement)+ } else {+ return Some(format!("url(\"{replacement}\")"));}- _ => None,- };- let data_start = pos;- if !starts_with_ci(bytes, pos, b"data:image/") {+ } else if !collect_remote_urls {return None;+ } else if source.contains('\\') {+ None+ } else {+ ctx.collect_url_from(source, ImageSource::CssProperty(property))+ };+ match reference {+ Some(reference) => {+ let slot = refs.len();+ refs.insert(slot.to_string(), reference);+ Some(format!("url(\"{}\")", numbered_placeholder(slot)))+ }+ None => Some(format!("url(\"{PLACEHOLDER_SRC}\")")),}- pos += b"data:image/".len();- // subtype: [a-z0-9.+-]+ (case-insensitive)- let subtype_start = pos;- while matches!(bytes.get(pos), Some(&c) if c.is_ascii_alphanumeric() || matches!(c, b'.' | b'+' | b'-'))- {- pos += 1;+}++fn scan_url_function(value: &str, start: usize) -> UrlFunctionScan {+ let bytes = value.as_bytes();+ let Some(resume_at) = matching_paren(bytes, start + 3) else {+ return UrlFunctionScan {+ resume_at: bytes.len(),+ source: None,+ };+ };+ let contents_end = resume_at - 1;+ let mut position = start + 4;+ skip_whitespace(bytes, &mut position);+ let source = if matches!(bytes.get(position), Some(b'\'' | b'"')) {+ let content_start = position + 1;+ let Some(end) = skip_quoted(bytes, position) else {+ return UrlFunctionScan {+ resume_at,+ source: None,+ };+ };+ let content_end = end - 1;+ position = end;+ skip_whitespace(bytes, &mut position);+ if position != contents_end {+ return UrlFunctionScan {+ resume_at,+ source: None,+ };+ }+ &value[content_start..content_end]+ } else {+ &value[position..contents_end]+ };+ let source = source.trim();+ UrlFunctionScan {+ resume_at,+ source: (!source.is_empty() && !source.as_bytes().contains(&b'\\'))+ .then(|| source.to_string()),}- if pos == subtype_start {- return None;+}++fn select_image_set_candidate(contents: &str) -> Option<String> {+ let mut best: Option<(f64, String)> = None;+ for candidate in split_image_set_candidates(contents)? {+ let (source, remainder) = parse_image_set_source(candidate.trim())?;+ let resolution = parse_resolution(remainder)?;+ if best+ .as_ref()+ .is_none_or(|(best_resolution, _)| resolution > *best_resolution)+ {+ best = Some((resolution, source));+ }}- if !starts_with_ci(bytes, pos, b";base64,") {- return None;+ best.map(|(_, source)| source)+}++fn image_set_contains_inline_image(contents: &str) -> bool {+ split_image_set_candidates(contents).is_some_and(|candidates| {+ candidates.into_iter().any(|candidate| {+ parse_image_set_source(candidate.trim())+ .is_some_and(|(source, _)| is_image_data_uri(&source))+ })+ })+}++fn split_image_set_candidates(contents: &str) -> Option<Vec<&str>> {+ let bytes = contents.as_bytes();+ let mut candidates = Vec::new();+ let mut start = 0;+ let mut position = 0;+ let mut depth = 0usize;+ while position < bytes.len() {+ if starts_with(bytes, position, b"/*") {+ position = skip_comment(bytes, position)?;+ continue;+ }+ if matches!(bytes[position], b'\'' | b'"') {+ position = skip_quoted(bytes, position)?;+ continue;+ }+ match bytes[position] {+ b'(' => depth += 1,+ b')' => depth = depth.saturating_sub(1),+ b',' if depth == 0 => {+ candidates.push(&contents[start..position]);+ start = position + 1;+ }+ _ => {}+ }+ position += 1;}- pos += b";base64,".len();- // base64 body: [A-Za-z0-9+/=]+- let b64_start = pos;- while matches!(bytes.get(pos), Some(&c) if c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='))- {- pos += 1;+ candidates.push(&contents[start..]);+ (!candidates+ .iter()+ .any(|candidate| candidate.trim().is_empty()))+ .then_some(candidates)+}++fn parse_image_set_source(candidate: &str) -> Option<(String, &str)> {+ let bytes = candidate.as_bytes();+ if function_at(bytes, 0, b"url") {+ let UrlFunctionScan { resume_at, source } = scan_url_function(candidate, 0);+ return Some((source?, &candidate[resume_at..]));}- if pos == b64_start {- return None;+ if matches!(bytes.first(), Some(b'\'' | b'"')) {+ let end = skip_quoted(bytes, 0)?;+ let source = candidate[1..end - 1].to_string();+ if source.as_bytes().contains(&b'\\') {+ return None;+ }+ return Some((source, &candidate[end..]));}- let data_end = pos;- if let Some(q) = quote {- if bytes.get(pos) != Some(&q) {+ None+}++fn parse_resolution(remainder: &str) -> Option<f64> {+ let mut resolution = None;+ for token in remainder.split_ascii_whitespace() {+ let parsed = if let Some(value) = token.strip_suffix("dppx") {+ value.parse::<f64>().ok()+ } else if let Some(value) = token.strip_suffix("dpi") {+ value.parse::<f64>().ok().map(|value| value / 96.0)+ } else if let Some(value) = token.strip_suffix("dpcm") {+ value.parse::<f64>().ok().map(|value| value * 2.54 / 96.0)+ } else if let Some(value) = token.strip_suffix('x') {+ value.parse::<f64>().ok()+ } else if token.starts_with("type(") {+ continue;+ } else {+ return None;+ };+ let value = parsed?;+ if resolution.replace(value).is_some() {return None;}- pos += 1;}- skip_ws(bytes, &mut pos);- if bytes.get(pos) != Some(&b')') {+ let value = resolution.unwrap_or(1.0);+ (value.is_finite() && value > 0.0).then_some(value)+}++fn function_at(bytes: &[u8], start: usize, name: &[u8]) -> bool {+ let Some(candidate) = bytes.get(start..start + name.len()) else {+ return false;+ };+ candidate.eq_ignore_ascii_case(name)+ && bytes.get(start + name.len()) == Some(&b'(')+ && (start == 0+ || !matches!(bytes[start - 1], b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-'))+}++fn matching_paren(bytes: &[u8], open: usize) -> Option<usize> {+ if bytes.get(open) != Some(&b'(') {return None;}- pos += 1;- // Only images (data URIs); guaranteed by the `data:image/` prefix above.- debug_assert!(is_image_data_uri(- std::str::from_utf8(&bytes[data_start..data_end]).unwrap_or("")- ));- Some(Match {- end: pos,- quote,- data_start,- data_end,- })+ let mut position = open + 1;+ let mut depth = 1usize;+ while position < bytes.len() {+ if starts_with(bytes, position, b"/*") {+ position = skip_comment(bytes, position)?;+ continue;+ }+ if matches!(bytes[position], b'\'' | b'"') {+ position = skip_quoted(bytes, position)?;+ continue;+ }+ match bytes[position] {+ b'(' => depth += 1,+ b')' => {+ depth -= 1;+ if depth == 0 {+ return Some(position + 1);+ }+ }+ _ => {}+ }+ position += 1;+ }+ None+}++fn skip_quoted(bytes: &[u8], start: usize) -> Option<usize> {+ let quote = *bytes.get(start)?;+ let mut position = start + 1;+ while position < bytes.len() {+ match bytes[position] {+ b'\\' => position += 2,+ value if value == quote => return Some(position + 1),+ _ => position += 1,+ }+ }+ None}-fn skip_ws(bytes: &[u8], pos: &mut usize) {- while matches!(bytes.get(*pos), Some(&c) if c.is_ascii_whitespace() || c == 0x0b) {- *pos += 1;+fn skip_comment(bytes: &[u8], start: usize) -> Option<usize> {+ let relative = bytes+ .get(start + 2..)?+ .windows(2)+ .position(|pair| pair == b"*/")?;+ Some(start + 2 + relative + 2)+}++fn skip_whitespace(bytes: &[u8], position: &mut usize) {+ while matches!(bytes.get(*position), Some(value) if value.is_ascii_whitespace()) {+ *position += 1;}}-fn starts_with_ci(bytes: &[u8], pos: usize, needle: &[u8]) -> bool {- bytes- .get(pos..pos + needle.len())- .is_some_and(|s| s.eq_ignore_ascii_case(needle))+fn starts_with(bytes: &[u8], start: usize, needle: &[u8]) -> bool {+ bytes.get(start..start + needle.len()) == Some(needle)+}++#[cfg(test)]+mod tests {+ use super::{rewrite, CssContext};+ use crate::allow_lists::AllowLists;+ use crate::collect::ImageCollection;+ use crate::context::{Ctx, ImageSourceCount};+ use crate::testkit::png_data_uri;+ use crate::url_collect::UrlCollection;++ #[test]+ fn remote_urls_use_valid_placeholders() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let css = "color:red;background-image:url('https://example.com/a.png');mask-image:url(https://example.com/b.png);content:url(\"https://example.com/<metadata id='anon-image-slot-7'/>\")";+ let rewritten = rewrite(&ctx, css, CssContext::DeclarationList).expect("images change");+ assert!(rewritten.refs.is_empty());+ assert_eq!(rewritten.css.matches("data:image/svg+xml").count(), 3);+ assert!(!rewritten.css.contains("https://example.com"));+ }++ #[test]+ fn non_image_css_urls_are_left_alone() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let css = "@import url('https://example.com/a.css');@font-face{src:url('https://example.com/a.woff2')}";+ assert!(rewrite(&ctx, css, CssContext::Stylesheet).is_none());+ }++ #[test]+ fn inline_images_still_use_the_inline_scrubber() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let original = png_data_uri(8, 8, [10, 20, 30, 255]);+ let css = format!("background-image:url('{original}')");+ let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");+ assert!(!rewritten.css.contains(&original));+ assert!(rewritten.css.contains("data:image/"));+ }++ #[test]+ fn escaped_url_does_not_stop_later_inline_image_scrubbing() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let original = png_data_uri(8, 8, [10, 20, 30, 255]);+ let escaped_url = r#"url("https://example.com/a\2e png")"#;+ let css = format!("background-image:{escaped_url},url('{original}')");+ let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");+ assert!(rewritten.css.contains(escaped_url));+ assert!(!rewritten.css.contains(&original));+ }++ #[test]+ fn repeated_unterminated_urls_do_not_rescan_the_suffix() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let css = format!("background-image:{}", "url(".repeat(20_000));+ assert!(rewrite(&ctx, &css, CssContext::DeclarationList).is_none());+ }++ #[test]+ fn collected_inline_images_use_numbered_placeholders() {+ let allow = AllowLists::default();+ let ctx = Ctx::with_image_collection(+ &allow,+ Some(ImageCollection {+ pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),+ content_key: "fedcba9876543210fedcba9876543210".to_string(),+ }),+ );+ let original = png_data_uri(8, 8, [10, 20, 30, 255]);+ let css = format!("background-image:url('{original}')");+ let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");+ assert!(rewritten.css.contains("anon-image-slot-0"));+ assert_eq!(rewritten.refs.len(), 1);+ assert!(rewritten.refs["0"].starts_with("image:"));+ assert_eq!(+ ctx.take_image_source_counts(),+ vec![ImageSourceCount {+ source: "css",+ property: "background-image",+ kind: "inline",+ count: 1,+ }]+ );+ }++ #[test]+ fn custom_properties_scrub_inline_images_without_collecting_remote_urls() {+ let allow = AllowLists::default();+ let ctx = Ctx::with_image_collection(+ &allow,+ Some(ImageCollection {+ pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),+ content_key: "fedcba9876543210fedcba9876543210".to_string(),+ }),+ )+ .collecting_urls(Some(UrlCollection {+ url_key: "0123456789abcdef0123456789abcdef".to_string(),+ }));+ let original = png_data_uri(8, 8, [10, 20, 30, 255]);+ let remote = "https://cdn.example.com/hero.png";+ let css = format!("--hero:url('{original}');--hero-set:image-set('{original}' 2x);--remote:url('{remote}');background-image:var(--hero)");+ let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");+ assert!(!rewritten.css.contains(&original));+ assert!(rewritten.css.contains("anon-image-slot-0"));+ assert!(rewritten.css.contains("anon-image-slot-1"));+ assert!(rewritten.css.contains(remote));+ assert_eq!(rewritten.refs.len(), 2);+ assert!(rewritten.refs["0"].starts_with("image:"));+ assert!(rewritten.refs["1"].starts_with("image:"));+ assert_eq!(+ ctx.take_image_source_counts(),+ vec![ImageSourceCount {+ source: "css",+ property: "custom-property",+ kind: "inline",+ count: 2,+ }]+ );+ }++ #[test]+ fn collected_remote_images_record_the_css_property() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow).collecting_urls(Some(UrlCollection {+ url_key: "0123456789abcdef0123456789abcdef".to_string(),+ }));+ let css = "mask-image:url('https://cdn.example.com/mask.png')";+ let rewritten = rewrite(&ctx, css, CssContext::DeclarationList).expect("image changes");+ assert!(rewritten.refs["0"].starts_with("imageurl:"));+ assert_eq!(+ ctx.take_image_source_counts(),+ vec![ImageSourceCount {+ source: "css",+ property: "mask-image",+ kind: "url",+ count: 1,+ }]+ );+ }++ #[test]+ fn inline_svg_in_css_stays_out_of_the_collection_lane() {+ let allow = AllowLists::default();+ let ctx = Ctx::with_image_collection(+ &allow,+ Some(ImageCollection {+ pseudo_team: "0123456789abcdef0123456789abcdef".to_string(),+ content_key: "fedcba9876543210fedcba9876543210".to_string(),+ }),+ );+ let original = "data:image/svg+xml;base64,PHN2Zz48dGV4dD5qb2huLmZha2VuYW1lQGV4YW1wbGUuY29tPC90ZXh0Pjwvc3ZnPg==";+ let css = format!("background-image:url('{original}')");+ let rewritten = rewrite(&ctx, &css, CssContext::DeclarationList).expect("image changes");+ assert!(rewritten.refs.is_empty());+ assert!(!rewritten.css.contains(original));+ assert!(rewritten.css.contains("data:image/png;base64"));+ assert!(ctx.take_image_source_counts().is_empty());+ }++ #[test]+ fn image_set_uses_the_largest_candidate() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let css = "background-image:image-set(url('https://example.com/a.png') 1x, url('https://example.com/b.png') 2x)";+ let rewritten = rewrite(&ctx, css, CssContext::DeclarationList).expect("image changes");+ assert_eq!(rewritten.css.matches("data:image/svg+xml").count(), 1);+ assert!(!rewritten.css.contains("example.com"));+ }++ #[test]+ fn strings_and_comments_do_not_create_image_fetches() {+ let allow = AllowLists::default();+ let ctx = Ctx::new(&allow);+ let css = "content:'url(https://example.com/a.png)';background-image:/* url(https://example.com/b.png) */none";+ assert!(rewrite(&ctx, css, CssContext::DeclarationList).is_none());+ }}diff --git a/rust/replay-anonymizer/src/dom.rs b/rust/replay-anonymizer/src/dom.rsindex e5501bb98486..87476c86d0b4 100644--- a/rust/replay-anonymizer/src/dom.rs+++ b/rust/replay-anonymizer/src/dom.rs@@ -6,11 +6,11 @@ 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, INLINE_IMAGE_ATTR,+ is_media_tag, CSS_IMAGE_REFS_ATTR_PREFIX, 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::css::{is_strict_css_refs, scrub_css_images, CssContext, INLINED_STYLESHEET_ATTR};use crate::json::{as_array_mut, as_object_mut, as_small_uint, as_str, is_object, is_true, key, string_value,};@@ -26,6 +26,7 @@ const NODE_COMMENT: u8 = 5;#[derive(Clone, Copy, PartialEq, Eq)]pub(crate) enum ParentKind {+ Picture,Script,Style,Other,@@ -99,7 +100,7 @@ pub fn scrub_mutation_attributes(ctx: &Ctx<'_>, attributes: &mut Vec<Value<'_>>)};// A mutation carries attributes with no tag, so a `src` here could belong to an// iframe or a script as easily as an image. Decline rather than guess.- changed |= scrub_attrs(ctx, attrs, kind, false);+ changed |= scrub_attrs(ctx, attrs, kind, "", false);}}}@@ -135,12 +136,16 @@ pub(crate) fn walk_node(ctx: &Ctx<'_>, node: &mut Value<'_>, parent: ParentKind).to_string();let kind = classify_tag(&tag);if let Some(attrs) = obj.get_mut("attributes").and_then(as_object_mut) {- changed |= scrub_attrs(ctx, attrs, kind, crate::assets::tag_src_is_image(&tag));+ changed |= scrub_attrs(ctx, attrs, kind, &tag, parent == ParentKind::Picture);}- let child_parent = match kind {- TagKind::Script => ParentKind::Script,- TagKind::Style => ParentKind::Style,- TagKind::Media | TagKind::Other => ParentKind::Other,+ let child_parent = if tag.eq_ignore_ascii_case("picture") {+ ParentKind::Picture+ } else {+ match kind {+ TagKind::Script => ParentKind::Script,+ TagKind::Style => ParentKind::Style,+ TagKind::Media | TagKind::Other => ParentKind::Other,+ }};if let Some(children) = obj.get_mut("childNodes").and_then(as_array_mut) {for child in children.iter_mut() {@@ -166,7 +171,7 @@ pub(crate) fn walk_node(ctx: &Ctx<'_>, node: &mut Value<'_>, parent: ParentKind)}let is_style = obj.get("isStyle").map(is_true).unwrap_or(false);if parent == ParentKind::Style || is_style {- return scrub_css_images(ctx, obj, "textContent");+ return scrub_css_images(ctx, obj, "textContent", CssContext::Stylesheet);}changed |= scrub_text_content(ctx, obj);}@@ -208,7 +213,8 @@ fn scrub_attrs(ctx: &Ctx<'_>,attrs: &mut Object<'_>,kind: TagKind,- tag_src_is_image: bool,+ tag: &str,+ parent_is_picture: bool,) -> bool {let mut changed = false;// Plain string scrubs mutate values in place while iterating — no per-element key Vec. Only the@@ -221,7 +227,12 @@ fn scrub_attrs(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);+ let keep = ctx.keeps_image_refs()+ && if name.starts_with(CSS_IMAGE_REFS_ATTR_PREFIX) {+ is_strict_css_refs(value)+ } else {+ as_str(value).is_some_and(is_image_ref_strict)+ };if !keep {rejected_image_refs.push(name.to_string());}@@ -266,13 +277,15 @@ fn scrub_attrs(for name in deferred {if name == INLINE_IMAGE_ATTR {changed |= blur_inline_image_attr(ctx, attrs, &name);+ } else if name == "style" {+ changed |= scrub_css_images(ctx, attrs, &name, CssContext::DeclarationList);} else {- changed |= scrub_css_images(ctx, attrs, &name);+ changed |= scrub_css_images(ctx, attrs, &name, CssContext::Stylesheet);}}if kind == TagKind::Media {- changed |= apply_blur(ctx, attrs, tag_src_is_image);+ changed |= apply_blur(ctx, attrs, tag, parent_is_picture);}changed@@ -373,7 +386,7 @@ mod tests {"the original image must be gone from {attr}");assert!(- scrubbed.contains("url(data:image/png"),+ scrubbed.contains("data:image/png"),"replaced with a data image in {attr}: {scrubbed}");}diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 883dd00399b4..2183c3368ede 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -52,6 +52,8 @@ pub mod json;pub mod scan;pub mod snapshot;#[doc(hidden)]+pub mod srcset;+#[doc(hidden)]pub mod text;pub mod timings;#[cfg(feature = "typed-parse")]diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex eb4eb8db16fa..6946dfca8237 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -28,7 +28,7 @@ use simd_json::prelude::Writable;use crate::allow_lists::AllowLists;use crate::collect::{CollectedImage, ImageCollection};-use crate::context::Ctx;+use crate::context::{Ctx, ImageSourceCount};use crate::event::{route_data, route_event, SOURCE_ADOPTED_STYLESHEET, SOURCE_CANVAS_MUTATION, SOURCE_INPUT,SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,@@ -172,6 +172,9 @@ pub struct SnapshotMeta {/// Collected remote image URLs (hash-sorted); non-empty only on the URL-collection lane.#[serde(skip_serializing_if = "Vec::is_empty")]pub urls: Vec<UrlEntry>,+ /// Collected ref occurrences by bounded replay location, property, and inline or URL lane.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub image_sources: Vec<ImageSourceCount>,/// Counts by reason for the URLs the collector refused. Every decline is otherwise invisible,/// and the phase that measures this lane would report a smaller URL set than the traffic holds/// with nothing to say why.@@ -547,6 +550,7 @@ fn anonymize_snapshot_data_inner(domain: u.domain,}).collect();+ msg.meta.image_sources = ctx.take_image_source_counts();let (entries, image_bytes) = pack_images(ctx.into_collected_images());msg.meta.images = entries;msg.image_bytes = image_bytes;@@ -984,6 +988,7 @@ fn finish(// The collector lives on the Ctx, not the Sink; the entry point packs it in.images: Vec::new(),urls: Vec::new(),+ image_sources: Vec::new(),url_declines: Vec::new(),},image_bytes: Vec::new(),diff --git a/rust/replay-anonymizer/src/srcset.rs b/rust/replay-anonymizer/src/srcset.rsnew file mode 100644index 000000000000..4d03596443fd--- /dev/null+++ b/rust/replay-anonymizer/src/srcset.rs@@ -0,0 +1,159 @@+#[derive(Clone, Copy, PartialEq, Eq)]+enum DescriptorKind {+ Density,+ Width,+}++struct Candidate<'a> {+ url: &'a str,+ kind: DescriptorKind,+ value: f64,+}++pub(crate) fn largest_candidate(srcset: &str) -> Option<&str> {+ let candidates = parse_candidates(srcset)?;+ let kind = candidates.first()?.kind;+ if candidates.iter().any(|candidate| candidate.kind != kind) {+ return None;+ }+ candidates+ .into_iter()+ .reduce(|best, candidate| {+ if candidate.value > best.value {+ candidate+ } else {+ best+ }+ })+ .map(|candidate| candidate.url)+}++fn parse_candidates(srcset: &str) -> Option<Vec<Candidate<'_>>> {+ let bytes = srcset.as_bytes();+ let mut candidates = Vec::new();+ let mut position = 0;+ while position < bytes.len() {+ while matches!(bytes.get(position), Some(byte) if byte.is_ascii_whitespace()) {+ position += 1;+ }+ if position == bytes.len() {+ break;+ }+ if bytes[position] == b',' {+ return None;+ }++ let url_start = position;+ while matches!(bytes.get(position), Some(byte) if !byte.is_ascii_whitespace()) {+ position += 1;+ }+ let mut url_end = position;+ while bytes.get(url_end.wrapping_sub(1)) == Some(&b',') && url_end > url_start {+ url_end -= 1;+ }+ if url_end == url_start {+ return None;+ }+ if position - url_end > 1 {+ return None;+ }+ let url = &srcset[url_start..url_end];+ if !url.starts_with("data:") && url.contains(',') {+ return None;+ }+ let ended_with_comma = url_end < position;++ while matches!(bytes.get(position), Some(byte) if byte.is_ascii_whitespace()) {+ position += 1;+ }+ let descriptor_start = position;+ if !ended_with_comma {+ while matches!(bytes.get(position), Some(byte) if *byte != b',') {+ position += 1;+ }+ }+ let descriptor = srcset[descriptor_start..position].trim();+ let separated = if bytes.get(position) == Some(&b',') {+ position += 1;+ true+ } else {+ ended_with_comma+ };++ let (kind, value) = parse_descriptor(descriptor)?;+ candidates.push(Candidate { url, kind, value });+ if separated {+ let mut next = position;+ while matches!(bytes.get(next), Some(byte) if byte.is_ascii_whitespace()) {+ next += 1;+ }+ if next == bytes.len() || bytes[next] == b',' {+ return None;+ }+ }+ }+ (!candidates.is_empty()).then_some(candidates)+}++fn parse_descriptor(descriptor: &str) -> Option<(DescriptorKind, f64)> {+ if descriptor.is_empty() {+ return Some((DescriptorKind::Density, 1.0));+ }+ if descriptor.split_ascii_whitespace().count() != 1 {+ return None;+ }+ if let Some(width) = descriptor.strip_suffix('w') {+ let value = width.parse::<u32>().ok()?;+ return (value > 0).then_some((DescriptorKind::Width, f64::from(value)));+ }+ let density = descriptor.strip_suffix('x')?.parse::<f64>().ok()?;+ (density.is_finite() && density > 0.0).then_some((DescriptorKind::Density, density))+}++#[cfg(test)]+mod tests {+ use super::largest_candidate;++ #[test]+ fn selects_the_largest_consistent_candidate() {+ for (srcset, expected) in [+ (+ "https://example.com/a.png 1x, https://example.com/b.png 2x",+ "https://example.com/b.png",+ ),+ (+ "https://example.com/a.png 320w, https://example.com/b.png 1280w",+ "https://example.com/b.png",+ ),+ (+ "data:image/png;base64,AAAA 1x, data:image/png;base64,BBBB 2x",+ "data:image/png;base64,BBBB",+ ),+ ] {+ assert_eq!(largest_candidate(srcset), Some(expected));+ }+ }++ #[test]+ fn rejects_mixed_or_malformed_descriptors() {+ for srcset in [+ "https://example.com/a.png 1x, https://example.com/b.png 1280w",+ "https://example.com/a.png 0x",+ "https://example.com/a.png 1x 2x",+ ", https://example.com/a.png 1x",+ "https://example.com/a.png 1x,",+ "https://example.com/a.png 1x,, https://example.com/b.png 2x",+ "https://example.com/a.png,https://example.com/b.png",+ ] {+ assert_eq!(largest_candidate(srcset), None);+ }+ }++ #[test]+ fn the_first_candidate_wins_a_tie() {+ assert_eq!(+ largest_candidate("https://example.com/a.png 2x, https://example.com/b.png 2x"),+ Some("https://example.com/a.png")+ );+ }+}diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rsindex 547de8cbe49c..55b2f7bfdf92 100644--- a/rust/replay-anonymizer/tests/ref_idempotence.rs+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs@@ -21,6 +21,7 @@ const TS0: f64 = 1_700_000_000_000.0;const REF: &str = "image:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";const URL_REF: &str = "imageurl:AAAAAAAAAAAAAAAAAAAAAA";const LEGACY_URL_REF: &str = "imageurl:0123456789abcdef0123456789abcdef:AAAAAAAAAAAAAAAAAAAAAA";+const NUMBERED_PLACEHOLDER: &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'/><metadata id='anon-image-slot-0'/></svg>";fn img_line(value: &str, attr: &str) -> Value {json!(["w", { "type": 3, "timestamp": TS0, "data": {@@ -38,6 +39,17 @@ fn canvas_line(value: &str) -> Value {"data": [{ "rr_type": "ArrayBuffer", "base64": value }] }] }] }] } }])}+fn css_line(reference: &str) -> Value {+ json!(["w", { "type": 3, "timestamp": TS0, "data": {+ "source": 0, "adds": [{ "parentId": 1, "nextId": null, "node": {+ "type": 2, "tagName": "div", "id": 42,+ "attributes": {+ "style": format!("background-image:url(\"{NUMBERED_PLACEHOLDER}\")"),+ "data-anon-image-refs-style": json!({ "0": reference }).to_string()+ },+ "childNodes": [] } }] } }])+}+/// 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 {@@ -118,6 +130,22 @@ fn a_namespaced_url_ref_survives_only_a_trusted_rescrub() {}}+#[test]+fn a_css_ref_map_survives_only_a_trusted_rescrub() {+ for reference in [REF, URL_REF, LEGACY_URL_REF] {+ let line = css_line(reference);+ assert!(scrub_trusted(&line).contains(reference));+ assert!(scrub_trusted(&line).contains("anon-image-slot-0"));+ assert!(!scrub_default(&line).contains("data-anon-image-refs-style"));+ for byte_walk in [true, false] {+ assert!(+ !scrub_ingestion(&line, byte_walk).contains("data-anon-image-refs-style"),+ "a captured CSS ref map 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"));diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex ddb47a702ed4..025d3370bd13 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -7,6 +7,7 @@use posthog_replay_anonymizer::allow_lists::AllowLists;use posthog_replay_anonymizer::collect::{hash_image_bytes, image_ref};+use posthog_replay_anonymizer::context::ImageSourceCount;use posthog_replay_anonymizer::snapshot::{anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_via_tree, AnonymizeOpts,AnonymizedMessage, FailKind, Failure, FLAG_ACTIVE, FLAG_CLICK, FLAG_KEYPRESS,@@ -832,6 +833,30 @@ fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {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:?}"+ );}}}@@ -883,5 +908,6 @@ fn image_collection_svg_stays_on_the_inline_scrub_path() {.expect("anonymizes");let lines = String::from_utf8(out.lines.clone()).unwrap();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");}diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rsindex ea48daee25c4..0f5e97bceee1 100644--- a/rust/replay-anonymizer/tests/url_collection.rs+++ b/rust/replay-anonymizer/tests/url_collection.rs@@ -63,37 +63,116 @@ fn collect_urls_of(tag: &str, attrs: Value) -> Vec<String> {}#[test]-fn only_an_image_bearing_tag_has_its_src_collected() {- // TagKind::Media also covers video, audio and track, whose src is a movie, a sound file, or a- // WebVTT subtitle document. The fetch lane is sized to download images.- for tag in ["img", "image", "picture"] {+fn known_image_fields_are_collected() {+ for (tag, attrs) in [+ ("img", json!({ "src": "https://cdn.example.com/a.png" })),+ ("img", json!({ "rr_src": "https://cdn.example.com/a.png" })),+ ("image", json!({ "href": "https://cdn.example.com/a.png" })),+ (+ "image",+ json!({ "xlink:href": "https://cdn.example.com/a.png" }),+ ),+ (+ "video",+ json!({ "poster": "https://cdn.example.com/a.png" }),+ ),+ ] {assert_eq!(- collect_urls_of(tag, json!({ "src": "https://cdn.example.com/a.png" })),+ collect_urls_of(tag, attrs),vec!["byte_walk=true:1", "byte_walk=false:1"],- "{tag} src should be collected"- );- }- for tag in ["video", "audio", "track", "source"] {- assert_eq!(- collect_urls_of(tag, json!({ "src": "https://cdn.example.com/movie.mp4" })),- vec!["byte_walk=true:0", "byte_walk=false:0"],- "{tag} src is not an image and must not be collected"+ "{tag} image field should be collected");}}#[test]-fn attributes_other_than_src_are_not_collected() {+fn fields_that_can_name_non_images_are_not_collected() {for (tag, attrs) in [- ("img", json!({ "rr_src": "https://cdn.example.com/a.png" })),+ (+ "iframe",+ json!({ "rr_src": "https://cdn.example.com/frame.html" }),+ ),("video",- json!({ "poster": "https://cdn.example.com/poster.jpg" }),+ json!({ "src": "https://cdn.example.com/movie.mp4" }),+ ),+ (+ "audio",+ json!({ "src": "https://cdn.example.com/audio.mp3" }),+ ),+ (+ "track",+ json!({ "src": "https://cdn.example.com/subtitles.vtt" }),+ ),+ (+ "source",+ json!({ "srcset": "https://cdn.example.com/a.png 2x" }),),] {assert_eq!(collect_urls_of(tag, attrs),- vec!["byte_walk=true:0", "byte_walk=false:0"]+ vec!["byte_walk=true:0", "byte_walk=false:0"],+ "{tag} field must not be guessed as an image"+ );+ }+}++#[test]+fn picture_source_srcset_is_collected_when_its_parent_is_known() {+ let inner = json!({+ "event": "$snapshot_items",+ "properties": {+ "$session_id": "s",+ "$window_id": "w",+ "$snapshot_items": [{+ "type": 2,+ "timestamp": TS0,+ "data": {+ "node": {+ "type": 0,+ "childNodes": [{+ "type": 2,+ "tagName": "picture",+ "attributes": {},+ "childNodes": [{+ "type": 2,+ "tagName": "source",+ "attributes": {+ "srcset": "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x"+ },+ "childNodes": []+ }]+ }]+ },+ "initialOffset": { "top": 0, "left": 0 }+ }+ }]+ }+ });+ let payload = json!({ "distinct_id": "d", "data": inner.to_string() })+ .to_string()+ .into_bytes();++ for byte_walk in [true, false] {+ let mut bytes = payload.clone();+ let message = anonymize_kafka_payload_collecting(+ &AllowLists::default(),+ &mut bytes,+ AnonymizeOpts {+ byte_walk,+ image_policy: ImagePolicy::Inline,+ },+ None,+ None,+ Some(UrlCollection {+ url_key: URL_KEY.to_string(),+ }),+ )+ .expect("anonymize should succeed");+ assert_eq!(message.meta.urls.len(), 1, "byte_walk={byte_walk}");+ assert_eq!(+ message.meta.urls[0].url, "https://cdn.example.com/b.png",+ "byte_walk={byte_walk}");}}@@ -183,6 +262,16 @@ fn a_remote_src_keeps_its_placeholder_and_stashes_the_ref() {assert_eq!(urls.len(), 1, "{engine}");assert_eq!(urls[0]["url"], "https://cdn.example.com/hero.png?w=200");assert_eq!(urls[0]["host"], "cdn.example.com");+ assert_eq!(+ meta["imageSources"],+ json!([{+ "source": "html",+ "property": "src",+ "kind": "url",+ "count": 1+ }]),+ "{engine}"+ );assert!(url_ref== format!(@@ -249,9 +338,7 @@ fn a_non_fetchable_scheme_keeps_the_placeholder() {}#[test]-fn srcset_stays_out_of_scope_and_keeps_the_placeholder() {- // srcset holds several candidates with descriptors, so it needs a parse and a choice this lane- // deliberately does not make yet. Pinned so adding it is a decision rather than an accident.+fn srcset_collects_only_the_largest_candidate() {for (engine, result) in run(json!({ "srcset": "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x" }),true,@@ -265,13 +352,58 @@ fn srcset_stays_out_of_scope_and_keeps_the_placeholder() {"{engine}: expected the placeholder, got {srcset}");assert!(- attrs_of(line).get("data-anon-image-ref-srcset").is_none(),+ attrs_of(line)["data-anon-image-ref-srcset"]+ .as_str()+ .is_some_and(|reference| reference.starts_with("imageurl:")),"{engine}");+ assert_eq!(meta["urls"].as_array().map(Vec::len), Some(1), "{engine}");+ assert_eq!(meta["urls"][0]["url"], "https://cdn.example.com/b.png");+ }+}++#[test]+fn srcset_routes_an_inlined_largest_candidate_to_the_image_scrubber() {+ let small = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";+ let large = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l5hJxAAAAABJRU5ErkJggg==";+ for (engine, result) in run(json!({ "srcset": format!("{small} 1x, {large} 2x") }), true) {+ let (line, meta) = (&result[0], &result[1]);+ let srcset = attrs_of(line)["srcset"]+ .as_str()+ .expect("srcset is a string");+ assert!(!srcset.contains(large), "{engine}");+ assert!(srcset.starts_with("data:image/"), "{engine}: {srcset}");assert!(meta.get("urls").is_none(), "{engine}");}}+#[test]+fn css_image_urls_use_numbered_placeholders_and_a_reference_map() {+ let css = "background-image:url('https://cdn.example.com/a.png');mask-image:url(https://cdn.example.com/b.png)";+ for (engine, result) in run(json!({ "style": css }), true) {+ let (line, meta) = (&result[0], &result[1]);+ let attrs = attrs_of(line);+ let style = attrs["style"].as_str().expect("style is a string");+ assert!(!style.contains("cdn.example.com"), "{engine}: {style}");+ assert!(style.contains("anon-image-slot-0"), "{engine}: {style}");+ assert!(style.contains("anon-image-slot-1"), "{engine}: {style}");++ let refs: serde_json::Map<String, Value> = serde_json::from_str(+ attrs["data-anon-image-refs-style"]+ .as_str()+ .expect("CSS references are present"),+ )+ .expect("CSS references are JSON");+ assert_eq!(refs.len(), 2, "{engine}");+ assert!(refs.values().all(|reference| {+ reference+ .as_str()+ .is_some_and(|reference| reference.starts_with("imageurl:"))+ }));+ assert_eq!(meta["urls"].as_array().map(Vec::len), Some(2), "{engine}");+ }+}+#[test]fn signed_urls_produce_no_ref_or_fetch_candidate() {for (engine, result) in run(