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(ml): scrub inline css and style mutations (#68916)

Nicholas Waltz42e17024bd8a
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
index c9d204fe7085..e17d1dc972c9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
@@ -49,6 +49,38 @@ describe('anonymize/event router', () => {
expect(anonymizeEvent(ctx, event)).toBe(false)
})
+ const onePxPng =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+ test.each([
+ [
+ 'StyleSheetRule adds/replace/replaceSync',
+ {
+ source: 8,
+ id: 1,
+ adds: [{ rule: `.a{background:url(${onePxPng})}` }],
+ replace: `.b{background:url(${onePxPng})}`,
+ replaceSync: `.c{background:url(${onePxPng})}`,
+ },
+ ],
+ [
+ 'StyleDeclaration set value',
+ { source: 13, id: 1, index: [0], set: { property: 'background', value: `url(${onePxPng})` } },
+ ],
+ [
+ 'AdoptedStyleSheet rules',
+ {
+ source: 15,
+ id: 1,
+ styleIds: [1],
+ styles: [{ styleId: 1, rules: [{ rule: `.a{background:url(${onePxPng})}` }] }],
+ },
+ ],
+ ])('scrubs css data images in incremental stylesheet events: %s', (_name, data) => {
+ const event: any = { type: 3, timestamp: 1, data }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(JSON.stringify(event)).not.toContain(onePxPng)
+ })
+
it('scrubs console plugin payload strings', () => {
const event: any = {
type: 6,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
index d3f98ed7a9c9..687dda534f02 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
@@ -7,6 +7,7 @@ import { RRWebEventSource, RRWebEventType } from '~/ingestion/pipelines/sessionr
import { runBlurJobs } from './blur'
import { scrubCanvasMutation } from './canvas'
import { BlurCache, BlurJob, ScrubContext, ScrubTiming, isObject } from './config'
+import { scrubAdoptedStyleSheet, scrubStyleDeclaration, scrubStyleSheetRule } from './css'
import { scrubCompressedFullSnapshot, scrubCompressedMutation } from './cv'
import { scrubFullSnapshot, scrubMutation } from './dom'
import { scrubText } from './text'
@@ -119,6 +120,15 @@ function routeEvent(ctx: ScrubContext, event: Record<string, unknown>): boolean
if (data.source === RRWebEventSource.CanvasMutation) {
return scrubCanvasMutation(ctx, data)
}
+ if (data.source === RRWebEventSource.StyleSheetRule) {
+ return scrubStyleSheetRule(ctx, data)
+ }
+ if (data.source === RRWebEventSource.StyleDeclaration) {
+ return scrubStyleDeclaration(ctx, data)
+ }
+ if (data.source === RRWebEventSource.AdoptedStyleSheet) {
+ return scrubAdoptedStyleSheet(ctx, data)
+ }
return false
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
index 3e8ebca4015a..66ba68eba90b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
@@ -1,6 +1,10 @@
/** Blur inline `url(data:image/...;base64,...)` backgrounds in CSS */
import { BLANK_IMAGE_DATA_URI, blurImageDataUri, memoizedBlur } from './blur'
-import { ScrubContext } from './config'
+import { ScrubContext, isObject } from './config'
+
+// 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`.
+export const INLINED_STYLESHEET_ATTR = '_cssText'
const URL_DATA_IMAGE_RE = /url\(\s*(['"]?)(data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+)\1\s*\)/gi
@@ -34,3 +38,42 @@ export function scrubCssImages(ctx: ScrubContext, container: Record<string, unkn
}
return changed
}
+
+/** rrweb StyleSheetRule (source 8): CSS lives in `adds[].rule` and whole-sheet `replace`/`replaceSync`. */
+export function scrubStyleSheetRule(ctx: ScrubContext, data: Record<string, unknown>): boolean {
+ let changed = scrubCssImages(ctx, data, 'replace')
+ changed = scrubCssImages(ctx, data, 'replaceSync') || changed
+ return scrubRuleList(ctx, data.adds) || changed
+}
+
+/** rrweb StyleDeclaration (source 13): CSS value lives in `set.value`. */
+export function scrubStyleDeclaration(ctx: ScrubContext, data: Record<string, unknown>): boolean {
+ return isObject(data.set) ? scrubCssImages(ctx, data.set, 'value') : false
+}
+
+/** rrweb AdoptedStyleSheet (source 15): CSS lives in `styles[].rules[].rule`. */
+export function scrubAdoptedStyleSheet(ctx: ScrubContext, data: Record<string, unknown>): boolean {
+ if (!Array.isArray(data.styles)) {
+ return false
+ }
+ let changed = false
+ for (const style of data.styles) {
+ if (isObject(style)) {
+ changed = scrubRuleList(ctx, style.rules) || changed
+ }
+ }
+ return changed
+}
+
+function scrubRuleList(ctx: ScrubContext, rules: unknown): boolean {
+ if (!Array.isArray(rules)) {
+ return false
+ }
+ let changed = false
+ for (const rule of rules) {
+ if (isObject(rule)) {
+ changed = scrubCssImages(ctx, rule, 'rule') || changed
+ }
+ }
+ return changed
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
index a23663c0b0eb..9b336668a147 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
@@ -232,6 +232,17 @@ describe('anonymize/dom', () => {
expect(event.data.node.childNodes[0].childNodes[0].textContent).toBe(cssText)
})
+ it('neutralizes data-image backgrounds in an inlined stylesheet (_cssText)', () => {
+ const onePxPng =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+ const attrs: Record<string, unknown> = {
+ rel: 'stylesheet',
+ _cssText: `.a{background:url(${onePxPng})}`,
+ }
+ expect(scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })).toBe(true)
+ expect(attrs._cssText).not.toContain(onePxPng)
+ })
+
it('blurs canvas pixels inlined as rr_dataURL in a FullSnapshot', () => {
const blurCtx = { allow: defaultAllowLists(), blurJobs: [] as any[] }
const onePxPng =
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
index 83efc00c4923..77d40fca95ca 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
@@ -8,7 +8,7 @@ import {
isMediaTag,
} from './assets'
import { ScrubContext, isObject } from './config'
-import { scrubCssImages } from './css'
+import { INLINED_STYLESHEET_ATTR, scrubCssImages } from './css'
import { redactEmails, scrubText } from './text'
import { scrubUrl } from './url'
@@ -168,7 +168,7 @@ function scrubAttrs(ctx: ScrubContext, attrs: Record<string, unknown>, kind: Tag
let result
if (isUrlAttr(name)) {
result = scrubUrl(ctx, value)
- } else if (name === 'style') {
+ } else if (name === 'style' || name === INLINED_STYLESHEET_ATTR) {
changed = scrubCssImages(ctx, attrs, name) || changed
continue
} else if (isUserTextAttr(name)) {
diff --git a/rust/replay-anonymizer-node/src/bytewalk.rs b/rust/replay-anonymizer-node/src/bytewalk.rs
index 80949bb3d973..3a0546be42bc 100644
--- a/rust/replay-anonymizer-node/src/bytewalk.rs
+++ b/rust/replay-anonymizer-node/src/bytewalk.rs
@@ -836,7 +836,7 @@ impl<'c, 'a> Walker<'c, 'a> {
Some(w.ctx.blur_data_uri(s).unwrap_or_else(blank_image_data_uri))
});
}
- if name == "style" {
+ if name == "style" || name == css::INLINED_STYLESHEET_ATTR {
return w.scrub_string_value(vstart, out, |w, s| css::rewrite(w.ctx, s));
}
if is_url_attr(name) {
diff --git a/rust/replay-anonymizer-node/src/css.rs b/rust/replay-anonymizer-node/src/css.rs
index 6083c65f6765..fcccda411cec 100644
--- a/rust/replay-anonymizer-node/src/css.rs
+++ b/rust/replay-anonymizer-node/src/css.rs
@@ -4,11 +4,15 @@
use std::borrow::Cow;
-use simd_json::borrowed::Object;
+use simd_json::borrowed::{Object, Value};
use crate::blur::{blank_image_data_uri, is_image_data_uri};
use crate::context::Ctx;
-use crate::json::{as_str, string_value};
+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 {
@@ -24,6 +28,50 @@ pub fn scrub_css_images(ctx: &Ctx<'_>, container: &mut Object<'_>, key: &str) ->
}
}
+/// 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");
+ 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,
+ }
+}
+
+/// 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;
+ };
+ let mut changed = false;
+ for style in styles.iter_mut() {
+ if let Some(style) = as_object_mut(style) {
+ if let Some(rules) = style.get_mut("rules").and_then(as_array_mut) {
+ changed |= scrub_rule_list(ctx, rules);
+ }
+ }
+ }
+ changed
+}
+
+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
+}
+
pub(crate) fn rewrite(ctx: &Ctx<'_>, css: &str) -> Option<String> {
let bytes = css.as_bytes();
let mut out = String::new();
diff --git a/rust/replay-anonymizer-node/src/dom.rs b/rust/replay-anonymizer-node/src/dom.rs
index 0c8d526a0a83..3a46a8e553a6 100644
--- a/rust/replay-anonymizer-node/src/dom.rs
+++ b/rust/replay-anonymizer-node/src/dom.rs
@@ -9,7 +9,7 @@ use crate::assets::{
INLINE_IMAGE_ATTR,
};
use crate::context::Ctx;
-use crate::css::scrub_css_images;
+use crate::css::{scrub_css_images, INLINED_STYLESHEET_ATTR};
use crate::json::{
as_array_mut, as_object_mut, as_small_uint, as_str, is_object, is_true, key, string_value,
};
@@ -210,7 +210,7 @@ fn scrub_attrs(ctx: &Ctx<'_>, attrs: &mut Object<'_>, kind: TagKind) -> bool {
continue;
}
// Inlined rendered pixels (`rr_dataURL`): blur the image, on any tag.
- if name == INLINE_IMAGE_ATTR || name == "style" {
+ if name == INLINE_IMAGE_ATTR || name == "style" || name == INLINED_STYLESHEET_ATTR {
deferred.push(name.to_string());
continue;
}
@@ -330,20 +330,25 @@ mod tests {
#[test]
fn css_data_image_background_is_neutralized() {
- let uri = png_data_uri(8, 8, [200, 200, 10, 255]);
- let style = serde_json::to_string(&format!("background:url({uri})")).unwrap();
- let data = format!(
- r#"{{"node":{{"type":0,"childNodes":[{{"type":2,"tagName":"div","attributes":{{"style":{style}}},"childNodes":[]}}]}},"initialOffset":{{"top":0,"left":0}}}}"#
- );
- let out = scrub_snapshot(&data);
- let scrubbed = out["node"]["childNodes"][0]["attributes"]["style"]
- .as_str()
- .unwrap();
- assert!(!scrubbed.contains(&uri), "the original image must be gone");
- assert!(
- scrubbed.contains("url(data:image/png"),
- "replaced with a data image: {scrubbed}"
- );
+ for attr in ["style", INLINED_STYLESHEET_ATTR] {
+ let uri = png_data_uri(8, 8, [200, 200, 10, 255]);
+ let css = serde_json::to_string(&format!("background:url({uri})")).unwrap();
+ let data = format!(
+ r#"{{"node":{{"type":0,"childNodes":[{{"type":2,"tagName":"div","attributes":{{"{attr}":{css}}},"childNodes":[]}}]}},"initialOffset":{{"top":0,"left":0}}}}"#
+ );
+ let out = scrub_snapshot(&data);
+ let scrubbed = out["node"]["childNodes"][0]["attributes"][attr]
+ .as_str()
+ .unwrap();
+ assert!(
+ !scrubbed.contains(&uri),
+ "the original image must be gone from {attr}"
+ );
+ assert!(
+ scrubbed.contains("url(data:image/png"),
+ "replaced with a data image in {attr}: {scrubbed}"
+ );
+ }
}
#[test]
diff --git a/rust/replay-anonymizer-node/src/event.rs b/rust/replay-anonymizer-node/src/event.rs
index e447cb5db38b..d48189df820b 100644
--- a/rust/replay-anonymizer-node/src/event.rs
+++ b/rust/replay-anonymizer-node/src/event.rs
@@ -9,6 +9,7 @@ use simd_json::StaticNode;
use crate::allow_lists::AllowLists;
use crate::canvas::scrub_canvas_mutation;
use crate::context::Ctx;
+use crate::css::{scrub_adopted_style_sheet, scrub_style_declaration, scrub_style_sheet_rule};
use crate::cv::{scrub_compressed_full_snapshot, scrub_compressed_mutation};
use crate::dom::{scrub_full_snapshot, scrub_mutation};
use crate::json::{
@@ -29,7 +30,10 @@ pub const TYPE_PLUGIN: u8 = 6;
// RRWebEventSource (incremental)
pub const SOURCE_MUTATION: u8 = 0;
pub const SOURCE_INPUT: u8 = 5;
+pub const SOURCE_STYLESHEET_RULE: u8 = 8;
pub const SOURCE_CANVAS_MUTATION: u8 = 9;
+pub const SOURCE_STYLE_DECLARATION: u8 = 13;
+pub const SOURCE_ADOPTED_STYLESHEET: u8 = 15;
pub const NETWORK_PLUGIN: &str = "rrweb/network@1";
pub const CONSOLE_PLUGIN: &str = "rrweb/console@1";
@@ -128,6 +132,15 @@ pub fn route_data(
"text",
)),
Some(SOURCE_CANVAS_MUTATION) => Ok(scrub_canvas_mutation(ctx, data)),
+ Some(SOURCE_STYLESHEET_RULE) => {
+ Ok(scrub_style_sheet_rule(ctx, as_object_mut(data).unwrap()))
+ }
+ Some(SOURCE_STYLE_DECLARATION) => {
+ Ok(scrub_style_declaration(ctx, as_object_mut(data).unwrap()))
+ }
+ Some(SOURCE_ADOPTED_STYLESHEET) => {
+ Ok(scrub_adopted_style_sheet(ctx, as_object_mut(data).unwrap()))
+ }
_ => Ok(false),
}
}
diff --git a/rust/replay-anonymizer-node/src/snapshot.rs b/rust/replay-anonymizer-node/src/snapshot.rs
index 0a5362306ac3..73bdbd1302c2 100644
--- a/rust/replay-anonymizer-node/src/snapshot.rs
+++ b/rust/replay-anonymizer-node/src/snapshot.rs
@@ -29,7 +29,8 @@ use simd_json::prelude::Writable;
use crate::allow_lists::AllowLists;
use crate::context::Ctx;
use crate::event::{
- route_data, route_event, SOURCE_CANVAS_MUTATION, SOURCE_INPUT, SOURCE_MUTATION, TYPE_CUSTOM,
+ route_data, route_event, SOURCE_ADOPTED_STYLESHEET, SOURCE_CANVAS_MUTATION, SOURCE_INPUT,
+ SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,
TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META, TYPE_PLUGIN,
};
use crate::json::{
@@ -993,7 +994,7 @@ fn process_event_at(
return Ok(end);
}
- // Incremental events only route to a scrubber for mutation/input/canvas sources.
+ // Incremental events only route to a scrubber for mutation/input/canvas/stylesheet sources.
let source = es
.source
.and_then(|s| scan::parse_number(inner, s))
@@ -1001,7 +1002,12 @@ fn process_event_at(
if ty == Some(TYPE_INCREMENTAL)
&& !matches!(
source,
- Some(SOURCE_MUTATION) | Some(SOURCE_INPUT) | Some(SOURCE_CANVAS_MUTATION)
+ Some(SOURCE_MUTATION)
+ | Some(SOURCE_INPUT)
+ | Some(SOURCE_CANVAS_MUTATION)
+ | Some(SOURCE_STYLESHEET_RULE)
+ | Some(SOURCE_STYLE_DECLARATION)
+ | Some(SOURCE_ADOPTED_STYLESHEET)
)
{
pass_through(inner, span, ts, ty, Some(&es), sink);
diff --git a/rust/replay-anonymizer-node/tests/snapshot.rs b/rust/replay-anonymizer-node/tests/snapshot.rs
index 6811cc1b029c..cd51e9c743ce 100644
--- a/rust/replay-anonymizer-node/tests/snapshot.rs
+++ b/rust/replay-anonymizer-node/tests/snapshot.rs
@@ -532,6 +532,59 @@ fn differential_stream_vs_tree() {
);
}
+#[test]
+fn stylesheet_data_images_are_neutralized_and_engines_agree() {
+ // CSS reaches the anonymizer as an inlined `<link>` `_cssText` attribute and as the incremental
+ // stylesheet events (StyleSheetRule/StyleDeclaration/AdoptedStyleSheet); a data-image in any of
+ // them must be blurred like a `style` attribute, and the byte walk must match the tree on these
+ // arms (the shared fixture corpus carries no CSS cases, so the differential alone never hits them).
+ const ONE_PX: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg==";
+ let css = format!(".a{{background:url({ONE_PX})}}");
+ let inner = snapshot_message(json!([
+ {
+ "type": 2,
+ "timestamp": TS0,
+ "data": {
+ "node": {"type": 0, "childNodes": [{
+ "type": 2,
+ "tagName": "link",
+ "attributes": {"rel": "stylesheet", "_cssText": css},
+ "childNodes": []
+ }]},
+ "initialOffset": {"top": 0, "left": 0}
+ }
+ },
+ {
+ "type": 3,
+ "timestamp": TS0 + 1.0,
+ "data": {"source": 8, "id": 1, "adds": [{"rule": css}], "replace": css, "replaceSync": css}
+ },
+ {
+ "type": 3,
+ "timestamp": TS0 + 2.0,
+ "data": {"source": 13, "id": 1, "index": [0], "set": {"property": "background", "value": format!("url({ONE_PX})")}}
+ },
+ {
+ "type": 3,
+ "timestamp": TS0 + 3.0,
+ "data": {"source": 15, "id": 1, "styleIds": [1], "styles": [{"styleId": 1, "rules": [{"rule": css}]}]}
+ },
+ ]));
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ assert_stream_matches_tree(
+ &allow,
+ &serde_json::to_string(&inner).unwrap(),
+ "css data images",
+ );
+ let out = run(&allow, &payload_of(&inner)).expect("anonymizes");
+ let lines = String::from_utf8(out.lines.clone()).unwrap();
+ assert_eq!(parse_lines(&out.lines).len(), 4, "all four events survive");
+ assert!(
+ !lines.contains(ONE_PX),
+ "raw css data image must not pass through any stylesheet route"
+ );
+}
+
#[test]
fn differential_cv_stream_vs_tree() {
// Compressed with flate2 (an independent codec from the libdeflate legs under test); latin-1