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(replay): deduplicate responsive and shopify image sources (#98301)

Robbie3843bbdd42ae
diff --git a/docs/internal/session-replay-image-canonicalisation.md b/docs/internal/session-replay-image-canonicalisation.md
new file mode 100644
index 000000000000..c5e3592606a4
--- /dev/null
+++ b/docs/internal/session-replay-image-canonicalisation.md
@@ -0,0 +1,43 @@
+# Session replay image canonicalisation
+
+The replay mirror collects remote image URLs. The shared Rust URL policy defines the fetch URL and the global image identity.
+
+## Source selection
+
+For an `img` with a usable `srcset`, the collector selects a candidate within a size limit and ignores `src` and `rr_src`. The ignored attributes become placeholders and produce no image refs. This rule applies to every site and both replay walkers.
+
+For width descriptors, the collector chooses the largest candidate at or below 1024w. For density descriptors, it chooses the largest candidate at or below 2x. If all candidates exceed the relevant limit, it chooses the smallest. The first candidate wins a tie. The same rule applies to `picture` source elements. CSS `image-set()` retains its existing largest-density selection.
+
+These limits guide source selection; they do not enforce a download-size or total-pixel limit. Width descriptors omit height, and density descriptors omit absolute dimensions. The choice never rewrites a URL or changes its aspect ratio. The fetcher and scrubber still enforce their byte and decoded-pixel limits. The selection limit is separate from the scrubber's output ceiling because detection requires more detail than storage.
+
+A usable candidate is an admitted HTTPS image URL or a supported base64 image data URI. Trusted re-scrubbing also recognises an existing image ref. If `srcset` is empty, malformed, mixes widths and densities, or selects a refused URL, the collector retains the `src` and `rr_src` fallbacks. The collector does not infer relationships between separate `picture` children or between separate attribute mutations.
+
+## Shopify resizing
+
+The policy recognises raster images on `cdn.shopify.com/s/files/<numeric store path>/{files,products,collections}/` and `/cdn/shop/{files,products,collections}/` on a single-label `*.myshopify.com` storefront. Custom domains keep their resize values because the path alone does not prove Shopify semantics. It keeps the hostname, store path, asset name, file extension, version, and other retained query bytes distinct.
+
+Recognised resizes use a consistent size in the dedup URL, which determines the global identity. The fetch URL retains its observed resize suffix and query bytes:
+
+- A `width` query without `height` becomes `width=1024`.
+- A `height` query without `width` becomes `height=1024`.
+- Uncropped legacy suffixes such as `_480x`, `_x480`, and `_480x480` use an integer scale with a longest requested side at most 1024. Two dimensions retain their exact requested ratio. Ratios that cannot fit at that size remain unchanged.
+- Legacy sizes `pico`, `icon`, `thumb`, `small`, `compact`, `medium`, `large`, and `grande` use a 1024-by-1024 bounding box.
+- A legacy `@2x` or `@3x` density suffix is absorbed into the consistent dedup size.
+
+The dedup URL is an identity input, not a fetch target. For example, `photo_480x.jpg` has a dedup suffix of `photo_1024x.jpg`, but the fetcher still requests `photo_480x.jpg`. Within a collection batch, the first observed variant supplies the fetch URL. Across batches, the first successfully stored variant can supply the image for later variants, including larger ones.
+
+Crop suffixes, crop parameters, and query URLs with both `width` and `height` remain unchanged. The crop result can depend on the original image bounds as well as the requested ratio. Unknown query fields, duplicate resize fields, invalid dimensions, and combined legacy/query resizing also keep their original resize values. `_480px` is not a recognised Shopify suffix.
+
+The normalised identity size does not set the fetch or output resolution. The URL-image scrubber defaults to a 50,000-pixel output ceiling and can store less to satisfy its detection constraints. Scrubbing still applies to every fetched image.
+
+See Shopify's [image_url](https://shopify.dev/docs/api/liquid/filters/image_url) and [legacy img_url](https://shopify.dev/docs/api/liquid/filters/img_url) contracts.
+
+## Global query rules
+
+Outside recognised Shopify image routes, `width`, `height`, `w`, `h`, and `size` remain part of the global identity. Their names do not establish whether they select a resize, crop, generated image, or another resource. Downsampling does not make different crops equivalent.
+
+The existing volatile-query rules still apply. Admission checks run before size normalisation, so a signed URL is refused rather than rewritten into an unsigned request. Unrelated query fields retain their original order and encoding.
+
+## Rollout
+
+The mirror and image fetcher use the same compiled Rust policy. Deploy both to obtain consistent identity rules. Existing queued jobs keep their original refs and observed resize values. Existing stored refs remain readable, while newly collected size variants use their new shared identity.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index d803c8ceadcc..8cf4db02e3f9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -125,7 +125,7 @@ The pass-budget alert is inactive in dry-run mode. Delay-topic lag has no alert
## Assumptions
-- Only the `src` attribute creates a remote-image ref. The collector does not create refs for `rr_src` or `poster`.
+- Image source selection follows requirements 13.11–13.12. A usable `img[srcset]` suppresses that element's `src` and `rr_src` fallbacks. Shopify resize normalisation follows the shared URL policy.
- A response can contain at most four content-coding layers. This bound limits decompression work while retaining common stacked encodings.
- The standard pass is shorter than the minimum image retry delay. Active back-off therefore follows requirement 7.13 without an in-memory second pass.
- Smokescreen is the authoritative production DNS and connection boundary. Local URL admission is an additional fail-closed check.
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 0a56acc2bae8..1aac6bdf8e40 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
@@ -509,7 +509,7 @@ Each metric returns the top 20 domain-factor keys per flush and tracks at most 2
**13.3** The key uses the shared Rust URL-policy implementation to canonicalize the URL. The canonical form uses the parser's serialized HTTPS URL, lowercases and IDNA-encodes the host, removes a trailing DNS root dot, removes the fragment, omits the explicit default port `443`, and uses `/` for an empty path. It does not sort path segments or query fields. The shared parser's serialization is authoritative for percent-encoding and dot-segment normalization.
-The fetch URL keeps the original query verbatim. The global ref uses a canonical query that removes every occurrence of a volatile query field after percent-decoding its name and comparing it case-insensitively. The implementation filters raw query fields and never rebuilds a query. Every retained field stays byte-for-byte unchanged. The global volatile field names are `cb`, `nocache`, and `rnd`. If the URL contains `_nc_ohc`, the scoped volatile field names are `_nc_ohc`, `_nc_ht`, `ccb`, `oe`, `oh`, and `stp`. These lists are part of the shared URL policy. A new volatile field requires a specification change and shared test vectors. A credential field is refused under requirement 1.2 before canonicalization and is never removed to make a URL acceptable. If several fetch URLs in one collection batch map to one global ref, the first collected fetch URL becomes the fetch candidate.
+Recognised image resizes on `cdn.shopify.com` and single-label `*.myshopify.com` storefronts use a consistent size only in the dedup URL before the global identity is calculated. Custom domains retain their resize values because the route alone does not establish Shopify semantics. The fetch URL retains the observed resize suffix and query bytes. The rules and exceptions are defined in [image canonicalisation](/docs/internal/session-replay-image-canonicalisation.md). Crops, query URLs with both dimensions, asset versions, and unrecognised resize controls remain distinct. Shopify size normalisation never creates a new fetch target. The global ref uses a canonical query that removes every occurrence of a volatile query field after percent-decoding its name and comparing it case-insensitively. The implementation filters raw query fields and never rebuilds a query. Every retained field stays byte-for-byte unchanged. The global volatile field names are `cb`, `nocache`, and `rnd`. If the URL contains `_nc_ohc`, the scoped volatile field names are `_nc_ohc`, `_nc_ht`, `ccb`, `oe`, `oh`, and `stp`. These lists are part of the shared URL policy. A new volatile field requires a specification change and shared test vectors. A credential field is refused under requirement 1.2 before canonicalization and is never removed to make a URL acceptable. If several fetch URLs in one collection batch map to one global ref, the first collected fetch URL becomes the fetch candidate.
**13.4** A URL ref does not contain a team identifier, a team pseudonym, or a key derived from one team. The same canonical URL produces the same ref for every team.
@@ -527,7 +527,7 @@ The fetch URL keeps the original query verbatim. The global ref uses a canonical
**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.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.12** For `srcset`, the mirror selects the largest candidate at or below 1024w or 2x, according to the descriptor type. If all candidates exceed that limit, it selects the smallest. These descriptor limits do not establish total pixels or download bytes. CSS `image-set()` retains its largest-density selection. It declines a malformed or mixed `srcset`. The first candidate wins a tie. An `img` with a usable `srcset` candidate does not also collect or scrub its `src` or `rr_src`; those attributes become placeholders without refs. A refused or malformed `srcset` retains those fallbacks. This choice applies within one attribute map, not across separate elements or mutations.
**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.
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index caff5c270de0..3b4c3bf829c8 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9333,7 +9333,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.6.1"
+version = "0.6.2"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index a5600c2670f1..a098d1f051bb 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.6.1"
+version = "0.6.2"
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 763f6ff15b25..5771998dbf5e 100644
--- a/rust/replay-anonymizer/src/assets.rs
+++ b/rust/replay-anonymizer/src/assets.rs
@@ -7,12 +7,13 @@ use std::borrow::Cow;
use simd_json::borrowed::{Object, Value};
use crate::blur::is_image_data_uri;
-use crate::collect::is_image_ref_strict;
+use crate::collect::{collectable_data_uri_bytes, is_image_ref_strict};
use crate::context::{Ctx, ImageSource};
use crate::images::ImageFallback;
use crate::json::{as_f64, as_str, string_value};
-use crate::srcset::largest_candidate;
+use crate::srcset::candidate_for_scrubbing;
use crate::url::scrub_url;
+use crate::url_policy::canonicalize;
// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute.
pub const INLINE_IMAGE_ATTR: &str = "rr_dataURL";
@@ -139,6 +140,13 @@ pub fn has_media_src_attr(attrs: &Object<'_>) -> bool {
MEDIA_SRC_ATTRS.iter().any(|name| attrs.contains_key(*name))
}
+pub(crate) fn has_usable_srcset(value: &str, keep_image_refs: bool) -> bool {
+ (keep_image_refs && is_image_ref_strict(value))
+ || candidate_for_scrubbing(value).is_some_and(|url| {
+ collectable_data_uri_bytes(url).is_some() || canonicalize(url).is_some()
+ })
+}
+
/// Blur an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`).
/// Returns whether it acted.
pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str) -> bool {
@@ -168,6 +176,11 @@ pub fn apply_blur(
parent_is_picture: bool,
) -> bool {
let mut acted = false;
+ let prefer_srcset = tag.eq_ignore_ascii_case("img")
+ && attrs
+ .get("srcset")
+ .and_then(as_str)
+ .is_some_and(|value| has_usable_srcset(value, ctx.keeps_image_refs()));
// Computed only when a remote image is about to be collected, because the inline style is
// parsed for it and most elements never reach that branch.
let mut hidden_pixel: Option<bool> = None;
@@ -175,6 +188,15 @@ pub fn apply_blur(
let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {
continue;
};
+ if prefer_srcset && matches!(*key, "src" | "rr_src") {
+ attrs.insert(
+ Cow::Borrowed(*key),
+ string_value(PLACEHOLDER_SRC.to_string()),
+ );
+ attrs.remove(format!("{IMAGE_REF_ATTR_PREFIX}{key}").as_str());
+ acted = true;
+ continue;
+ }
// A content ref from an earlier pass over already-mirrored output: opaque, carrying no
// content of its own, with its bytes scrubbed out of band. Re-scrubbing would redact it
// into the placeholder and strand that image beyond recovery, so a caller re-scrubbing
@@ -185,7 +207,7 @@ pub fn apply_blur(
}
acted = true;
let selected = if *key == "srcset" {
- largest_candidate(&existing).map(str::to_string)
+ candidate_for_scrubbing(&existing).map(str::to_string)
} else {
Some(existing.clone())
};
diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rs
index 2ecf3c766b1d..575d82ad895f 100644
--- a/rust/replay-anonymizer/src/bytewalk.rs
+++ b/rust/replay-anonymizer/src/bytewalk.rs
@@ -14,8 +14,9 @@
//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.
use crate::assets::{
- is_at_most_one_pixel, is_fetchable_image_attr, is_image_ref_attr, is_media_src_attr, px_length,
- IMAGE_REF_ATTR_PREFIX, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC,
+ has_usable_srcset, is_at_most_one_pixel, is_fetchable_image_attr, is_image_ref_attr,
+ is_media_src_attr, px_length, IMAGE_REF_ATTR_PREFIX, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS,
+ PLACEHOLDER_SRC,
};
use crate::blur::is_image_data_uri;
use crate::collect::is_image_ref_strict;
@@ -28,7 +29,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::srcset::candidate_for_scrubbing;
use crate::text::{redact_emails, scrub_text};
use crate::url::scrub_url;
@@ -944,6 +945,17 @@ impl<'c, 'a> Walker<'c, 'a> {
if self.bytes.get(start) != Some(&b'{') {
return self.copy_value(start, out);
}
+ let prefer_srcset = if tag.eq_ignore_ascii_case("img") {
+ match self.find_member(start, b"srcset").ok()? {
+ Some(span) if scan::is_string(self.bytes, span) => {
+ let value = scan::unescape(self.bytes, span).ok()?;
+ has_usable_srcset(&value, self.ctx.keeps_image_refs())
+ }
+ _ => false,
+ }
+ } else {
+ false
+ };
let mut stashes: Vec<(String, String)> = Vec::new();
let end = {
let stashes = &mut stashes;
@@ -956,6 +968,15 @@ impl<'c, 'a> Walker<'c, 'a> {
return None;
}
if kind == TagKind::Media && is_media_src_attr(name) {
+ if prefer_srcset
+ && matches!(name, "src" | "rr_src")
+ && w.bytes.get(vstart) == Some(&b'"')
+ {
+ let end = scan::skip_string(w.bytes, vstart).ok()?;
+ scan::write_json_string(PLACEHOLDER_SRC, out);
+ w.changed = true;
+ return Some(end);
+ }
return w.blur_media_src(
name,
vstart,
@@ -1045,7 +1066,7 @@ impl<'c, 'a> Walker<'c, 'a> {
return self.copy_value(vstart, out);
}
let selected = if name == "srcset" {
- largest_candidate(existing.as_ref()).map(str::to_string)
+ candidate_for_scrubbing(existing.as_ref()).map(str::to_string)
} else {
Some(existing.into_owned())
};
diff --git a/rust/replay-anonymizer/src/srcset.rs b/rust/replay-anonymizer/src/srcset.rs
index 4d03596443fd..56c5d92864c3 100644
--- a/rust/replay-anonymizer/src/srcset.rs
+++ b/rust/replay-anonymizer/src/srcset.rs
@@ -1,3 +1,6 @@
+const MAX_SRCSET_WIDTH: f64 = 1024.0;
+const MAX_SRCSET_DENSITY: f64 = 2.0;
+
#[derive(Clone, Copy, PartialEq, Eq)]
enum DescriptorKind {
Density,
@@ -10,21 +13,26 @@ struct Candidate<'a> {
value: f64,
}
-pub(crate) fn largest_candidate(srcset: &str) -> Option<&str> {
+pub(crate) fn candidate_for_scrubbing(srcset: &str) -> Option<&str> {
let candidates = parse_candidates(srcset)?;
let kind = candidates.first()?.kind;
if candidates.iter().any(|candidate| candidate.kind != kind) {
return None;
}
+ let limit = match kind {
+ DescriptorKind::Width => MAX_SRCSET_WIDTH,
+ DescriptorKind::Density => MAX_SRCSET_DENSITY,
+ };
candidates
.into_iter()
- .reduce(|best, candidate| {
- if candidate.value > best.value {
- candidate
- } else {
- best
- }
- })
+ .reduce(
+ |best, candidate| match (best.value <= limit, candidate.value <= limit) {
+ (false, true) => candidate,
+ (true, true) if candidate.value > best.value => candidate,
+ (false, false) if candidate.value < best.value => candidate,
+ _ => best,
+ },
+ )
.map(|candidate| candidate.url)
}
@@ -112,10 +120,10 @@ fn parse_descriptor(descriptor: &str) -> Option<(DescriptorKind, f64)> {
#[cfg(test)]
mod tests {
- use super::largest_candidate;
+ use super::candidate_for_scrubbing;
#[test]
- fn selects_the_largest_consistent_candidate() {
+ fn selects_the_largest_candidate_within_the_limit_or_the_smallest_above_it() {
for (srcset, expected) in [
(
"https://example.com/a.png 1x, https://example.com/b.png 2x",
@@ -123,14 +131,38 @@ mod tests {
),
(
"https://example.com/a.png 320w, https://example.com/b.png 1280w",
- "https://example.com/b.png",
+ "https://example.com/a.png",
+ ),
+ (
+ "large.png 3840w, medium.png 960w, small.png 320w, extra.png 1920w",
+ "medium.png",
+ ),
+ (
+ "small.png 960w, exact.png 1024w, large.png 2048w",
+ "exact.png",
+ ),
+ (
+ "large.png 3840w, small.png 1280w, medium.png 1920w",
+ "small.png",
),
+ (
+ "small.png 1280w, medium.png 1920w, large.png 3840w",
+ "small.png",
+ ),
+ ("large.png 4x, medium.png 2x, small.png 1x", "medium.png"),
+ ("small.png 1x, medium.png 1.5x, large.png 3x", "medium.png"),
+ ("large.png 4x, small.png 3x", "small.png"),
+ ("small.png 3x, large.png 4x", "small.png"),
+ ("default.png, large.png 3x", "default.png"),
+ ("only.png 4096w", "only.png"),
+ ("only.png 4x", "only.png"),
+ ("small.png 320w, large.png 1024w", "large.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));
+ assert_eq!(candidate_for_scrubbing(srcset), Some(expected), "{srcset}");
}
}
@@ -145,15 +177,19 @@ mod tests {
"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);
+ assert_eq!(candidate_for_scrubbing(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")
- );
+ for descriptor in ["2x", "3x", "1024w", "2048w"] {
+ assert_eq!(
+ candidate_for_scrubbing(&format!(
+ "first.png {descriptor}, second.png {descriptor}"
+ )),
+ Some("first.png")
+ );
+ }
}
}
diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rs
index 67201399a98c..1f4bb3a467a0 100644
--- a/rust/replay-anonymizer/src/url_collect.rs
+++ b/rust/replay-anonymizer/src/url_collect.rs
@@ -1,9 +1,9 @@
-//! Collect the original URLs of remote images, for the out-of-band fetch lane.
+//! Collect remote image URLs for the out-of-band fetch lane.
//!
//! 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 keeps the media placeholder and a namespaced
-//! sibling attribute carries the content ref. The message also carries the original URL back to
+//! sibling attribute carries the content ref. The message also carries the fetch URL back to
//! the caller.
//!
//! **Two forms of one URL come out of this module. Do not confuse them.**
@@ -11,9 +11,9 @@
//! The *dedup* URL is canonical, and its volatile parameters are removed. It is the only input to
//! the hash, so it sets the ref and the dedup key of the fetch lane.
//!
-//! The *fetch* URL keeps the original query bytes, and every permitted parameter stays. The
-//! fetcher requests this one. URLs that carry credentials or signatures are refused before either
-//! form is created.
+//! The *fetch* URL keeps the original path's resize suffix and query bytes. Shopify resize
+//! normalisation applies only to the dedup URL. URLs that carry credentials or signatures are
+//! refused before either form is created.
//!
//! That split is what makes the ref stable across non-credential cache busters. A ref that appears
//! once joins to nothing downstream. Removing the volatile parameters matters more for that than
@@ -60,7 +60,7 @@ pub struct UrlCollection {
pub struct CollectedUrl {
/// First 22 base64url chars of `HMAC-SHA256(url_key, dedup_url)`.
pub hash: String,
- /// The URL with its original query bytes intact. This is what the fetcher requests.
+ /// The fetch URL, retaining the observed resize suffix and original query bytes.
pub url: String,
/// The host the request goes to. robots.txt and the connection limit are scoped to this.
pub host: String,
@@ -239,11 +239,24 @@ mod tests {
#[test]
fn a_resize_parameter_is_not_volatile() {
// Collapsing these onto one ref would point one ref at two different images.
- let mut c = collector();
- let small = c.collect("https://cdn.example.com/a.png?w=100").unwrap();
- let large = c.collect("https://cdn.example.com/a.png?w=900").unwrap();
- assert_ne!(small, large);
- assert_eq!(c.into_urls().len(), 2);
+ for (small_url, large_url) in [
+ (
+ "https://cdn.example.com/a.png?w=100",
+ "https://cdn.example.com/a.png?w=900",
+ ),
+ (
+ "https://store.example.com/cdn/shop/files/photo.jpg?width=100",
+ "https://store.example.com/cdn/shop/files/photo.jpg?width=900",
+ ),
+ (
+ "https://store.example.com/cdn/shop/files/photo_480x.jpg",
+ "https://store.example.com/cdn/shop/files/photo_960x.jpg",
+ ),
+ ] {
+ let mut c = collector();
+ assert_ne!(c.collect(small_url).unwrap(), c.collect(large_url).unwrap());
+ assert_eq!(c.into_urls().len(), 2);
+ }
}
#[test]
@@ -261,6 +274,24 @@ mod tests {
assert_eq!(urls[0].url, first_url);
}
+ #[test]
+ fn shopify_sizes_share_a_ref_and_fetch_the_first_observed_url() {
+ for (first, second) in [
+ ("photo_480x.jpg", "photo_960x.jpg"),
+ ("photo_960x.jpg", "photo_480x.jpg"),
+ ("photo.jpg?width=300", "photo.jpg?width=800"),
+ ("photo.jpg?width=800", "photo.jpg?width=300"),
+ ] {
+ let mut c = collector();
+ let first_url = format!("https://example-store.myshopify.com/cdn/shop/files/{first}");
+ let second_url = format!("https://example-store.myshopify.com/cdn/shop/files/{second}");
+ assert_eq!(c.collect(&first_url), c.collect(&second_url));
+ let urls = c.into_urls();
+ assert_eq!(urls.len(), 1);
+ assert_eq!(urls[0].url, first_url);
+ }
+ }
+
#[test]
fn collect_stops_at_the_cap_but_still_refs_a_url_it_already_holds() {
let mut c = collector();
diff --git a/rust/replay-anonymizer/src/url_policy.rs b/rust/replay-anonymizer/src/url_policy.rs
index 91576f13baa6..955b2749195c 100644
--- a/rust/replay-anonymizer/src/url_policy.rs
+++ b/rust/replay-anonymizer/src/url_policy.rs
@@ -20,6 +20,8 @@ use public_suffix::{EffectiveTLDProvider, DEFAULT_PROVIDER};
use url::Url;
+mod shopify;
+
const VOLATILE_PARAMS: &[&str] = &["cb", "nocache", "rnd"];
const CREDENTIAL_PARAMS: &[&str] = &[
@@ -391,8 +393,12 @@ pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {
return Err(Decline::TooLong);
}
- let dedup_query = remove_volatile_params(original_query)?;
- let dedup = serialize_with_query(&serialized_without_query, dedup_query.as_deref());
+ let resized_query = shopify::normalize_image_size(&mut url, original_query);
+ let dedup_query = remove_volatile_params(resized_query.as_deref().or(original_query))?;
+ let dedup = serialize_with_query(url.as_str(), dedup_query.as_deref());
+ if dedup.len() > MAX_URL_LEN {
+ return Err(Decline::TooLong);
+ }
Ok(CanonicalUrl {
fetch,
@@ -718,6 +724,132 @@ mod tests {
assert_eq!(canonical.dedup, "https://cdn.example.com/a.png?w=200");
}
+ #[test]
+ fn shopify_resize_variants_share_an_identity_and_keep_their_fetch_urls() {
+ for (first, second, expected) in [
+ (
+ "photo.jpg?v=123&width=300",
+ "photo.jpg?v=123&width=800",
+ "photo.jpg?v=123&width=1024",
+ ),
+ (
+ "photo.jpg?height=100",
+ "photo.jpg?height=200",
+ "photo.jpg?height=1024",
+ ),
+ (
+ "photo_64x64.jpg?v=123",
+ "photo_128x128.jpg?v=123",
+ "photo_1024x1024.jpg?v=123",
+ ),
+ ("photo_480x.jpg", "[email protected]", "photo_1024x.jpg"),
+ ("photo_x480.jpg", "photo_x960.jpg", "photo_x1024.jpg"),
+ ("photo_small.jpg", "photo_large.jpg", "photo_1024x1024.jpg"),
+ (
+ "photo_300x200.png",
+ "photo_600x400.png",
+ "photo_1023x682.png",
+ ),
+ ] {
+ for prefix in [
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/",
+ "https://cdn.shopify.com/s/files/1/0000/0001/products/",
+ "https://cdn.shopify.com/s/files/1/0000/0001/collections/",
+ "https://example-store.myshopify.com/cdn/shop/files/",
+ "https://example-store.myshopify.com/cdn/shop/products/",
+ "https://example-store.myshopify.com/cdn/shop/collections/",
+ ] {
+ let first_url = format!("{prefix}{first}");
+ let second_url = format!("{prefix}{second}");
+ let first = canonicalize(&first_url).unwrap();
+ let second = canonicalize(&second_url).unwrap();
+ assert_eq!(first.fetch, first_url);
+ assert_eq!(second.fetch, second_url);
+ assert_eq!(first.dedup, format!("{prefix}{expected}"));
+ assert_eq!(first.dedup, second.dedup);
+ assert_eq!(canonicalize(&first.fetch).unwrap(), first);
+ }
+ }
+ }
+
+ #[test]
+ fn shopify_paths_on_unknown_hosts_preserve_distinct_resources() {
+ for prefix in [
+ "https://store.example.com/cdn/shop/files/",
+ "https://store.example.com/cdn/shop/products/",
+ "https://store.example.com/cdn/shop/collections/",
+ "https://notmyshopify.com/cdn/shop/files/",
+ "https://example-store.myshopify.com.example.com/cdn/shop/files/",
+ "https://nested.example-store.myshopify.com/cdn/shop/files/",
+ "https://myshopify.com/cdn/shop/files/",
+ "https://cdn.shopify.com.example.com/s/files/1/0000/0001/files/",
+ ] {
+ for suffix in [
+ "photo.jpg?width=300",
+ "photo.jpg?width=800",
+ "photo.jpg?height=100",
+ "photo.jpg?height=200",
+ "photo_480x.jpg",
+ "photo_960x.jpg",
+ ] {
+ let raw = format!("{prefix}{suffix}");
+ let canonical = canonicalize(&raw).unwrap();
+ assert_eq!(canonical.fetch, raw);
+ assert_eq!(canonical.dedup, raw);
+ }
+ }
+ }
+
+ #[test]
+ fn shopify_resize_normalization_preserves_content_boundaries() {
+ let prefix = "https://cdn.shopify.com/s/files/1/0000/0001/files/";
+ for (first, second) in [
+ ("photo.jpg?v=1&width=300", "photo.jpg?v=2&width=300"),
+ (
+ "photo_300x200_crop_center.jpg",
+ "photo_200x300_crop_center.jpg",
+ ),
+ (
+ "photo_300x300_crop_top.jpg",
+ "photo_300x300_crop_bottom.jpg",
+ ),
+ (
+ "photo.jpg?width=300&height=200",
+ "photo.jpg?width=200&height=300",
+ ),
+ (
+ "photo.jpg?width=300&height=200&crop=top",
+ "photo.jpg?width=300&height=200&crop=bottom",
+ ),
+ ("photo.jpg?width=300", "other.jpg?width=300"),
+ ] {
+ assert_ne!(
+ canonicalize(&format!("{prefix}{first}")).unwrap().dedup,
+ canonicalize(&format!("{prefix}{second}")).unwrap().dedup
+ );
+ }
+ for raw in [
+ "https://example.com/photo.jpg?width=300&height=200&size=small",
+ "https://example.com/photo_480x.jpg",
+ "https://cdn.shopify.com/other/photo.jpg?width=300",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&width=400",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=0",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=999999999999999999999",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&crop=region&crop_width=100",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&height=200",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&height=200&crop=center",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_64x64_crop_center.jpg",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&size=small",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_300x200.jpg?width=100",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_350x350_banner.jpg",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_480px.jpg",
+ ] {
+ let canonical = canonicalize(raw).unwrap();
+ assert_eq!(canonical.fetch, raw);
+ assert_eq!(canonical.dedup, raw);
+ }
+ }
+
#[test]
fn fetch_and_retained_dedup_query_bytes_are_never_rebuilt() {
let raw = "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f&cb=drop#fragment";
diff --git a/rust/replay-anonymizer/src/url_policy/shopify.rs b/rust/replay-anonymizer/src/url_policy/shopify.rs
new file mode 100644
index 000000000000..172982c343c8
--- /dev/null
+++ b/rust/replay-anonymizer/src/url_policy/shopify.rs
@@ -0,0 +1,160 @@
+use percent_encoding::percent_decode_str;
+use url::Url;
+
+const RESIZE_LONG_SIDE: u32 = 1024;
+const MAX_SHOPIFY_DIMENSION: u32 = 5760;
+type Dimensions = (Option<u32>, Option<u32>);
+
+pub(super) fn normalize_image_size(url: &mut Url, query: Option<&str>) -> Option<String> {
+ if !is_shopify_image(url) || url.path().contains("_crop_") {
+ return None;
+ }
+ let fields: Vec<&str> = query.map_or_else(Vec::new, |query| query.split('&').collect());
+ let mut width = None;
+ let mut height = None;
+ for field in &fields {
+ let (name, value) = field.split_once('=').unwrap_or((field, ""));
+ let name = percent_decode_str(name).decode_utf8().ok()?;
+ match name.as_ref() {
+ "width" if width.is_none() => width = Some(dimension(value)?),
+ "height" if height.is_none() => height = Some(dimension(value)?),
+ "v" | "format" | "cb" | "nocache" | "rnd" => {}
+ _ => return None,
+ }
+ }
+ let (stem, extension) = url.path().rsplit_once('.')?;
+ let legacy_size = legacy_size(stem);
+ if let Some((base, dimensions)) = legacy_size {
+ if width.is_some() || height.is_some() {
+ return None;
+ }
+ let (width, height) = normalize_dimensions(dimensions.0, dimensions.1)?;
+ let width = width.map_or_else(String::new, |value| value.to_string());
+ let height = height.map_or_else(String::new, |value| value.to_string());
+ let path = format!("{base}_{width}x{height}.{extension}");
+ url.set_path(&path);
+ return None;
+ }
+ // Two dimensions can request a crop, whose result also depends on the original image bounds.
+ if width.is_some() && height.is_some() {
+ return None;
+ }
+ let (width, height) = normalize_dimensions(width, height)?;
+ let fields: Vec<String> = fields
+ .into_iter()
+ .map(|field| {
+ let (name, _) = field.split_once('=').unwrap_or((field, ""));
+ match percent_decode_str(name).decode_utf8().ok().as_deref() {
+ Some("width") => format!("{name}={}", width.unwrap()),
+ Some("height") => format!("{name}={}", height.unwrap()),
+ _ => field.to_string(),
+ }
+ })
+ .collect();
+ Some(fields.join("&"))
+}
+
+fn is_shopify_image(url: &Url) -> bool {
+ let path = url.path();
+ let Some((_, extension)) = path.rsplit_once('.') else {
+ return false;
+ };
+ if !matches!(extension, "jpg" | "jpeg" | "png" | "webp" | "avif" | "gif") {
+ return false;
+ }
+ if url
+ .host_str()
+ .and_then(|host| host.strip_suffix(".myshopify.com"))
+ .is_some_and(|store| !store.is_empty() && !store.contains('.'))
+ {
+ return [
+ "/cdn/shop/files/",
+ "/cdn/shop/products/",
+ "/cdn/shop/collections/",
+ ]
+ .iter()
+ .any(|prefix| {
+ path.strip_prefix(prefix)
+ .is_some_and(|file| !file.contains('/'))
+ });
+ }
+ if url.host_str() != Some("cdn.shopify.com") {
+ return false;
+ }
+ let Some(path) = path.strip_prefix("/s/files/") else {
+ return false;
+ };
+ let segments: Vec<&str> = path.split('/').collect();
+ segments.len() >= 5
+ && matches!(
+ segments[segments.len() - 2],
+ "files" | "products" | "collections"
+ )
+ && segments[..segments.len() - 2]
+ .iter()
+ .all(|segment| !segment.is_empty() && segment.bytes().all(|byte| byte.is_ascii_digit()))
+}
+
+fn dimension(value: &str) -> Option<u32> {
+ if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
+ return None;
+ }
+ value
+ .parse()
+ .ok()
+ .filter(|value| (1..=MAX_SHOPIFY_DIMENSION).contains(value))
+}
+
+fn legacy_size(stem: &str) -> Option<(&str, Dimensions)> {
+ let stem = stem
+ .strip_suffix("@2x")
+ .or_else(|| stem.strip_suffix("@3x"))
+ .unwrap_or(stem);
+ let (base, size) = stem.rsplit_once('_')?;
+ let named = match size {
+ "pico" => Some(16),
+ "icon" => Some(32),
+ "thumb" => Some(50),
+ "small" => Some(100),
+ "compact" => Some(160),
+ "medium" => Some(240),
+ "large" => Some(480),
+ "grande" => Some(600),
+ _ => None,
+ };
+ let dimensions = if let Some(side) = named {
+ (Some(side), Some(side))
+ } else {
+ let (width, height) = size.split_once('x')?;
+ (
+ if width.is_empty() {
+ None
+ } else {
+ Some(dimension(width)?)
+ },
+ if height.is_empty() {
+ None
+ } else {
+ Some(dimension(height)?)
+ },
+ )
+ };
+ Some((base, dimensions))
+}
+
+fn normalize_dimensions(width: Option<u32>, height: Option<u32>) -> Option<Dimensions> {
+ match (width, height) {
+ (Some(width), Some(height)) => {
+ let (mut a, mut b) = (width, height);
+ while b != 0 {
+ (a, b) = (b, a % b);
+ }
+ let (width, height) = (width / a, height / a);
+ let scale = RESIZE_LONG_SIDE / width.max(height);
+ (scale > 0).then_some((Some(width * scale), Some(height * scale)))
+ }
+ (Some(_), None) => Some((Some(RESIZE_LONG_SIDE), None)),
+ (None, Some(_)) => Some((None, Some(RESIZE_LONG_SIDE))),
+ (None, None) => None,
+ }
+}
diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rs
index 55b2f7bfdf92..2fd4c0ba0cb6 100644
--- a/rust/replay-anonymizer/tests/ref_idempotence.rs
+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs
@@ -103,7 +103,14 @@ fn scrub_ingestion(line: &Value, byte_walk: bool) -> String {
#[test]
fn a_ref_survives_a_trusted_rescrub() {
- for attr in ["src", "xlink:href", "rr_src", "poster", "rr_dataURL"] {
+ for attr in [
+ "src",
+ "srcset",
+ "xlink:href",
+ "rr_src",
+ "poster",
+ "rr_dataURL",
+ ] {
assert!(
scrub_trusted(&img_line(REF, attr)).contains(REF),
"ref destroyed in {attr}"
@@ -118,7 +125,10 @@ fn a_ref_survives_a_trusted_rescrub() {
#[test]
fn a_namespaced_url_ref_survives_only_a_trusted_rescrub() {
for url_ref in [URL_REF, LEGACY_URL_REF] {
- let line = img_line(url_ref, "data-anon-image-ref-src");
+ let mut line = img_line(url_ref, "data-anon-image-ref-src");
+ let attrs = &mut line[1]["data"]["adds"][0]["node"]["attributes"];
+ attrs["src"] = json!("data:image/svg+xml;base64,PHN2Zz4=");
+ attrs["srcset"] = json!("data:image/svg+xml;base64,PHN2Zz4=");
assert!(scrub_trusted(&line).contains(url_ref));
assert!(!scrub_default(&line).contains("data-anon-image-ref-src"));
for byte_walk in [true, false] {
diff --git a/rust/replay-anonymizer/tests/url_collection.rs b/rust/replay-anonymizer/tests/url_collection.rs
index a8ea625e0a3d..2d4cd7204e6a 100644
--- a/rust/replay-anonymizer/tests/url_collection.rs
+++ b/rust/replay-anonymizer/tests/url_collection.rs
@@ -138,7 +138,7 @@ fn picture_source_srcset_is_collected_when_its_parent_is_known() {
"type": 2,
"tagName": "source",
"attributes": {
- "srcset": "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x"
+ "srcset": "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x, https://cdn.example.com/c.png 4x"
},
"childNodes": []
}]
@@ -469,35 +469,86 @@ fn a_non_fetchable_scheme_keeps_the_placeholder() {
}
#[test]
-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,
- ) {
- let (line, meta) = (&result[0], &result[1]);
- let srcset = attrs_of(line)["srcset"]
- .as_str()
- .expect("srcset is a string");
- assert!(
- srcset.starts_with("data:image/svg+xml"),
- "{engine}: expected the placeholder, got {srcset}"
- );
- assert!(
- attrs_of(line)["data-anon-image-ref-srcset"]
+fn srcset_collects_only_the_selected_candidate() {
+ for srcset in [
+ "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 2x, https://cdn.example.com/c.png 4x",
+ "https://cdn.example.com/c.png 3840w, https://cdn.example.com/b.png 960w, https://cdn.example.com/a.png 320w",
+ "https://cdn.example.com/c.png 3840w, https://cdn.example.com/b.png 1280w, https://cdn.example.com/a.png 1920w",
+ ] {
+ for (engine, result) in run(
+ json!({
+ "src": "https://cdn.example.com/fallback.png",
+ "rr_src": "https://cdn.example.com/rendered.png",
+ "srcset": srcset
+ }),
+ true,
+ ) {
+ let (line, meta) = (&result[0], &result[1]);
+ let srcset = attrs_of(line)["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");
+ .expect("srcset is a string");
+ assert!(
+ srcset.starts_with("data:image/svg+xml"),
+ "{engine}: expected the placeholder, got {srcset}"
+ );
+ assert!(
+ 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");
+ for name in ["src", "rr_src"] {
+ assert!(attrs_of(line)[name]
+ .as_str()
+ .unwrap()
+ .starts_with("data:image/svg+xml"));
+ assert!(attrs_of(line)
+ .get(format!("data-anon-image-ref-{name}"))
+ .is_none());
+ }
+ }
}
}
#[test]
-fn srcset_routes_an_inlined_largest_candidate_to_the_image_scrubber() {
+fn unusable_srcset_keeps_the_src_fallback() {
+ for srcset in [
+ "",
+ "https://cdn.example.com/a.png 1x, https://cdn.example.com/b.png 400w",
+ "https://cdn.example.com/a.png?token=secret 2x",
+ "https://127.0.0.1/a.png 2x",
+ "data:image/png;base64,%%% 2x",
+ "data:image/svg+xml;base64,PHN2Zz4= 2x",
+ ] {
+ for (engine, result) in run(
+ json!({
+ "src": "https://cdn.example.com/fallback.png", "srcset": srcset
+ }),
+ true,
+ ) {
+ assert_eq!(
+ result[1]["urls"].as_array().map(Vec::len),
+ Some(1),
+ "{engine}: {srcset}"
+ );
+ assert_eq!(
+ result[1]["urls"][0]["url"],
+ "https://cdn.example.com/fallback.png"
+ );
+ }
+ }
+}
+
+#[test]
+fn srcset_routes_an_inlined_selected_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) {
+ for (engine, result) in run(
+ json!({ "src": "https://cdn.example.com/fallback.png", "srcset": format!("{small} 1x, {large} 2x, https://cdn.example.com/oversized.png 4x") }),
+ true,
+ ) {
let (line, meta) = (&result[0], &result[1]);
let srcset = attrs_of(line)["srcset"]
.as_str()