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.

feat(replay-anonymizer): accept only posthog-js canvas snapshot frames (#116875)

Nicholas Waltzb3068b2c22be
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 66e572aae98c..9d2b144be64f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -86,6 +86,12 @@ export class MlMirrorMetrics {
labelNames: ['source', 'property', 'kind'],
})
+ private static readonly mlScrubDrops = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_scrub_drops_total',
+ help: 'Replay content the anonymizer removed outright rather than replaced with a scrubbed copy, by reason',
+ labelNames: ['reason'],
+ })
+
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',
@@ -248,6 +254,12 @@ export class MlMirrorMetrics {
}
}
+ public static incrementMlScrubDrops(reason: string, count: number): void {
+ if (count > 0) {
+ this.mlScrubDrops.labels(reason).inc(count)
+ }
+ }
+
public static observeMlUrlBytes(bytes: number): void {
if (this.urlBytesSeen++ % URL_BYTES_SAMPLE_RATE === 0) {
this.mlUrlBytes.observe(bytes)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
index a9df1051c955..75a50d10bd34 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts
@@ -29,6 +29,15 @@ async function metricValue(name: string): Promise<number> {
return values[0]?.value ?? 0
}
+async function scrubDropMetricValue(reason: string): Promise<number> {
+ const metric = register.getSingleMetric('recording_blob_ingestion_v2_ml_scrub_drops_total')
+ if (!metric) {
+ return 0
+ }
+ const { values } = await metric.get()
+ return values.find((value) => value.labels.reason === reason)?.value ?? 0
+}
+
async function imageSourceMetricValue(source: string, property: string, kind: string): Promise<number> {
const metric = register.getSingleMetric(IMAGE_SOURCE_METRIC)
if (!metric) {
@@ -122,7 +131,8 @@ describe('createParseAndAnonymizeMessageStep', () => {
it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {
const jsonLdEventsBefore = await metricValue(JSON_LD_EVENT_METRIC)
- addonSuccess({ jsonLdEventCount: 2 })
+ const canvasDropsBefore = await scrubDropMetricValue('canvas_mutation_not_snapshot_frame')
+ addonSuccess({ jsonLdEventCount: 2, scrubDrops: [{ reason: 'canvas_mutation_not_snapshot_frame', count: 3 }] })
const result = await step({ message: kafkaMessage(), headers, team })
expect(result.type).toBe(PipelineResultType.OK)
@@ -141,6 +151,7 @@ describe('createParseAndAnonymizeMessageStep', () => {
expect(parsed.snapshot_library).toBe('posthog-js')
expect(parsed.metadata).toEqual({ partition: 3, topic: 'snapshots', rawSize: 2, offset: 42, timestamp: now })
await expect(metricValue(JSON_LD_EVENT_METRIC)).resolves.toBe(jsonLdEventsBefore + 2)
+ await expect(scrubDropMetricValue('canvas_mutation_not_snapshot_frame')).resolves.toBe(canvasDropsBefore + 3)
})
it('normalizes a UUID session id before comparing against the header', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
index f4b0e4783eec..bafc01bd3799 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts
@@ -273,6 +273,9 @@ export function createParseAndAnonymizeMessageStep<
}
recordImageSources(meta)
+ for (const drop of meta.scrubDrops ?? []) {
+ MlMirrorMetrics.incrementMlScrubDrops(drop.reason, drop.count)
+ }
MlMirrorMetrics.incrementMlJsonLdEvents(meta.jsonLdEventCount)
const parsedMessage: ParsedMessageData = {
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 26ecf9f5a013..a662d1eea34d 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9553,7 +9553,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.8.0"
+version = "0.9.0"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
index 60dd4f6e9da9..4d414771340c 100644
--- a/rust/replay-anonymizer-node/src/index.ts
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -76,6 +76,7 @@ export interface AnonymizeMeta {
imageSources?: AnonymizeImageSourceCount[]
/** Counts by reason for the URLs the collector refused. Absent when it refused none. */
urlDeclines?: { reason: string; count: number }[]
+ scrubDrops?: { reason: string; count: number }[]
}
/**
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index ff2f8e3b7e9c..51db8f1edc40 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.8.0"
+version = "0.9.0"
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/blur.rs b/rust/replay-anonymizer/src/blur.rs
index 26ef1991630c..085c2add466f 100644
--- a/rust/replay-anonymizer/src/blur.rs
+++ b/rust/replay-anonymizer/src/blur.rs
@@ -3,7 +3,7 @@
//! sidecar still uses, with matching params), so tests assert structure (decodes to W x H PNG), not bytes.
use base64::Engine;
-use image::{DynamicImage, GenericImageView, RgbaImage};
+use image::{DynamicImage, GenericImageView};
const DOWNSAMPLE_RATIO: f32 = 0.12;
const BLUR_SIGMA: f32 = 2.34;
@@ -135,33 +135,6 @@ pub fn blur_image_data_uri(s: &str) -> Option<String> {
Some(format!("data:image/png;base64,{encoded}"))
}
-/// De-identify raw RGBA pixels: downsample + blur, then scale back to the original W x H, preserving
-/// byte length (`4*W*H`) so it slots back into a `putImageData` ImageData. None if it can't.
-pub fn pixelate_raw_rgba(base64_pixels: &str, width: u32, height: u32) -> Option<String> {
- let buf = base64::engine::general_purpose::STANDARD
- .decode(base64_pixels.as_bytes())
- .ok()?;
- // `checked_mul`: `w*h*4` on attacker-controlled dims can overflow usize; overflow -> reject.
- let expected = (width as usize)
- .checked_mul(height as usize)
- .and_then(|wh| wh.checked_mul(4))?;
- if buf.len() != expected {
- return None;
- }
- let img = RgbaImage::from_raw(width, height, buf)?;
- let dynamic = DynamicImage::ImageRgba8(img);
- let (sw, sh) = target_dims(width, height);
- let small = dynamic
- .resize_exact(sw, sh, image::imageops::FilterType::Triangle)
- .blur(BLUR_SIGMA);
- let restored = small.resize_exact(width, height, image::imageops::FilterType::Triangle);
- let out = restored.to_rgba8().into_raw();
- if out.len() != expected {
- return None;
- }
- Some(base64::engine::general_purpose::STANDARD.encode(&out))
-}
-
/// Split a `data:<mime>;...,<base64>` URI into (mime, base64). None if not a data URI.
pub fn split_data_uri(uri: &str) -> Option<(String, String)> {
let rest = uri.strip_prefix("data:")?;
@@ -243,22 +216,4 @@ mod tests {
assert!(blur_image_data_uri("data:text/plain;base64,aGVsbG8=").is_none());
assert!(blur_image_data_uri("not a data uri").is_none());
}
-
- #[test]
- fn pixelate_preserves_rgba_byte_length() {
- let (w, h) = (8u32, 8u32);
- let raw = vec![200u8; (w * h * 4) as usize];
- let b64 = base64::engine::general_purpose::STANDARD.encode(&raw);
- let out = pixelate_raw_rgba(&b64, w, h).expect("pixelate should succeed");
- let out_bytes = base64::engine::general_purpose::STANDARD
- .decode(&out)
- .unwrap();
- assert_eq!(out_bytes.len(), raw.len());
- }
-
- #[test]
- fn pixelate_rejects_wrong_length() {
- let b64 = base64::engine::general_purpose::STANDARD.encode([0u8; 10]);
- assert!(pixelate_raw_rgba(&b64, 8, 8).is_none());
- }
}
diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rs
index 4e8148d852a5..8f9a4fce47b9 100644
--- a/rust/replay-anonymizer/src/bytewalk.rs
+++ b/rust/replay-anonymizer/src/bytewalk.rs
@@ -20,7 +20,7 @@ use crate::assets::{
};
use crate::blur::is_image_data_uri;
use crate::collect::is_image_ref_strict;
-use crate::context::{Ctx, ImageSource};
+use crate::context::{CountCheckpoint, Ctx, ImageSource};
use crate::css;
use crate::dom::{
classify_tag, data_attr_looks_sensitive, is_data_attr, is_url_attr, is_user_text_attr,
@@ -603,7 +603,9 @@ impl<'c, 'a> Walker<'c, 'a> {
let base = self.seen.len();
let node_mark = out.len();
let changed_before = self.changed;
- let result = self.walk_node_inner(base, start, parent, node_mark, changed_before, out);
+ let counts = self.ctx.count_checkpoint();
+ let result =
+ self.walk_node_inner(base, start, parent, node_mark, changed_before, counts, out);
self.seen.truncate(base);
self.depth -= 1;
result
@@ -617,6 +619,7 @@ impl<'c, 'a> Walker<'c, 'a> {
parent: ParentKind,
node_mark: usize,
changed_before: bool,
+ counts: CountCheckpoint,
out: &mut Vec<u8>,
) -> Option<usize> {
let bytes = self.bytes;
@@ -630,6 +633,8 @@ impl<'c, 'a> Walker<'c, 'a> {
let mut attrs_m: Option<(Span, Span)> = None;
// childNodes: emitted range in `out` + source span, for the rare late splice.
let mut children: Option<((usize, usize), Span, Span)> = None;
+ // Counts before the optimistic children walk, restored when that walk is redone.
+ let mut children_counts = counts;
let mut pos = start + 1;
let mut first = true;
@@ -690,6 +695,7 @@ impl<'c, 'a> Walker<'c, 'a> {
out.extend_from_slice(&bytes[key.0 - 1..key_end]);
out.push(b':');
let seg_start = out.len();
+ children_counts = self.ctx.count_checkpoint();
let vend = self.walk_array(vstart, out, &mut |w, p, o| {
w.walk_node(p, ParentKind::Other, o)
})?;
@@ -726,12 +732,14 @@ impl<'c, 'a> Walker<'c, 'a> {
Some(NODE_ELEMENT) => {
if let (TagKind::Script, Some((seg, _, src))) = (kind, children) {
// Script content is code — the tree leaves the children untouched.
+ self.ctx.discard_walk(children_counts);
let verbatim = &bytes[src.0..src.1];
out.splice(seg.0..seg.1, verbatim.iter().copied());
}
if let (TagKind::Style, Some((seg, _, src))) = (kind, children) {
// Style children are CSS text: rebuild that segment with the style parent.
let mut tmp = Vec::with_capacity(src.1 - src.0);
+ self.ctx.restore_counts(children_counts);
self.walk_array(src.0, &mut tmp, &mut |w, p, o| {
w.walk_node(p, ParentKind::Style, o)
})?;
@@ -740,6 +748,7 @@ impl<'c, 'a> Walker<'c, 'a> {
if tag.eq_ignore_ascii_case("picture") {
if let Some((seg, _, src)) = children {
let mut tmp = Vec::with_capacity(src.1 - src.0);
+ self.ctx.restore_counts(children_counts);
self.walk_array(src.0, &mut tmp, &mut |w, p, o| {
w.walk_node(p, ParentKind::Picture, o)
})?;
@@ -754,7 +763,7 @@ impl<'c, 'a> Walker<'c, 'a> {
.ok()?
.is_some()
{
- return self.redo_node(start, end, parent, node_mark, out);
+ return self.redo_node(start, end, parent, node_mark, counts, out);
}
emit_deferred_key(bytes, key, &mut emitted, out);
let hidden_pixel = tag.eq_ignore_ascii_case("img")
@@ -777,6 +786,7 @@ impl<'c, 'a> Walker<'c, 'a> {
Some(NODE_TEXT) if parent == ParentKind::Script => {
// The tree never touches script text nodes: undo and re-emit verbatim.
out.truncate(node_mark);
+ self.ctx.discard_walk(counts);
out.extend_from_slice(&bytes[start..end]);
self.changed = changed_before;
return Some(end);
@@ -784,7 +794,7 @@ impl<'c, 'a> Walker<'c, 'a> {
Some(NODE_TEXT) | Some(NODE_COMMENT) | Some(NODE_CDATA) => {
if children.map(|(seg, ..)| seg.0 != seg.1).unwrap_or(false) && node_changed {
// A text-ish node with scrubbed childNodes has no tree equivalent: redo.
- return self.redo_node(start, end, parent, node_mark, out);
+ return self.redo_node(start, end, parent, node_mark, counts, out);
}
let styled = ty == Some(NODE_TEXT)
&& (parent == ParentKind::Style
@@ -792,7 +802,7 @@ impl<'c, 'a> Walker<'c, 'a> {
.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);
+ return self.redo_node(start, end, parent, node_mark, counts, out);
}
if let Some((key, v)) = text_m {
emit_deferred_key(bytes, key, &mut emitted, out);
@@ -807,7 +817,7 @@ impl<'c, 'a> Walker<'c, 'a> {
if attrs_m.is_some() {
// The tree ignores document attributes but still scrubs the children — no
// optimistic emission matches that; let the tree do this node.
- return self.redo_node(start, end, parent, node_mark, out);
+ return self.redo_node(start, end, parent, node_mark, counts, out);
}
// Children stay as walked (documents parent as Other); scalars verbatim.
for (key, v) in [ty_m, tag_m, is_style_m, text_m].into_iter().flatten() {
@@ -820,6 +830,7 @@ impl<'c, 'a> Walker<'c, 'a> {
// re-emit verbatim either way.
_ => {
out.truncate(node_mark);
+ self.ctx.discard_walk(counts);
out.extend_from_slice(&bytes[start..end]);
self.changed = changed_before;
return Some(end);
@@ -837,10 +848,12 @@ impl<'c, 'a> Walker<'c, 'a> {
end: usize,
parent: ParentKind,
node_mark: usize,
+ counts: CountCheckpoint,
out: &mut Vec<u8>,
) -> Option<usize> {
use simd_json::prelude::Writable;
out.truncate(node_mark);
+ self.ctx.restore_counts(counts);
let span = &self.bytes[start..end];
crate::json::reject_if_too_deep(span, "node").ok()?;
let mut scratch = span.to_vec();
diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rs
index 705827ec0493..fa28bd073668 100644
--- a/rust/replay-anonymizer/src/canvas.rs
+++ b/rust/replay-anonymizer/src/canvas.rs
@@ -1,190 +1,233 @@
-//! Scrubs rrweb CanvasMutation events: redacts text drawn via fill/strokeText and blurs drawn images
-//! and canvas snapshots. Blur runs inline (native), so the object lands on its final blurred/blanked
-//! value directly.
+//! Scrubs rrweb CanvasMutation events.
+//!
+//! posthog-js records a canvas in one way only: a snapshot frame that clears the canvas and draws one
+//! encoded image of it. That frame is rebuilt from its known fields, and its image goes to the image
+//! scrub. Any other canvas mutation (drawing commands, text, raw pixels, WebGL) cannot be scrubbed as
+//! an image, so the event keeps only its identity and an empty command list.
-use base64::Engine;
use simd_json::borrowed::{Object, Value};
-use crate::blur::{is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};
+use crate::blur::{split_data_uri, BLANK_PNG_BASE64};
use crate::collect::{is_image_ref, is_image_ref_strict, normalize_collected_mime};
use crate::context::Ctx;
use crate::images::ImageFallback;
use crate::json::{
- as_array, as_array_mut, as_object, as_object_mut, as_str, as_u32, as_usize, key, string_value,
+ as_array, as_array_mut, as_f64, as_object, as_object_mut, as_str, as_u32, key, string_value,
};
-use crate::url::scrub_url;
-fn b64() -> base64::engine::general_purpose::GeneralPurpose {
- base64::engine::general_purpose::STANDARD
-}
+const FRAME_MIMES: &[&str] = &["image/webp", "image/png", "image/jpeg"];
+const CONTEXT_2D: u32 = 0;
+const DATA_KEYS: &[&str] = &[
+ "source",
+ "id",
+ "type",
+ "commands",
+ "displayWidth",
+ "displayHeight",
+];
+pub(crate) const REJECTED_CANVAS_MUTATION: &str = "canvas_mutation_not_snapshot_frame";
/// Scrub a CanvasMutation `data` object in place. Returns whether anything changed.
pub fn scrub_canvas_mutation(ctx: &Ctx<'_>, data: &mut Value<'_>) -> bool {
let Some(obj) = as_object_mut(data) else {
return false;
};
- let has_commands = matches!(obj.get("commands"), Some(Value::Array(_)));
- if has_commands {
- let mut changed = false;
- let commands = obj.get_mut("commands").and_then(as_array_mut).unwrap();
- for cmd in commands.iter_mut() {
- if let Some(c) = as_object_mut(cmd) {
- changed |= scrub_command(ctx, c);
- }
+ if is_snapshot_frame(obj) {
+ let mut changed = prune_to_frame(obj);
+ if let Some(blob) = frame_blob_mut(obj) {
+ changed |= scrub_frame_blob(ctx, blob);
}
changed
- } else if obj.get("property").and_then(as_str).is_some() {
- // Flattened single-command form: `data` itself is the command.
- scrub_command(ctx, obj)
} else {
- false
+ let changed = empty_mutation(obj);
+ if changed {
+ ctx.record_scrub_drop(REJECTED_CANVAS_MUTATION);
+ }
+ changed
}
}
-// Canvas API calls whose leading string arguments are user-visible text.
-fn is_text_command(property: &str) -> bool {
- matches!(property, "fillText" | "strokeText")
+fn is_number(v: &Value<'_>) -> bool {
+ as_f64(v).is_some_and(f64::is_finite)
}
-fn scrub_command(ctx: &Ctx<'_>, cmd: &mut Object<'_>) -> bool {
- let is_text = cmd
- .get("property")
- .and_then(as_str)
- .map(is_text_command)
- .unwrap_or(false);
- let Some(args) = cmd.get_mut("args").and_then(as_array_mut) else {
- return false;
- };
- let mut changed = false;
+fn is_property(cmd: &Object<'_>, name: &str) -> bool {
+ cmd.get("property").and_then(as_str) == Some(name)
+}
- // Text drawn onto the canvas: fillText/strokeText take the text as leading string args.
- if is_text {
- for a in args.iter_mut() {
- if let Value::String(s) = a {
- if let Some(nv) = crate::text::scrub_text(ctx.allow, s) {
- *a = string_value(nv);
- changed = true;
- }
- }
- }
- }
+fn rr_type_is(obj: &Object<'_>, name: &str) -> bool {
+ obj.get("rr_type").and_then(as_str) == Some(name)
+}
- // Images/snapshots can appear anywhere in the (recursive) arg tree.
- for a in args.iter_mut() {
- changed |= blur_canvas_arg(ctx, a);
- }
- changed
+fn numbers(args: &[Value<'_>]) -> bool {
+ args.iter().all(is_number)
}
-/// Recursively neutralize+blur image data inside a canvas arg, mutating in place.
-fn blur_canvas_arg(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
- match value {
- Value::String(s) => {
- if is_image_data_uri(s) {
- let b = ctx.scrub_image(s, ImageFallback::Blank);
- *value = string_value(b);
- return true;
- }
- return false;
- }
- Value::Array(arr) => {
- let mut changed = false;
- for item in arr.iter_mut() {
- changed |= blur_canvas_arg(ctx, item);
- }
- return changed;
- }
- _ => {}
+/// `{ id, type: 2D, commands: [clearRect(4 numbers), drawImage(ImageBitmap(Blob), 4 numbers)] }`,
+/// with any display size given as numbers.
+fn is_snapshot_frame(obj: &Object<'_>) -> bool {
+ if obj.get("id").and_then(as_u32).is_none()
+ || obj.get("type").and_then(as_u32) != Some(CONTEXT_2D)
+ {
+ return false;
}
-
- let Some(obj) = as_object_mut(value) else {
+ if ["displayWidth", "displayHeight"]
+ .iter()
+ .any(|name| obj.get(*name).is_some_and(|v| !is_number(v)))
+ {
+ return false;
+ }
+ let Some([clear, draw]) = obj.get("commands").and_then(as_array).map(Vec::as_slice) else {
return false;
};
+ let (Some(clear), Some(draw)) = (as_object(clear), as_object(draw)) else {
+ return false;
+ };
+ let clear_ok = is_property(clear, "clearRect")
+ && clear
+ .get("args")
+ .and_then(as_array)
+ .is_some_and(|args| args.len() == 4 && numbers(args));
+ let draw_ok = is_property(draw, "drawImage")
+ && draw.get("args").and_then(as_array).is_some_and(|args| {
+ // posthog-js before 1.391 drew at the origin without a size, so `[bitmap, x, y]`.
+ matches!(args.len(), 3 | 5)
+ && numbers(&args[1..])
+ && as_object(&args[0]).is_some_and(is_frame_bitmap)
+ });
+ clear_ok && draw_ok
+}
- // Serialized image element: { rr_type, src }. Data-URI src is an embedded image; a remote src is a
- // URL that may itself carry PII.
- if let Some(src) = obj.get("src").and_then(as_str).map(str::to_string) {
- if is_image_data_uri(&src) {
- let b = ctx.scrub_image(&src, ImageFallback::Blank);
- obj.insert(key("src"), string_value(b));
- return true;
- }
- return match scrub_url(ctx, &src) {
- Some(v) => {
- obj.insert(key("src"), string_value(v));
- true
- }
- None => false,
- };
- }
+fn is_frame_bitmap(bitmap: &Object<'_>) -> bool {
+ rr_type_is(bitmap, "ImageBitmap")
+ && matches!(
+ bitmap.get("args").and_then(as_array).map(Vec::as_slice),
+ Some([blob]) if as_object(blob).is_some_and(is_frame_blob)
+ )
+}
- let rr_type = obj.get("rr_type").and_then(as_str).map(str::to_string);
+fn is_frame_blob(blob: &Object<'_>) -> bool {
+ rr_type_is(blob, "Blob")
+ && blob
+ .get("type")
+ .and_then(as_str)
+ .is_some_and(|mime| FRAME_MIMES.contains(&mime))
+ && matches!(
+ blob.get("data").and_then(as_array).map(Vec::as_slice),
+ Some([buffer]) if as_object(buffer).is_some_and(|b| {
+ rr_type_is(b, "ArrayBuffer") && b.get("base64").and_then(as_str).is_some()
+ })
+ )
+}
- // Encoded image snapshot: { rr_type: 'Blob', type: 'image/...', data: [ {rr_type:'ArrayBuffer', base64} ] }.
- if rr_type.as_deref() == Some("Blob") {
- if let Some(t) = obj.get("type").and_then(as_str) {
- if t.starts_with("image/") {
- return blur_blob_image(ctx, obj);
+fn prune_to_frame(obj: &mut Object<'_>) -> bool {
+ let mut changed = retain_keys(obj, DATA_KEYS);
+ let Some(commands) = obj.get_mut("commands").and_then(as_array_mut) else {
+ return changed;
+ };
+ for command in commands.iter_mut() {
+ let Some(command) = as_object_mut(command) else {
+ continue;
+ };
+ changed |= retain_keys(command, &["property", "args"]);
+ }
+ if let Some(bitmap) = commands
+ .get_mut(1)
+ .and_then(as_object_mut)
+ .and_then(|draw| draw.get_mut("args"))
+ .and_then(as_array_mut)
+ .and_then(|args| args.first_mut())
+ .and_then(as_object_mut)
+ {
+ changed |= retain_keys(bitmap, &["rr_type", "args"]);
+ if let Some(blob) = bitmap
+ .get_mut("args")
+ .and_then(as_array_mut)
+ .and_then(|args| args.first_mut())
+ .and_then(as_object_mut)
+ {
+ changed |= retain_keys(blob, &["rr_type", "type", "data"]);
+ if let Some(buffer) = blob
+ .get_mut("data")
+ .and_then(as_array_mut)
+ .and_then(|data| data.first_mut())
+ .and_then(as_object_mut)
+ {
+ changed |= retain_keys(buffer, &["rr_type", "base64"]);
}
}
}
+ changed
+}
- // Raw pixels: { rr_type: 'ImageData', args: [pixels, width, height] } (putImageData).
- if rr_type.as_deref() == Some("ImageData") {
- return blur_image_data(ctx, obj);
- }
+fn retain_keys(obj: &mut Object<'_>, keep: &[&str]) -> bool {
+ let before = obj.len();
+ obj.retain(|name, _| keep.contains(&name.as_ref()));
+ obj.len() != before
+}
- // Otherwise recurse into nested arg/data arrays (ImageBitmap -> Blob, etc.).
- let mut changed = false;
- if let Some(args) = obj.get_mut("args").and_then(as_array_mut) {
- for it in args.iter_mut() {
- changed |= blur_canvas_arg(ctx, it);
- }
- }
- if let Some(data) = obj.get_mut("data").and_then(as_array_mut) {
- for it in data.iter_mut() {
- changed |= blur_canvas_arg(ctx, it);
+fn frame_blob_mut<'a, 'v>(obj: &'a mut Object<'v>) -> Option<&'a mut Object<'v>> {
+ obj.get_mut("commands")
+ .and_then(as_array_mut)?
+ .get_mut(1)
+ .and_then(as_object_mut)?
+ .get_mut("args")
+ .and_then(as_array_mut)?
+ .first_mut()
+ .and_then(as_object_mut)?
+ .get_mut("args")
+ .and_then(as_array_mut)?
+ .first_mut()
+ .and_then(as_object_mut)
+}
+
+fn empty_mutation(obj: &mut Object<'_>) -> bool {
+ let already_empty = obj
+ .get("commands")
+ .and_then(as_array)
+ .is_some_and(Vec::is_empty);
+ let mut changed = !already_empty;
+ changed |= retain_keys(obj, &["source", "id", "type", "commands"]);
+ for name in ["id", "type"] {
+ if obj.get(name).is_some_and(|v| as_u32(v).is_none()) {
+ obj.remove(name);
+ changed = true;
}
}
+ obj.insert(key("commands"), Value::Array(Box::default()));
changed
}
-/// Blur the encoded image bytes inside an image Blob, neutralizing them first (fail-safe).
-fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
+fn scrub_frame_blob(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
let mime = blob
.get("type")
.and_then(as_str)
.unwrap_or("image/png")
.to_string();
- let Some(idx) = find_array_buffer_index(blob) else {
- return false;
- };
- let base64 = match blob
+ let Some(base64) = blob
.get("data")
.and_then(as_array)
- .and_then(|d| d.get(idx))
+ .and_then(|data| data.first())
.and_then(as_object)
- .and_then(|o| o.get("base64"))
+ .and_then(|buffer| buffer.get("base64"))
.and_then(as_str)
- {
- Some(s) => s.to_string(),
- None => return false,
+ .map(str::to_string)
+ else {
+ return false;
};
// A content ref left by an earlier pass. Reassembling it into `data:{mime};base64,image:...`
- // below yields a URI that cannot decode, which `scrub_image` fails safe to a blank pixel —
- // destroying the join key and stranding the image. Left alone only on an explicitly trusted
- // re-scrub, and only when fully well-formed: see `assets::apply_blur`.
+ // yields a URI that cannot decode, which `scrub_image` fails safe to a blank pixel — destroying
+ // the join key and stranding the image. Left alone only on an explicitly trusted re-scrub, and
+ // only when fully well-formed: see `assets::apply_blur`.
if ctx.keeps_image_refs() && is_image_ref_strict(&base64) {
return false;
}
- let original = format!("data:{mime};base64,{base64}");
- // scrub_image never fails outward (fallbacks are baked in). The collection lane's ref
- // replaces the payload wholesale (it is the consumer's join key, not decodable bytes); the
- // mime survives only through the raster allowlist — the blur path re-encoded and overwrote
- // it, so the ref path must not let a client string through this field either. Otherwise the
- // split always succeeds — the stated fallback keeps the fail-safe explicit if the URI shape
- // ever changes.
- let scrubbed = ctx.scrub_image(&original, ImageFallback::Blank);
+ let scrubbed = ctx.scrub_image(
+ &format!("data:{mime};base64,{base64}"),
+ ImageFallback::Blank,
+ );
+ // The collection lane's ref replaces the payload wholesale, and the mime survives only through
+ // the raster allowlist, so no client string reaches the output through this field.
let (new_b64, new_type) = if is_image_ref(&scrubbed) {
(scrubbed, normalize_collected_mime(&mime).to_string())
} else {
@@ -193,327 +236,184 @@ fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
None => (BLANK_PNG_BASE64.to_string(), "image/png".to_string()),
}
};
- if let Some(ab) = blob
+ if let Some(buffer) = blob
.get_mut("data")
.and_then(as_array_mut)
- .and_then(|d| d.get_mut(idx))
+ .and_then(|data| data.first_mut())
.and_then(as_object_mut)
{
- ab.insert(key("base64"), string_value(new_b64));
+ buffer.insert(key("base64"), string_value(new_b64));
}
blob.insert(key("type"), string_value(new_type));
true
}
-fn find_array_buffer_index(blob: &Object<'_>) -> Option<usize> {
- blob.get("data").and_then(as_array).and_then(|data| {
- data.iter().position(|d| {
- as_object(d)
- .map(|o| {
- o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
- && o.get("base64").and_then(as_str).is_some()
- })
- .unwrap_or(false)
- })
- })
-}
-
-/// Pixelate raw ImageData pixels in place (blanked, with the downsampled-and-restored region merged
-/// back in on success). Falls back to blanking every nested ArrayBuffer for an unexpected shape.
-fn blur_image_data<'v>(ctx: &Ctx<'_>, image_data: &mut Object<'v>) -> bool {
- let width = image_data
- .get("args")
- .and_then(as_array)
- .and_then(|a| a.get(1))
- .and_then(as_u32);
- let height = image_data
- .get("args")
- .and_then(as_array)
- .and_then(|a| a.get(2))
- .and_then(as_u32);
- if let (Some(w), Some(h)) = (width, height) {
- if w > 0 && h > 0 && pixelate_image_data_arg(ctx, image_data, w, h) {
- return true;
- }
- }
- // Unexpected shape — guarantee no raw-pixel leak by blanking every nested ArrayBuffer.
- let mut v: Value<'v> = Value::Object(Box::new(std::mem::take(image_data)));
- let changed = blank_array_buffers(&mut v);
- if let Value::Object(o) = v {
- *image_data = *o;
- }
- changed
-}
-
-/// Locate the RGBA ArrayBuffer behind an ImageData's pixel descriptor (direct or typed-array-wrapped),
-/// blank it and merge the pixelated region back. Returns whether it handled the pixels.
-fn pixelate_image_data_arg(ctx: &Ctx<'_>, image_data: &mut Object<'_>, w: u32, h: u32) -> bool {
- // `checked_mul`: `w*h*4` on attacker-controlled dims can overflow usize; overflow -> no match.
- let Some(expected) = (w as usize)
- .checked_mul(h as usize)
- .and_then(|wh| wh.checked_mul(4))
- else {
- return false;
- };
-
- // Shape A: args[0] is the ArrayBuffer directly.
- let direct = image_data
- .get("args")
- .and_then(as_array)
- .and_then(|a| a.first())
- .and_then(as_object)
- .map(|o| {
- o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
- && o.get("base64").and_then(as_str).is_some()
- })
- .unwrap_or(false);
- if direct {
- if let Some(ab) = image_data
- .get_mut("args")
- .and_then(as_array_mut)
- .and_then(|a| a.first_mut())
- .and_then(as_object_mut)
- {
- return process_raw_buffer(ctx, ab, 0, None, w, h, expected);
- }
- }
-
- // Shape B: typed-array wrapper { args: [ {ArrayBuffer}, byteOffset?, length? ] }.
- let (start, length_opt, wrapped) = {
- let inner = image_data
- .get("args")
- .and_then(as_array)
- .and_then(|a| a.first())
- .and_then(as_object)
- .and_then(|o| o.get("args"))
- .and_then(as_array);
- match inner {
- Some(args) => {
- let is_ab = args
- .first()
- .and_then(as_object)
- .map(|o| {
- o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
- && o.get("base64").and_then(as_str).is_some()
- })
- .unwrap_or(false);
- (
- args.get(1).and_then(as_usize).unwrap_or(0),
- args.get(2).and_then(as_usize),
- is_ab,
- )
- }
- None => (0, None, false),
- }
- };
- if wrapped {
- if let Some(ab) = image_data
- .get_mut("args")
- .and_then(as_array_mut)
- .and_then(|a| a.first_mut())
- .and_then(as_object_mut)
- .and_then(|o| o.get_mut("args"))
- .and_then(as_array_mut)
- .and_then(|a| a.first_mut())
- .and_then(as_object_mut)
- {
- return process_raw_buffer(ctx, ab, start, length_opt, w, h, expected);
- }
- }
- false
-}
-
-fn process_raw_buffer(
- ctx: &Ctx<'_>,
- ab: &mut Object<'_>,
- start: usize,
- length_opt: Option<usize>,
- w: u32,
- h: u32,
- expected: usize,
-) -> bool {
- let Some(base64) = ab.get("base64").and_then(as_str).map(str::to_string) else {
- return false;
- };
- let Ok(full) = b64().decode(base64.as_bytes()) else {
- return false;
- };
- let length = length_opt.unwrap_or_else(|| full.len().saturating_sub(start));
- // `start`/`length` come from untrusted JSON numbers; guard against overflow (release builds don't
- // check arithmetic) so a crafted pair can't produce a reversed/out-of-range slice panic.
- let Some(end) = start.checked_add(length) else {
- return false;
- };
- if length != expected || end > full.len() {
- return false;
- }
- let rgba = b64().encode(&full[start..end]);
- let mut merged = full.clone();
- for b in &mut merged[start..end] {
- *b = 0;
- }
- if let Some(pix) = ctx.pixelate_raw(&rgba, w, h) {
- if let Ok(outbuf) = b64().decode(pix.as_bytes()) {
- if outbuf.len() == length {
- merged[start..end].copy_from_slice(&outbuf);
- }
- }
- }
- ab.insert(key("base64"), string_value(b64().encode(&merged)));
- true
-}
-
-/// Zero out every nested `{rr_type:'ArrayBuffer', base64}` (same byte length). Last-resort fail-safe.
-fn blank_array_buffers(node: &mut Value<'_>) -> bool {
- match node {
- Value::Array(arr) => {
- let mut changed = false;
- for item in arr.iter_mut() {
- changed |= blank_array_buffers(item);
- }
- changed
- }
- Value::Object(obj) => {
- if obj.get("rr_type").and_then(as_str) == Some("ArrayBuffer") {
- if let Some(base64) = obj.get("base64").and_then(as_str) {
- let len = b64()
- .decode(base64.as_bytes())
- .map(|b| b.len())
- .unwrap_or(0);
- let zeros = b64().encode(vec![0u8; len]);
- obj.insert(key("base64"), string_value(zeros));
- return true;
- }
- }
- let mut changed = false;
- for (_, val) in obj.iter_mut() {
- changed |= blank_array_buffers(val);
- }
- changed
- }
- _ => false,
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
use crate::allow_lists::AllowLists;
+ use crate::collect::ImageCollection;
use crate::context::Ctx;
- use crate::testkit::{png_base64, png_data_uri, rgba_base64};
- use base64::Engine;
+ use crate::testkit::png_base64;
+ use serde_json::json;
use simd_json::prelude::Writable;
- // Scrub a CanvasMutation `data` JSON string and return the result as a serde_json Value.
- fn scrub(data_json: &str) -> serde_json::Value {
- let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
- let ctx = Ctx::new(&allow);
- let mut bytes = data_json.as_bytes().to_vec();
- let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
- scrub_canvas_mutation(&ctx, &mut data);
- serde_json::from_str(&data.encode()).unwrap()
+ fn frame(mime: &str, base64: &str) -> serde_json::Value {
+ json!({ "source": 9, "id": 1, "type": 0,
+ "commands": [
+ { "property": "clearRect", "args": [0, 0, 8, 8] },
+ { "property": "drawImage", "args": [
+ { "rr_type": "ImageBitmap", "args": [
+ { "rr_type": "Blob", "type": mime,
+ "data": [{ "rr_type": "ArrayBuffer", "base64": base64 }] }] },
+ 0, 0, 8, 8] }],
+ "displayWidth": 8, "displayHeight": 8 })
}
- fn decode(b64: &str) -> Vec<u8> {
- b64_engine().decode(b64).unwrap()
+ fn scrub_with(ctx: &Ctx<'_>, data: &serde_json::Value) -> (bool, serde_json::Value) {
+ let mut bytes = data.to_string().into_bytes();
+ let mut value = simd_json::to_borrowed_value(&mut bytes).unwrap();
+ let changed = scrub_canvas_mutation(ctx, &mut value);
+ (changed, serde_json::from_str(&value.encode()).unwrap())
}
- fn b64_engine() -> base64::engine::general_purpose::GeneralPurpose {
- base64::engine::general_purpose::STANDARD
+
+ fn blob(out: &serde_json::Value) -> &serde_json::Value {
+ &out["commands"][1]["args"][0]["args"][0]
}
#[test]
- fn image_element_data_uri_src_is_neutralized() {
- let uri = png_data_uri(8, 8, [200, 10, 10, 255]);
- let out = scrub(&format!(
- r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"HTMLImageElement","src":"{uri}"}}]}}]}}"#
- ));
- let src = out["commands"][0]["args"][0]["src"].as_str().unwrap();
- assert!(src.starts_with("data:image/"), "still an image: {src}");
- assert_ne!(src, uri, "raw image must not pass through");
+ fn snapshot_frame_image_never_passes_through() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let b64 = png_base64(8, 8, [10, 200, 10, 255]);
+ let sized = frame("image/png", &b64);
+ let mut unsized_frame = sized.clone();
+ unsized_frame["commands"][1]["args"]
+ .as_array_mut()
+ .unwrap()
+ .truncate(3);
+ for data in [sized, unsized_frame] {
+ let ctx = Ctx::new(&allow);
+ let (changed, out) = scrub_with(&ctx, &data);
+ assert!(changed);
+ assert_ne!(blob(&out)["data"][0]["base64"], b64.as_str());
+ assert_eq!(out["commands"][0]["property"], "clearRect");
+ let rejected = ctx
+ .take_scrub_drops()
+ .into_iter()
+ .any(|(reason, _)| reason == REJECTED_CANVAS_MUTATION);
+ assert!(!rejected, "a frame is kept: {data}");
+ }
}
#[test]
- fn blob_mime_is_allowlisted_on_the_collection_lane() {
- // The blur path re-encodes and overwrites the client-controlled `type`; the ref path has
- // no bytes to re-encode, so it must normalize the mime instead of echoing client text.
- use crate::collect::ImageCollection;
+ fn snapshot_frame_image_becomes_a_ref_on_the_collection_lane() {
let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
let ctx = Ctx::with_image_collection(
&allow,
Some(ImageCollection::new("0".repeat(32), "k".repeat(32))),
);
- let b64 = png_base64(8, 8, [10, 200, 10, 255]);
- let scrub_with = |mime: &str| -> serde_json::Value {
- let data_json = format!(
- r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"Blob","type":"{mime}","data":[{{"rr_type":"ArrayBuffer","base64":"{b64}"}}]}}]}}]}}"#
- );
- let mut bytes = data_json.as_bytes().to_vec();
- let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
- scrub_canvas_mutation(&ctx, &mut data);
- serde_json::from_str(&data.encode()).unwrap()
- };
- let arg = |v: &serde_json::Value| v["commands"][0]["args"][0].clone();
-
- let kept = arg(&scrub_with("image/webp"));
- assert_eq!(kept["type"], "image/webp", "known raster subtype survives");
- assert!(kept["data"][0]["base64"]
+ let (_, out) = scrub_with(
+ &ctx,
+ &frame("image/webp", &png_base64(8, 8, [10, 200, 10, 255])),
+ );
+ assert_eq!(blob(&out)["type"], "image/webp");
+ assert!(blob(&out)["data"][0]["base64"]
.as_str()
.unwrap()
.starts_with("image:"));
-
- let scrubbed = arg(&scrub_with("image/x-evil-client-text"));
- assert_eq!(
- scrubbed["type"], "image/png",
- "unknown subtype must not echo"
- );
+ assert!(ctx.take_scrub_drops().is_empty());
}
#[test]
- fn blob_image_bytes_are_neutralized() {
- let b64 = png_base64(8, 8, [10, 200, 10, 255]);
- let out = scrub(&format!(
- r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"Blob","type":"image/png","data":[{{"rr_type":"ArrayBuffer","base64":"{b64}"}}]}}]}}]}}"#
- ));
- let new_b64 = out["commands"][0]["args"][0]["data"][0]["base64"]
- .as_str()
- .unwrap();
- assert_ne!(new_b64, b64, "raw blob bytes must not pass through");
+ fn snapshot_frame_keeps_only_its_known_keys() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let mut data = frame("image/png", &png_base64(8, 8, [1, 2, 3, 255]));
+ data["secret"] = json!("x");
+ data["commands"][0]["secret"] = json!("x");
+ data["commands"][1]["args"][0]["secret"] = json!("x");
+ data["commands"][1]["args"][0]["args"][0]["secret"] = json!("x");
+ data["commands"][1]["args"][0]["args"][0]["data"][0]["secret"] = json!("x");
+ let (_, out) = scrub_with(&Ctx::new(&allow), &data);
+ assert!(!out.to_string().contains("secret"), "{out}");
}
#[test]
- fn image_data_raw_pixels_are_pixelated_preserving_length() {
- let (w, h) = (8u32, 8u32);
- let rgba = rgba_base64(w, h);
- let out = scrub(&format!(
- r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"putImageData","args":[{{"rr_type":"ImageData","args":[{{"rr_type":"ArrayBuffer","base64":"{rgba}"}},{w},{h}]}}]}}]}}"#
- ));
- let new_b64 = out["commands"][0]["args"][0]["args"][0]["base64"]
- .as_str()
- .unwrap();
- assert_ne!(new_b64, rgba, "raw pixels must not pass through");
- assert_eq!(
- decode(new_b64).len(),
- (w * h * 4) as usize,
- "byte length preserved"
- );
+ fn anything_but_a_snapshot_frame_keeps_only_its_identity() {
+ let png = png_base64(8, 8, [10, 200, 10, 255]);
+ let mut extra_command = frame("image/png", &png);
+ extra_command["commands"]
+ .as_array_mut()
+ .unwrap()
+ .push(json!({ "property": "fillText", "args": ["secret", 1, 2] }));
+ let mut webgl = frame("image/png", &png);
+ webgl["type"] = json!(1);
+ let cases = [
+ (
+ "text",
+ json!({ "source": 9, "id": 1, "type": 0,
+ "commands": [{ "property": "fillText", "args": ["Hello secret", 10, 20] }] }),
+ ),
+ (
+ "flattened command",
+ json!({ "source": 9, "id": 1, "type": 0,
+ "property": "strokeText", "args": ["Hi secret", 1, 2] }),
+ ),
+ (
+ "raw pixels",
+ json!({ "source": 9, "id": 1, "type": 0,
+ "commands": [{ "property": "putImageData", "args": [{ "rr_type": "ImageData",
+ "args": [{ "rr_type": "ArrayBuffer", "base64": "AAAA" }, 1, 1] }, 0, 0] }] }),
+ ),
+ (
+ "image element",
+ json!({ "source": 9, "id": 1, "type": 0,
+ "commands": [{ "property": "drawImage", "args": [
+ { "rr_type": "HTMLImageElement", "src": format!("data:image/png;base64,{png}") }] }] }),
+ ),
+ (
+ "unwrapped blob",
+ json!({ "source": 9, "id": 1, "type": 0,
+ "commands": [{ "property": "drawImage", "args": [{ "rr_type": "Blob", "type": "image/png",
+ "data": [{ "rr_type": "ArrayBuffer", "base64": png }] }] }] }),
+ ),
+ ("svg frame", frame("image/svg+xml", &png)),
+ ("extra command", extra_command),
+ ("webgl context", webgl),
+ ];
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ for (name, data) in cases {
+ let ctx = Ctx::new(&allow);
+ let (changed, out) = scrub_with(&ctx, &data);
+ let context = if name == "webgl context" {
+ json!(1)
+ } else {
+ json!(0)
+ };
+ assert!(changed, "{name}");
+ assert_eq!(
+ out,
+ json!({ "source": 9, "id": 1, "type": context, "commands": [] }),
+ "{name}"
+ );
+ assert_eq!(
+ ctx.take_scrub_drops(),
+ vec![(REJECTED_CANVAS_MUTATION, 1)],
+ "{name}"
+ );
+ }
}
#[test]
- fn malformed_image_data_blanks_the_array_buffer() {
- // 4x4 buffer (64 bytes) but claims 8x8 (256 expected) → the raw-pixel path bails and the
- // fail-safe zeroes every nested ArrayBuffer rather than shipping the pixels.
- let rgba = rgba_base64(4, 4);
- let out = scrub(&format!(
- r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"putImageData","args":[{{"rr_type":"ImageData","args":[{{"rr_type":"ArrayBuffer","base64":"{rgba}"}},8,8]}}]}}]}}"#
- ));
- let new_b64 = out["commands"][0]["args"][0]["args"][0]["base64"]
- .as_str()
- .unwrap();
- let bytes = decode(new_b64);
- assert_eq!(bytes.len(), decode(&rgba).len(), "byte length preserved");
+ fn an_emptied_mutation_is_left_alone() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let empty = json!({ "source": 9, "id": 1, "type": 0, "commands": [] });
+ let ctx = Ctx::new(&allow);
+ let (changed, out) = scrub_with(&ctx, &empty);
+ assert!(!changed);
+ assert_eq!(out, empty);
assert!(
- bytes.iter().all(|&b| b == 0),
- "unhandled shape must be blanked"
+ ctx.take_scrub_drops().is_empty(),
+ "nothing was dropped this time"
);
}
}
diff --git a/rust/replay-anonymizer/src/collect.rs b/rust/replay-anonymizer/src/collect.rs
index 56cde33584b5..4660f325b500 100644
--- a/rust/replay-anonymizer/src/collect.rs
+++ b/rust/replay-anonymizer/src/collect.rs
@@ -186,6 +186,20 @@ impl ImageCollector {
self.max_image_bytes
}
+ pub(crate) fn len(&self) -> usize {
+ self.images.len()
+ }
+
+ pub(crate) fn truncate(&mut self, len: usize) -> HashSet<String> {
+ let mut removed = HashSet::new();
+ for image in self.images.drain(len.min(self.images.len())..) {
+ self.total_bytes -= image.bytes.len();
+ self.seen.remove(&image.hash);
+ removed.insert(image_ref(&self.team_id, &image.hash));
+ }
+ removed
+ }
+
/// Collect decoded image bytes and return their ref, or `None` when a cap says this image must
/// stay on the inline blur path.
pub fn collect(&mut self, bytes: Vec<u8>) -> Option<String> {
diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rs
index db3197130d28..481ad3211e4b 100644
--- a/rust/replay-anonymizer/src/context.rs
+++ b/rust/replay-anonymizer/src/context.rs
@@ -13,7 +13,7 @@ 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::blur::{blank_image_data_uri, blur_image_data_uri};
use crate::collect::{
collectable_data_uri_bytes, is_image_ref, CollectedImage, ImageCollection, ImageCollector,
MAX_IMAGE_BYTES,
@@ -33,6 +33,13 @@ pub(crate) enum ImageSource {
HtmlAttribute(&'static str),
}
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct CountCheckpoint {
+ image_sources: usize,
+ scrub_drops: usize,
+ images: usize,
+}
+
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ImageSourceCount {
pub source: &'static str,
@@ -46,7 +53,7 @@ pub struct ImageSourceCount {
pub struct Ctx<'a> {
pub allow: &'a AllowLists,
pub cv_budget: Cell<usize>,
- // key: the original data URI (data-image blur), or `raw:{w}x{h}:{base64}` (raw RGBA pixelate).
+ // key: the original data URI.
// value: the replacement — a content ref (collection lane), a blurred data URI — or `None`
// when neither could be produced (caller falls back to a blank pixel).
blur_cache: RefCell<HashMap<String, Option<String>>>,
@@ -57,7 +64,9 @@ 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>>,
+ // Logs, not tallies, so a walk whose output is thrown away can take its entries back with it.
+ image_source_log: RefCell<Vec<(ImageSource, &'static str)>>,
+ scrub_drop_log: RefCell<Vec<&'static str>>,
// 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,
@@ -96,7 +105,8 @@ 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()),
+ image_source_log: RefCell::new(Vec::new()),
+ scrub_drop_log: RefCell::new(Vec::new()),
preserve_image_refs: false,
}
}
@@ -218,13 +228,65 @@ impl<'a> Ctx<'a> {
}
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);
+ self.image_source_log.borrow_mut().push((source, kind));
+ }
+
+ pub(crate) fn record_scrub_drop(&self, reason: &'static str) {
+ self.scrub_drop_log.borrow_mut().push(reason);
+ }
+
+ /// A point to roll the counts back to when a walk's output is discarded and the same content is
+ /// walked again, so each occurrence is counted once.
+ pub(crate) fn count_checkpoint(&self) -> CountCheckpoint {
+ CountCheckpoint {
+ image_sources: self.image_source_log.borrow().len(),
+ scrub_drops: self.scrub_drop_log.borrow().len(),
+ images: self
+ .collector
+ .as_ref()
+ .map_or(0, |collector| collector.borrow().len()),
+ }
+ }
+
+ pub(crate) fn restore_counts(&self, checkpoint: CountCheckpoint) {
+ self.image_source_log
+ .borrow_mut()
+ .truncate(checkpoint.image_sources);
+ self.scrub_drop_log
+ .borrow_mut()
+ .truncate(checkpoint.scrub_drops);
+ }
+
+ /// Unlike a re-walk, which collects the same bytes again under the same ref, a discarded walk
+ /// leaves no ref in the output, so its images go too.
+ pub(crate) fn discard_walk(&self, checkpoint: CountCheckpoint) {
+ self.restore_counts(checkpoint);
+ let Some(collector) = self.collector.as_ref() else {
+ return;
+ };
+ let removed = collector.borrow_mut().truncate(checkpoint.images);
+ if !removed.is_empty() {
+ self.blur_cache
+ .borrow_mut()
+ .retain(|_, hit| !hit.as_ref().is_some_and(|r| removed.contains(r)));
+ }
+ }
+
+ pub fn take_scrub_drops(&self) -> Vec<(&'static str, u32)> {
+ let mut counts: BTreeMap<&'static str, u32> = BTreeMap::new();
+ for reason in std::mem::take(&mut *self.scrub_drop_log.borrow_mut()) {
+ let count = counts.entry(reason).or_default();
+ *count = count.saturating_add(1);
+ }
+ counts.into_iter().collect()
}
pub fn take_image_source_counts(&self) -> Vec<ImageSourceCount> {
- let counts = std::mem::take(&mut *self.image_source_counts.borrow_mut());
+ let mut counts: BTreeMap<(ImageSource, &'static str), u32> = BTreeMap::new();
+ for entry in std::mem::take(&mut *self.image_source_log.borrow_mut()) {
+ let count = counts.entry(entry).or_default();
+ *count = count.saturating_add(1);
+ }
counts
.into_iter()
.map(|((source, kind), count)| {
@@ -329,17 +391,6 @@ impl<'a> Ctx<'a> {
collector.borrow().max_image_bytes()
})
}
-
- /// Pixelate raw RGBA pixels, memoized on dimensions + bytes.
- pub fn pixelate_raw(&self, rgba_base64: &str, width: u32, height: u32) -> Option<String> {
- let key = format!("raw:{width}x{height}:{rgba_base64}");
- if let Some(hit) = self.blur_cache.borrow().get(&key) {
- return hit.clone();
- }
- let result = self.timed("blur", || pixelate_raw_rgba(rgba_base64, width, height));
- self.blur_cache.borrow_mut().insert(key, result.clone());
- result
- }
}
#[cfg(test)]
diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rs
index d4d0d2fcb609..35ee92a325e6 100644
--- a/rust/replay-anonymizer/src/lib.rs
+++ b/rust/replay-anonymizer/src/lib.rs
@@ -112,14 +112,4 @@ pub(crate) mod testkit {
pub fn png_data_uri(w: u32, h: u32, color: [u8; 4]) -> String {
format!("data:image/png;base64,{}", png_base64(w, h, color))
}
-
- /// Base64 of `w*h` non-uniform RGBA pixels — e.g. for a canvas `ImageData` ArrayBuffer.
- pub fn rgba_base64(w: u32, h: u32) -> String {
- let mut raw = Vec::with_capacity((w * h * 4) as usize);
- for i in 0..(w * h) {
- let b = (i % 256) as u8;
- raw.extend_from_slice(&[b, b.wrapping_add(50), b.wrapping_add(100), 255]);
- }
- base64::engine::general_purpose::STANDARD.encode(raw)
- }
}
diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rs
index 6470f65aa541..935a2dbe8707 100644
--- a/rust/replay-anonymizer/src/snapshot.rs
+++ b/rust/replay-anonymizer/src/snapshot.rs
@@ -193,6 +193,15 @@ pub struct SnapshotMeta {
/// with nothing to say why.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub url_declines: Vec<UrlDecline>,
+ /// Content the scrub removed outright rather than replaced, by reason.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub scrub_drops: Vec<ScrubDrop>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct ScrubDrop {
+ pub reason: &'static str,
+ pub count: u32,
}
/// One reason the collector refused a URL, and how many times it did.
@@ -542,11 +551,15 @@ fn anonymize_snapshot_data_inner(
// reject_if_too_deep — so the common all-walked path never pays a depth scan at all.
let mut ctx = Ctx::with_options(allow, timings, opts.image_policy, image_collection)
.collecting_urls(url_collection);
+ let counts = ctx.count_checkpoint();
let mut msg = match stream_message(&ctx, distinct_id, inner, opts)? {
Some(msg) => msg,
// Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was
// consumed before the signal, so the tree path re-reads the intact buffer.
- None => anonymize_via_tree_mut(&ctx, distinct_id, inner)?,
+ None => {
+ ctx.restore_counts(counts);
+ anonymize_via_tree_mut(&ctx, distinct_id, inner)?
+ }
};
msg.meta.url_declines = ctx
.take_url_declines()
@@ -1006,6 +1019,11 @@ fn finish(
urls: Vec::new(),
image_sources: Vec::new(),
url_declines: Vec::new(),
+ scrub_drops: ctx
+ .take_scrub_drops()
+ .into_iter()
+ .map(|(reason, count)| ScrubDrop { reason, count })
+ .collect(),
},
image_bytes: Vec::new(),
})
@@ -1240,6 +1258,7 @@ fn process_event_at(
let mark = sink.lines.len();
sink.lines.extend_from_slice(&inner[span.0..data.0]);
let data_mark = sink.lines.len();
+ let counts = ctx.count_checkpoint();
match crate::bytewalk::scrub_data_bytes(
ctx,
ty,
@@ -1271,7 +1290,10 @@ fn process_event_at(
});
return Ok(end);
}
- None => sink.lines.truncate(mark),
+ None => {
+ sink.lines.truncate(mark);
+ ctx.restore_counts(counts);
+ }
}
}
diff --git a/rust/replay-anonymizer/tests/fixtures/events.json b/rust/replay-anonymizer/tests/fixtures/events.json
index ed88105c2c72..8dfa0cd5e5c7 100644
--- a/rust/replay-anonymizer/tests/fixtures/events.json
+++ b/rust/replay-anonymizer/tests/fixtures/events.json
@@ -185,7 +185,7 @@
}
},
{
- "name": "canvas fillText args are text-scrubbed",
+ "name": "canvas text drawing is emptied, not scrubbed",
"allow": { "text": ["hello"], "url": [] },
"event": {
"type": 3,
@@ -193,7 +193,7 @@
},
"expected": {
"type": 3,
- "data": { "source": 9, "id": 1, "type": 0, "commands": [{ "property": "fillText", "args": ["Hello ******", 10, 20] }] }
+ "data": { "source": 9, "id": 1, "type": 0, "commands": [] }
}
},
{
@@ -383,14 +383,8 @@
}
},
{
- "name": "canvas strokeText in flattened single-command form is scrubbed",
- "allow": { "text": ["hi"], "url": [] },
- "event": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "property": "strokeText", "args": ["Hi secret", 1, 2] } },
- "expected": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "property": "strokeText", "args": ["Hi ******", 1, 2] } }
- },
- {
- "name": "canvas multiple commands (fillText + strokeText) each scrubbed",
- "allow": { "text": ["a", "b"], "url": [] },
+ "name": "canvas snapshot frame keeps its shape and its image never passes through",
+ "allow": { "text": [], "url": [] },
"event": {
"type": 3,
"data": {
@@ -398,8 +392,11 @@
"id": 1,
"type": 0,
"commands": [
- { "property": "fillText", "args": ["A secret"] },
- { "property": "strokeText", "args": ["B secret"] }
+ { "property": "clearRect", "args": [0, 0, 8, 8] },
+ {
+ "property": "drawImage",
+ "args": [{ "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/webp", "data": [{ "rr_type": "ArrayBuffer", "base64": "AAAA" }] }] }, 0, 0]
+ }
]
}
},
@@ -410,12 +407,38 @@
"id": 1,
"type": 0,
"commands": [
- { "property": "fillText", "args": ["A ******"] },
- { "property": "strokeText", "args": ["B ******"] }
+ { "property": "clearRect", "args": [0, 0, 8, 8] },
+ {
+ "property": "drawImage",
+ "args": [{ "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png", "data": [{ "rr_type": "ArrayBuffer", "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" }] }] }, 0, 0]
+ }
]
}
}
},
+ {
+ "name": "canvas command in flattened single-command form is emptied",
+ "allow": { "text": ["hi"], "url": [] },
+ "event": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "property": "strokeText", "args": ["Hi secret", 1, 2] } },
+ "expected": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "commands": [] } }
+ },
+ {
+ "name": "canvas drawing commands other than a snapshot frame are emptied",
+ "allow": { "text": ["a", "b"], "url": [] },
+ "event": {
+ "type": 3,
+ "data": {
+ "source": 9,
+ "id": 1,
+ "type": 0,
+ "commands": [
+ { "property": "fillText", "args": ["A secret"] },
+ { "property": "strokeText", "args": ["B secret"] }
+ ]
+ }
+ },
+ "expected": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "commands": [] } }
+ },
{
"name": "console plugin scrubs text payload frames and url trace frames",
"allow": { "text": ["oops"], "url": ["a"] },
diff --git a/rust/replay-anonymizer/tests/image_token_fuzz.rs b/rust/replay-anonymizer/tests/image_token_fuzz.rs
index 71f537ff6842..3896ce793bc9 100644
--- a/rust/replay-anonymizer/tests/image_token_fuzz.rs
+++ b/rust/replay-anonymizer/tests/image_token_fuzz.rs
@@ -167,12 +167,15 @@ fn make_event(rng: &mut Rng, small: &[String], large: &[String], ts: f64) -> Val
3 => json!({ "type": 2, "timestamp": ts, "data": { "node": { "type": 0, "id": 1,
"childNodes": adds.iter().map(|a| a["node"].clone()).collect::<Vec<_>>() },
"initialOffset": { "top": 0, "left": 0 } } }),
- // Canvas blob: the other `scrub_image` caller, with the Blank fallback.
+ // Canvas snapshot frame: the other `scrub_image` caller, with the Blank fallback.
_ => json!({ "type": 3, "timestamp": ts, "data": { "source": 9, "id": 5, "type": 0,
- "commands": [{ "property": "drawImage", "args": [{
- "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png",
- "data": [{ "rr_type": "ArrayBuffer", "base64":
- image_uri(rng, small, large).split(',').nth(1).unwrap_or("").to_string() }] }] }] }] } }),
+ "commands": [
+ { "property": "clearRect", "args": [0, 0, 8, 8] },
+ { "property": "drawImage", "args": [{
+ "rr_type": "ImageBitmap", "args": [{ "rr_type": "Blob", "type": "image/png",
+ "data": [{ "rr_type": "ArrayBuffer", "base64":
+ image_uri(rng, small, large).split(',').nth(1).unwrap_or("").to_string() }] }] },
+ 0, 0, 8, 8] }] } }),
}
}
diff --git a/rust/replay-anonymizer/tests/ref_idempotence.rs b/rust/replay-anonymizer/tests/ref_idempotence.rs
index 65ecb52ac6e1..36190e219b20 100644
--- a/rust/replay-anonymizer/tests/ref_idempotence.rs
+++ b/rust/replay-anonymizer/tests/ref_idempotence.rs
@@ -32,11 +32,12 @@ fn img_line(value: &str, attr: &str) -> Value {
fn canvas_line(value: &str) -> Value {
json!(["w", { "type": 3, "timestamp": TS0, "data": {
- "source": 9, "id": 5, "type": 0, "commands": [{
- "property": "drawImage",
- "args": [{ "rr_type": "ImageBitmap", "args": [{
+ "source": 9, "id": 5, "type": 0, "commands": [
+ { "property": "clearRect", "args": [0, 0, 8, 8] },
+ { "property": "drawImage",
+ "args": [{ "rr_type": "ImageBitmap", "args": [{
"rr_type": "Blob", "type": "image/png",
- "data": [{ "rr_type": "ArrayBuffer", "base64": value }] }] }] }] } }])
+ "data": [{ "rr_type": "ArrayBuffer", "base64": value }] }] }, 0, 0, 8, 8] }] } }])
}
fn css_line(reference: &str) -> Value {
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 295566523205..2fe14048ab5d 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -853,17 +853,90 @@ fn collect_payload() -> String {
"initialOffset": {"top": 0, "left": 0}
}
},
- // Canvas blob carrying the same bytes under a bare base64 payload.
+ // A posthog-js canvas snapshot frame carrying the same bytes under a bare base64 payload.
{
"type": 3,
"timestamp": TS0 + 1.0,
- "data": {"source": 9, "id": 1, "type": 0, "commands": [{"property": "drawImage", "args": [
- {"rr_type": "Blob", "type": "image/png", "data": [{"rr_type": "ArrayBuffer", "base64": COLLECT_PNG_B64}]}
- ]}]}
+ "data": {"source": 9, "id": 1, "type": 0, "commands": [
+ {"property": "clearRect", "args": [0, 0, 8, 8]},
+ {"property": "drawImage", "args": [
+ {"rr_type": "ImageBitmap", "args": [
+ {"rr_type": "Blob", "type": "image/png", "data": [{"rr_type": "ArrayBuffer", "base64": COLLECT_PNG_B64}]}
+ ]},
+ 0, 0, 8, 8
+ ]}
+ ]}
},
])))
}
+#[test]
+fn both_engines_count_and_collect_an_image_once_or_not_at_all() {
+ // The byte walk walks children before it knows their parent, then re-walks or discards them.
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let uri = format!("data:image/png;base64,{COLLECT_PNG_B64}");
+ let img = json!({"type": 2, "tagName": "img", "attributes": {"src": uri}, "childNodes": []});
+ let cases = [
+ (
+ "picture",
+ json!({"type": 2, "tagName": "picture", "attributes": {}, "childNodes": [img.clone()]}),
+ vec![("src", 1)],
+ 1,
+ ),
+ (
+ "document type",
+ json!({"type": 1, "name": "html", "childNodes": [img.clone()]}),
+ vec![],
+ 0,
+ ),
+ (
+ "unknown node",
+ json!({"type": 99, "childNodes": [img]}),
+ vec![],
+ 0,
+ ),
+ ];
+ for (label, node, expected_counts, expected_images) in cases {
+ let inner = snapshot_message(json!([{
+ "type": 2,
+ "timestamp": TS0,
+ "data": {
+ "node": {"type": 0, "childNodes": [node]},
+ "initialOffset": {"top": 0, "left": 0}
+ }
+ }]));
+ for byte_walk in [true, false] {
+ let mut bytes = payload_of(&inner).into_bytes();
+ let out = anonymize_kafka_payload_opts(
+ &allow,
+ &mut bytes,
+ AnonymizeOpts {
+ byte_walk,
+ ..Default::default()
+ },
+ Some(ImageCollection::new(
+ "42".to_string(),
+ "fedcba9876543210fedcba9876543210".to_string(),
+ )),
+ )
+ .expect("anonymizes");
+ let counts: Vec<_> = out
+ .meta
+ .image_sources
+ .iter()
+ .map(|c| (c.property, c.count))
+ .collect();
+ assert_eq!(counts, expected_counts, "{label}, walk={byte_walk}");
+ assert_eq!(
+ out.meta.images.len(),
+ expected_images,
+ "{label}, walk={byte_walk}"
+ );
+ assert!(out.meta.scrub_drops.is_empty(), "{label}, walk={byte_walk}");
+ }
+ }
+}
+
#[test]
fn image_collection_replaces_images_with_refs_and_returns_the_bytes() {
use base64::Engine;