:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(session-replay): make the replay anonymizer crate a first-class library for offline consumers (#71954)
Robbie531f5f40ce50
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex 247bc30588ff..347744b24427 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -63,6 +63,7 @@ jobs:# its Rust tests; a rust-side change (incl. the shared fixtures) must run it.- 'rust/replay-anonymizer/**'- 'rust/replay-anonymizer-node/**'+ - '**/crosslang/**'- 'posthog/clickhouse/**'- 'ee/migrations/**'- 'posthog/management/commands/setup_test_environment.py'diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.test.tsnew file mode 100644index 000000000000..5b952a4979b5--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.test.ts@@ -0,0 +1,25 @@+import { readFileSync } from 'fs'+import path from 'path'++import { DEFAULT_TEXT_WORDS, DEFAULT_URL_SEGMENTS } from './default-dict'++// The single source of truth for the default allow lists is the `.txt` pair under+// `crosslang/` in the posthog-replay-anonymizer Rust crate (embedded there via include_str!). This+// test reads those data files and asserts the TS copy matches, so the ingestion (TS) and offline+// (Rust) pipelines can never drift to different default vocabularies. It reads the data files — it+// does not parse Rust source — so a rename/reformat on either side that changes no values leaves it+// green. See the crate's `crosslang/README.md` for the folder convention.+const RUST_CROSSLANG = path.resolve(__dirname, '../../../../../../rust/replay-anonymizer/src/crosslang')++function readEmbeddedList(file: string): string[] {+ return readFileSync(path.join(RUST_CROSSLANG, file), 'utf8')+ .split('\n')+ .filter((line) => line.length > 0)+}++describe('anonymize/default-dict', () => {+ it('stays in sync with the Rust crate default lists', () => {+ expect(new Set(DEFAULT_TEXT_WORDS)).toEqual(new Set(readEmbeddedList('default_text_words.txt')))+ expect(new Set(DEFAULT_URL_SEGMENTS)).toEqual(new Set(readEmbeddedList('default_url_segments.txt')))+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.tsindex 88fde245e72e..74260525f4da 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts@@ -1,4 +1,11 @@-/** Default allow lists (English stopwords/UI vocabulary + safe URL segments), the fail-safe fallback. */+/**+ * Default allow lists (English stopwords/UI vocabulary + safe URL segments), the fail-safe fallback.+ *+ * The arrays below mirror the single source of truth — `default_text_words.txt` /+ * `default_url_segments.txt` in the `posthog-replay-anonymizer` Rust crate, which the crate embeds+ * for offline consumers. `default-dict.test.ts` reads those files and asserts this copy matches, so+ * editing the defaults means editing the `.txt` files and this list together.+ */import { AllowLists } from './allow-lists'export const DEFAULT_TEXT_WORDS: string[] = [diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 09c50ad4a9a8..da48dc00bcf9 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8020,7 +8020,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.1.0"+version = "0.2.0"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/Cargo.toml b/rust/replay-anonymizer-node/Cargo.tomlindex 6ce1165dc238..1ab16166ee66 100644--- a/rust/replay-anonymizer-node/Cargo.toml+++ b/rust/replay-anonymizer-node/Cargo.toml@@ -13,6 +13,7 @@ crate-type = ["cdylib"]# Safe here: the addon only runs in PostHog's Node ingestion workers, never in V8# sandboxed-pointer environments (Electron), where external buffers abort the VM.neon = { workspace = true, features = ["external-buffers"] }-posthog-replay-anonymizer = { path = "../replay-anonymizer" }+# default-features = false: the offline typed-parse module has no place in the ingestion cdylib.+posthog-replay-anonymizer = { path = "../replay-anonymizer", default-features = false }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex 75bc154de219..749f1d688f64 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.1.0"+version = "0.2.0"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"@@ -10,6 +10,12 @@ repository = "https://github.com/PostHog/posthog"[lints]workspace = true+[features]+default = ["typed-parse"]+# Typed rrweb parse output (the `typed` module) for offline consumers. The Node addon builds with+# `default-features = false` so the AST types stay out of the ingestion cdylib entirely.+typed-parse = []+[dependencies]ahash = { workspace = true }anyhow = { workspace = true }diff --git a/rust/replay-anonymizer/README.md b/rust/replay-anonymizer/README.mdindex 5157ca7fb11c..8a1ef31fb0d5 100644--- a/rust/replay-anonymizer/README.md+++ b/rust/replay-anonymizer/README.md@@ -7,7 +7,9 @@ Consumers:- `replay-anonymizer-node` (this workspace) wraps it as a Neon addon for the Node ingestion workers.- The MLHog training pipelines consume it from crates.io.-Behavior is pinned by the JSON fixtures under `tests/fixtures/`, shared with the Node addon's Jest suite. Scrubbing operates on untrusted input and may panic on pathological payloads; callers that must fail closed should wrap calls in `catch_unwind` under `panic = "unwind"`.+Behavior is pinned by the JSON fixtures under `tests/fixtures/`, shared with the Node addon's Jest suite. Scrubbing operates on untrusted input; the public entry points contain panics and convert them to errors, so callers fail closed (drop the message) without their own `catch_unwind`. Under `panic = "abort"` that backstop cannot run — builds that must fail closed need `panic = "unwind"`.++Offline consumers (JSONL of individual events rather than Kafka messages) get a dedicated surface: `anonymize_line` scrubs one line (bare event or `["window_id", event]` tuple), `AllowLists::from_json_bytes` loads the shipped `{ text, url }` document and `AllowLists::default()` embeds the production default lists, and the default `typed-parse` feature adds `parse_scrubbed_event` — scrub-then-parse to a typed rrweb AST (envelope, DOM tree, mutations, interactions) with `cv` payloads transparently decompressed. The Node addon builds with `default-features = false`, so none of the typed surface exists on the ingestion hot path.## Releasingdiff --git a/rust/replay-anonymizer/src/allow_lists.rs b/rust/replay-anonymizer/src/allow_lists.rsindex e71d0800ac8a..3b7b078595a6 100644--- a/rust/replay-anonymizer/src/allow_lists.rs+++ b/rust/replay-anonymizer/src/allow_lists.rs@@ -4,6 +4,24 @@// The lookups run once per word token of every text node; ahash beats SipHash on short strings and// the sets are built from operator-controlled config, so hash-DoS resistance buys nothing here.use ahash::AHashSet;+use anyhow::{Context, Result};+use serde::Deserialize;++/// Bounds on the *retained* allow-list, mirroring the TS loader's hygiene+/// (`anonymize/allow-list-loader.ts`). These cap what is kept, not peak parse memory — the JSON is+/// fully materialized by `serde_json` first. That's acceptable because the document is+/// operator-controlled config loaded once at startup, not per-request untrusted input.+const MAX_ALLOW_LIST_ENTRIES: usize = 500_000;+const MAX_ALLOW_LIST_ENTRY_LEN: usize = 256;++// The fail-safe default lists, embedded so offline consumers with no access to the shipped allow+// lists scrub with production-equivalent vocabulary instead of redacting everything. The `.txt`+// files under `crosslang/` are the single source of truth: the crate embeds them here, and the TS+// pipeline's `anonymize/default-dict.ts` mirrors them (a Jest test reads these files and asserts the+// match, so the two stay in sync without either side parsing the other's source). See+// `crosslang/README.md` for the cross-language folder convention.+const DEFAULT_TEXT_WORDS: &str = include_str!("crosslang/default_text_words.txt");+const DEFAULT_URL_SEGMENTS: &str = include_str!("crosslang/default_url_segments.txt");fn has_upper_ascii(s: &str) -> bool {s.bytes().any(|b| b.is_ascii_uppercase())@@ -22,7 +40,7 @@ fn ascii_lowercase(s: &str) -> String {out}-#[derive(Debug, Default)]+#[derive(Debug)]pub struct AllowLists {text: AHashSet<String>,url: AHashSet<String>,@@ -36,6 +54,39 @@ fn len_bit(s: &str) -> u64 {1u64 << s.len().min(63)}+/// The production default lists (English stopwords/UI vocabulary + safe URL segments) — the same+/// fallback the TS pipeline uses when the shipped lists can't be loaded. Consumers with explicit+/// lists should prefer [`AllowLists::from_json_bytes`]; [`AllowLists::new`] stays available for+/// deliberate empty construction (redact everything).+impl Default for AllowLists {+ fn default() -> Self {+ Self::new(DEFAULT_TEXT_WORDS.lines(), DEFAULT_URL_SEGMENTS.lines())+ }+}++#[derive(Deserialize)]+struct RawAllowLists {+ #[serde(default)]+ text: Option<serde_json::Value>,+ #[serde(default)]+ url: Option<serde_json::Value>,+}++/// The TS loader's sanitize pass: keep only string entries within the length bound, cap the count.+fn sanitize_entries(raw: Option<serde_json::Value>) -> Vec<String> {+ let Some(serde_json::Value::Array(items)) = raw else {+ return Vec::new();+ };+ items+ .into_iter()+ .filter_map(|v| match v {+ serde_json::Value::String(s) if s.len() <= MAX_ALLOW_LIST_ENTRY_LEN => Some(s),+ _ => None,+ })+ .take(MAX_ALLOW_LIST_ENTRIES)+ .collect()+}+impl AllowLists {pub fn new<I, J>(text: I, url: J) -> Selfwhere@@ -62,6 +113,19 @@ impl AllowLists {}}+ /// Parse the `{ "text": [...], "url": [...] }` allow-list document PostHog ships (the shape+ /// the Node addon loads from S3), with the TS loader's sanitize limits: non-string and+ /// over-long entries are dropped, each list is capped at 500k entries. Missing or non-array+ /// fields become empty lists (fail-safe: over-redaction, never under-redaction); only invalid+ /// JSON is an error.+ pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {+ let raw: RawAllowLists = serde_json::from_slice(bytes).context("parse allow-lists json")?;+ Ok(Self::new(+ sanitize_entries(raw.text),+ sanitize_entries(raw.url),+ ))+ }+pub fn text_contains(&self, word: &str) -> bool {if self.text_lens & len_bit(word) == 0 {return false;@@ -84,3 +148,43 @@ impl AllowLists {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn from_json_bytes_sanitizes_like_the_ts_loader() {+ let long = "x".repeat(MAX_ALLOW_LIST_ENTRY_LEN + 1);+ let doc = serde_json::json!({+ "text": ["Hello", 42, null, long, "world"],+ "url": ["Api"],+ });+ let allow = AllowLists::from_json_bytes(&serde_json::to_vec(&doc).unwrap()).unwrap();+ // Kept entries match case-insensitively, exactly like `AllowLists::new`.+ assert!(allow.text_contains("hello") && allow.text_contains("HELLO"));+ assert!(allow.text_contains("world"));+ assert!(allow.url_contains("api") && allow.url_contains("API"));+ // Non-string and over-long entries are dropped, not kept and not fatal.+ assert!(!allow.text_contains(&long));+ assert!(!allow.text_contains("42"));++ // Missing/non-array fields fail safe to empty lists; only invalid JSON errors.+ let empty = AllowLists::from_json_bytes(br#"{"text": "not an array"}"#).unwrap();+ assert!(!empty.text_contains("hello"));+ assert!(AllowLists::from_json_bytes(b"{nope").is_err());+ }++ #[test]+ fn defaults_allow_stopwords_and_still_redact_names() {+ let allow = AllowLists::default();+ // A word from the TS `DEFAULT_TEXT_WORDS` and a segment from `DEFAULT_URL_SEGMENTS`.+ assert!(allow.text_contains("the"));+ assert!(allow.url_contains("api"));+ assert_eq!(+ crate::text::scrub_text(&allow, "John Fakename accepted the request"),+ Some("**** ******** accepted the request".to_string()),+ "names must still redact under the default lists"+ );+ }+}diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rsindex 3a0546be42bc..7ac47df89c44 100644--- a/rust/replay-anonymizer/src/bytewalk.rs+++ b/rust/replay-anonymizer/src/bytewalk.rs@@ -218,15 +218,19 @@ fn scrub_cv_snapshot_value(return None;}let raw = latin1_from_wire(&bytes[data.0 + 1..data.1 - 1])?;- let decompressed = ctx.gunzip_cv(&raw).ok()?;+ let was_zstd = raw.starts_with(&crate::compression::ZSTD_MAGIC);+ let decompressed = ctx.decompress_cv(&raw).ok()?;let mut walked = Vec::with_capacity(decompressed.len() + 64);- // Unchanged payloads re-emit too: the whole output is zstd, never mixed-format blocks.- let content = if scrub_cv_snapshot(ctx, &decompressed, &mut walked)? {- &walked- } else {- &decompressed- };- let zs = crate::gzip::compress_cv(content).ok()?;+ let changed = scrub_cv_snapshot(ctx, &decompressed, &mut walked)?;+ // An unchanged zstd payload keeps its original bytes (safe: the walk proved it duplicate-key+ // free), so re-scrubbing already-anonymized data is a no-op. Unchanged gzip payloads re-emit+ // anyway: the whole output is zstd, never mixed-format blocks.+ if !changed && was_zstd {+ out.extend_from_slice(&bytes[data.0..data.1]);+ return Some(false);+ }+ let content = if changed { &walked } else { &decompressed };+ let zs = crate::compression::compress_cv(content).ok()?;write_latin1_json_string(&zs, out);Some(true)}@@ -959,8 +963,9 @@ impl<'c, 'a> Walker<'c, 'a> {})}- /// One cv-marked mutation sub-field from the wire: a gzipped string is decoded/walked, a plain- /// array walks uncompressed, `null`/empty-string keep verbatim, anything else declines.+ /// One cv-marked mutation sub-field from the wire: a compressed string (gzip or zstd) is+ /// decoded/walked, a plain array walks uncompressed, `null`/empty-string keep verbatim,+ /// anything else declines.fn walk_cv_sub(&mut self,field: CvMutationField,@@ -982,15 +987,18 @@ impl<'c, 'a> Walker<'c, 'a> {return Some(send);}let raw = latin1_from_wire(wire)?;- let decompressed = self.ctx.gunzip_cv(&raw).ok()?;+ let was_zstd = raw.starts_with(&crate::compression::ZSTD_MAGIC);+ let decompressed = self.ctx.decompress_cv(&raw).ok()?;let mut walked = Vec::with_capacity(decompressed.len() + 64);- let content =- if scrub_cv_mutation_field(self.ctx, field, &decompressed, &mut walked)? {- &walked- } else {- &decompressed- };- let zs = crate::gzip::compress_cv(content).ok()?;+ let changed = scrub_cv_mutation_field(self.ctx, field, &decompressed, &mut walked)?;+ // Unchanged zstd sub-fields keep their original bytes (the walk proved them+ // duplicate-key free), so a re-scrub is a no-op; gzip always re-emits as zstd.+ if !changed && was_zstd {+ out.extend_from_slice(&self.bytes[vstart..send]);+ return Some(send);+ }+ let content = if changed { &walked } else { &decompressed };+ let zs = crate::compression::compress_cv(content).ok()?;write_latin1_json_string(&zs, out);self.changed = true;Some(send)diff --git a/rust/replay-anonymizer/src/compression.rs b/rust/replay-anonymizer/src/compression.rsnew file mode 100644index 000000000000..44f8a8eb4afc--- /dev/null+++ b/rust/replay-anonymizer/src/compression.rs@@ -0,0 +1,300 @@+//! Every compression codec the anonymizer touches, in one place: gzip on libdeflate (~2-3x the+//! throughput of the streaming flate2 legs it replaced, at the cost of needing the output size up+//! front — which gzip carries in its ISIZE footer), the zstd pair (`compress_cv` re-emits cv+//! payloads; `unzstd` reads them back), the lz4 block leg for capture-wrapped Kafka values, and the+//! magic-byte dispatch over a cv stream. Note `compress_cv` emits **zstd**, not gzip — the crate+//! never produces gzip in production (that codec is decode-only here; the `gzip` compressor exists+//! for tests simulating the SDK wire format).++use std::cell::RefCell;+use std::io::Read;++use anyhow::{anyhow, bail, Result};+use libdeflater::{CompressionLvl, Compressor, Decompressor};++/// Compression-bomb cap: ~6x the 10.3 MB largest payload in a 1000-message production sample.+/// Exceeding it fails closed as a classified DLQ instead of an unclassifiable OOM crash-loop.+pub const MAX_DECOMPRESSED_BYTES: usize = 64 * 1024 * 1024;++/// Leading magic of a gzip member (RFC 1952).+pub const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];++/// Leading magic of a zstd frame (RFC 8878).+pub const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];++/// zstd level for re-emitted cv payloads. Counterintuitively negative: raw codec ratio is 20%+/// worse than level 1 (0.145 vs 0.121 on the real cv corpus), but these bytes are stored+/// latin-1-in-JSON inside snappy blocks, where entropy-coded output pays twice — high bytes cost+/// 2 UTF-8 bytes each and are incompressible to the block snappy, while the raw ASCII literals+/// negative levels leave behind cost 1 byte and snappy still compresses them. Measured end to+/// end on the corpus, -1 beats 1 on every axis: 3.67 vs 3.88 ms/msg, snappy'd blocks 272.7 vs+/// 289.2 MB, and the loader-side decompress is ~30% faster. Levels below -1 gain nothing.+const CV_ZSTD_LEVEL: i32 = -1;++/// zstd `windowLogMax` cap. The decoder's back-reference window can't exceed our decompressed-size+/// cap (2^26 = 64 MiB), so a frame header declaring a huge `windowLog` can't force an outsized+/// working-buffer allocation before the size cap engages. Real cv payloads sit far below this.+const CV_ZSTD_WINDOW_LOG_MAX: u32 = 26;++thread_local! {+ // Reused per thread: each codec state is a one-time ~50-300 KB malloc and cv work runs several+ // times per event.+ static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());+ static COMPRESSOR: RefCell<Compressor> =+ RefCell::new(Compressor::new(CompressionLvl::default()));+ static ZSTD_COMPRESSOR: RefCell<zstd::bulk::Compressor<'static>> = RefCell::new(+ zstd::bulk::Compressor::new(CV_ZSTD_LEVEL).expect("static zstd level is valid"),+ );+ static ZSTD_DECOMPRESSOR: RefCell<zstd::bulk::Decompressor<'static>> = RefCell::new({+ let mut d = zstd::bulk::Decompressor::new().expect("default zstd decompressor is valid");+ d.set_parameter(zstd::zstd_safe::DParameter::WindowLogMax(CV_ZSTD_WINDOW_LOG_MAX))+ .expect("window log max is a valid decompression parameter");+ d+ });+}++/// Gunzip a single-member stream. The output buffer is sized exactly from the stream's ISIZE+/// footer (uncompressed length mod 2^32, RFC 1952), so both footer lies fail closed: claiming+/// more than [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating, and claiming less than the+/// real size makes libdeflate stop at the buffer end with `InsufficientSpace`.+pub fn gunzip(raw: &[u8]) -> Result<Vec<u8>> {+ let Some(footer) = raw.len().checked_sub(4).map(|start| &raw[start..]) else {+ bail!("gzip stream too short");+ };+ let hint = u32::from_le_bytes(footer.try_into().expect("4-byte slice")) as usize;+ if hint > MAX_DECOMPRESSED_BYTES {+ bail!("gzip uncompressed size exceeds limit");+ }+ let mut out = vec![0u8; hint];+ let n = DECOMPRESSOR+ .with(|d| d.borrow_mut().gzip_decompress(raw, &mut out))+ .map_err(|e| anyhow!("gunzip: {e:?}"))?;+ out.truncate(n);+ Ok(out)+}++/// Gzip `payload` as one default-level (6, matching both flate2's default and the TS pipeline's+/// pako default) member.+pub fn gzip(payload: &[u8]) -> Result<Vec<u8>> {+ COMPRESSOR.with(|c| {+ let mut c = c.borrow_mut();+ let mut out = vec![0u8; c.gzip_compress_bound(payload.len())];+ let n = c+ .gzip_compress(payload, &mut out)+ .map_err(|e| anyhow!("gzip: {e:?}"))?;+ out.truncate(n);+ Ok(out)+ })+}++/// Decompress a single zstd frame. Unlike gzip there is no ISIZE trailer: when the frame header+/// declares its content size the output buffer is sized from it (a declaration past+/// [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating), and a frame without one falls back to+/// a streaming decode capped at the same limit.+///+/// The input must be exactly one frame that consumes every byte. Trailing bytes, concatenated+/// frames, and appended skippable frames all decode to less than the input; accepting them would+/// let never-decompressed bytes ride verbatim into a "kept unchanged" re-emit (the cv scrub keeps+/// an unchanged zstd payload's original bytes). Fail closed on anything but a single self-contained+/// frame — the gzip leg gets this for free (an unchanged gzip payload always re-emits, never keeps+/// its bytes), so only the zstd leg needs the explicit check.+pub fn unzstd(raw: &[u8]) -> Result<Vec<u8>> {+ match zstd::zstd_safe::find_frame_compressed_size(raw) {+ Ok(n) if n == raw.len() => {}+ Ok(_) => bail!("zstd cv payload is not a single self-contained frame"),+ Err(code) => bail!("zstd frame: {}", zstd::zstd_safe::get_error_name(code)),+ }+ match zstd::zstd_safe::get_frame_content_size(raw) {+ Ok(Some(size)) => {+ if size > MAX_DECOMPRESSED_BYTES as u64 {+ bail!("zstd declared content size exceeds limit");+ }+ ZSTD_DECOMPRESSOR+ .with(|d| d.borrow_mut().decompress(raw, size as usize))+ .map_err(|e| anyhow!("unzstd: {e}"))+ }+ Ok(None) => {+ let mut decoder = zstd::stream::read::Decoder::new(raw)?;+ decoder.window_log_max(CV_ZSTD_WINDOW_LOG_MAX)?;+ let mut out = Vec::new();+ decoder+ .take(MAX_DECOMPRESSED_BYTES as u64 + 1)+ .read_to_end(&mut out)+ .map_err(|e| anyhow!("unzstd (streaming): {e}"))?;+ if out.len() > MAX_DECOMPRESSED_BYTES {+ bail!("zstd uncompressed size exceeds limit");+ }+ Ok(out)+ }+ Err(e) => bail!("zstd frame header: {e}"),+ }+}++/// Re-compress a cv payload as zstd. The consumer distinguishes formats by magic bytes alone+/// (`1f 8b` gzip vs `28 b5 2f fd` zstd), so historical gzip blocks stay readable.+pub fn compress_cv(payload: &[u8]) -> Result<Vec<u8>> {+ ZSTD_COMPRESSOR.with(|c| {+ c.borrow_mut()+ .compress(payload)+ .map_err(|e| anyhow!("zstd: {e}"))+ })+}++/// Decompress a compressed stream by its leading magic: gzip (the SDK wire format) or zstd (the+/// anonymizer's own re-emit, so re-scrubbing already-anonymized data works). Unknown magic fails+/// closed. Unbudgeted — cv code must go through `Ctx::decompress_cv`, which layers the cumulative+/// per-message budget on top of this.+pub fn decompress_by_magic(raw: &[u8]) -> Result<Vec<u8>> {+ if raw.starts_with(&GZIP_MAGIC) {+ gunzip(raw)+ } else if raw.starts_with(&ZSTD_MAGIC) {+ unzstd(raw)+ } else {+ bail!("cv stream is neither gzip nor zstd");+ }+}++/// Decompress an lz4 *block* (not frame) with capture's 4-byte LE uncompressed-size prefix. Both+/// prefix lies fail closed: a size over [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating (a+/// forged u32 prefix can claim up to 4 GiB), and a decoded length that disagrees with the prefix is+/// an error rather than a short/long buffer surfacing later as invalid JSON.+pub fn unlz4_block(raw: &[u8]) -> Result<Vec<u8>> {+ let Some(size_bytes) = raw.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()) else {+ bail!("lz4 payload too short for size prefix");+ };+ let size = u32::from_le_bytes(size_bytes) as usize;+ if size > MAX_DECOMPRESSED_BYTES {+ bail!("lz4 uncompressed size exceeds limit");+ }+ let out = lz4::block::decompress(&raw[4..], Some(size as i32))+ .map_err(|e| anyhow!("lz4 decompress failed: {e}"))?;+ if out.len() != size {+ bail!("lz4 decoded length does not match the size prefix");+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::{Read, Write};++ #[test]+ fn round_trips_through_an_independent_codec() {+ let payload = b"hello hello hello compression".repeat(50);++ // Ours -> flate2: the member we emit must be a standard gzip stream.+ let ours = gzip(&payload).unwrap();+ let mut via_flate2 = Vec::new();+ flate2::read::GzDecoder::new(&ours[..])+ .read_to_end(&mut via_flate2)+ .unwrap();+ assert_eq!(via_flate2, payload);++ // flate2 -> ours: we must decode members other encoders produced.+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ enc.write_all(&payload).unwrap();+ let theirs = enc.finish().unwrap();+ assert_eq!(gunzip(&theirs).unwrap(), payload);+ }++ #[test]+ fn rejects_a_footer_claiming_more_than_the_cap() {+ let mut stream = gzip(b"small").unwrap();+ let n = stream.len();+ stream[n - 4..].copy_from_slice(&(u32::MAX).to_le_bytes());+ let err = gunzip(&stream).unwrap_err().to_string();+ assert!(err.contains("exceeds limit"), "got: {err}");+ }++ #[test]+ fn fails_closed_on_a_footer_claiming_less_than_the_real_size() {+ let payload = b"0123456789".repeat(100);+ let mut stream = gzip(&payload).unwrap();+ let n = stream.len();+ stream[n - 4..].copy_from_slice(&8u32.to_le_bytes());+ assert!(gunzip(&stream).is_err());+ }++ #[test]+ fn rejects_truncated_and_empty_streams() {+ assert!(gunzip(b"").is_err());+ assert!(gunzip(&[0x1f, 0x8b, 0x08]).is_err());+ }++ #[test]+ fn unzstd_round_trips_bulk_and_streaming_frames() {+ let payload = b"zstd zstd zstd payload".repeat(100);+ // Bulk frame with a declared content size — what `compress_cv` emits.+ let bulk = compress_cv(&payload).unwrap();+ assert_eq!(unzstd(&bulk).unwrap(), payload);+ // A streaming encoder omits the content size, exercising the capped streaming leg.+ let mut enc = zstd::stream::write::Encoder::new(Vec::new(), 1).unwrap();+ std::io::Write::write_all(&mut enc, &payload).unwrap();+ let streamed = enc.finish().unwrap();+ assert_eq!(+ zstd::zstd_safe::get_frame_content_size(&streamed).unwrap(),+ None,+ "fixture must omit the declared content size"+ );+ assert_eq!(unzstd(&streamed).unwrap(), payload);+ }++ #[test]+ fn unzstd_rejects_a_declared_size_over_the_cap() {+ let frame = compress_cv(&vec![0u8; MAX_DECOMPRESSED_BYTES + 1]).unwrap();+ let err = unzstd(&frame).unwrap_err().to_string();+ assert!(err.contains("exceeds limit"), "got: {err}");+ }++ #[test]+ fn unzstd_rejects_garbage() {+ assert!(unzstd(b"").is_err());+ assert!(unzstd(&[0x28, 0xb5, 0x2f, 0xfd, 0x00]).is_err());+ }++ #[test]+ fn unzstd_rejects_non_single_frame_payloads() {+ // Bytes past the first frame would ride verbatim into a "kept unchanged" re-emit without+ // ever being decompressed/scrubbed, so a single self-contained frame is required.+ let frame = compress_cv(b"clean cv content").unwrap();++ // Two concatenated frames.+ let mut concatenated = frame.clone();+ concatenated.extend_from_slice(&frame);+ assert!(unzstd(&concatenated)+ .unwrap_err()+ .to_string()+ .contains("single self-contained frame"));++ // A skippable frame appended (magic 0x184D2A50, 4-byte LE length, then arbitrary bytes).+ let mut with_skippable = frame.clone();+ with_skippable.extend_from_slice(&[0x50, 0x2a, 0x4d, 0x18]);+ with_skippable.extend_from_slice(&4u32.to_le_bytes());+ with_skippable.extend_from_slice(b"junk");+ assert!(unzstd(&with_skippable)+ .unwrap_err()+ .to_string()+ .contains("single self-contained frame"));++ // Trailing garbage after a complete frame.+ let mut with_trailing = frame.clone();+ with_trailing.extend_from_slice(b"trailing");+ assert!(unzstd(&with_trailing).is_err());++ // The clean single frame still decodes.+ assert_eq!(unzstd(&frame).unwrap(), b"clean cv content");+ }++ #[test]+ fn compress_cv_emits_a_zstd_frame() {+ // Magic-byte dispatch is the consumer contract, so pin the emitted magic.+ let payload = b"payload".repeat(20);+ let zs = compress_cv(&payload).unwrap();+ assert_eq!(&zs[..4], &[0x28, 0xb5, 0x2f, 0xfd]);+ assert_eq!(+ zstd::bulk::decompress(&zs, payload.len() + 64).unwrap(),+ payload+ );+ }+}diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex 8bb7f06e0a34..e25db1f134d5 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -14,10 +14,23 @@ use crate::allow_lists::AllowLists;use crate::blur::{blur_image_data_uri, pixelate_raw_rgba};/// Cumulative decompressed-bytes budget across all cv payloads in one message: the per-payload-/// `gzip::MAX_DECOMPRESSED_BYTES` cap bounds each field, this bounds their sum so many high-ratio+/// `compression::MAX_DECOMPRESSED_BYTES` cap bounds each field, this bounds their sum so many high-ratio/// fields can't decompress gigabytes serially. Real messages total under 10 MB.const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;+/// Scrub context: the allow lists, the first-party host patterns, the cv decompression budget,+/// and the blur memo.+///+/// # Production configuration+///+/// Ingestion builds one `Ctx` per Kafka message via [`Ctx::with_first_party_hosts`], passing the+/// registrable domains derived from the team's recording domains (computed TS-side by+/// `firstPartyHostPatterns` in `ml-mirror/first-party-hosts.ts`: hostname extracted, `*.`+/// wildcards stripped, reduced to the registrable domain, lowercased). The URL scrub collapses+/// matching hosts and their subdomains to `example.com`. [`Ctx::new`] — no first-party hosts —+/// matches production only for teams with no recording domains configured; an offline consumer+/// that wants production-equivalent URL scrubbing for a team must pass the same registrable+/// domains.pub struct Ctx<'a> {pub allow: &'a AllowLists,/// Registrable-domain patterns (computed TS-side from the team's recording domains);@@ -43,9 +56,18 @@ impl<'a> Ctx<'a> {}}- /// The only budgeted cv decompression path — cv code must not call `gzip::gunzip` directly.- pub fn gunzip_cv(&self, raw: &[u8]) -> Result<Vec<u8>> {- let out = crate::gzip::gunzip(raw)?;+ /// Restore the full cv decompression budget. The budget bounds one message; per-line callers+ /// ([`crate::event::anonymize_line_with_ctx`]) reset it each call so a long session file+ /// cannot exhaust it, while the blur memo keeps spanning the whole `Ctx`.+ pub fn reset_cv_budget(&self) {+ self.cv_budget.set(CV_MESSAGE_DECOMPRESSION_BUDGET);+ }++ /// The only budgeted cv decompression path — cv code must not call the [`crate::compression`]+ /// codecs directly. Magic-byte dispatch (gzip or zstd, unknown fails closed) lives in+ /// [`crate::compression::decompress_by_magic`]; this layers the cumulative budget on top.+ pub fn decompress_cv(&self, raw: &[u8]) -> Result<Vec<u8>> {+ let out = crate::compression::decompress_by_magic(raw)?;match self.cv_budget.get().checked_sub(out.len()) {Some(rest) => self.cv_budget.set(rest),None => bail!("message exceeds the cumulative cv decompression budget"),@@ -85,6 +107,33 @@ mod tests {use super::*;use crate::testkit::png_data_uri;+ #[test]+ fn decompress_cv_dispatches_on_magic_and_budgets_both_codecs() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let payload = b"x".repeat(1000);+ let gz = crate::compression::gzip(&payload).unwrap();+ let zs = crate::compression::compress_cv(&payload).unwrap();+ for compressed in [&gz, &zs] {+ let ctx = Ctx::new(&allow);+ assert_eq!(ctx.decompress_cv(compressed).unwrap(), payload);++ let ctx = Ctx::new(&allow);+ ctx.cv_budget.set(10);+ let err = ctx.decompress_cv(compressed).unwrap_err().to_string();+ assert!(err.contains("budget"), "got: {err}");+ }+ }++ #[test]+ fn decompress_cv_fails_closed_on_unknown_magic() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ assert!(ctx+ .decompress_cv(b"plainly not a compressed stream")+ .is_err());+ assert!(ctx.decompress_cv(b"").is_err());+ }+#[test]fn blur_memo_is_stable_and_keyed_per_image() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());diff --git a/rust/replay-anonymizer/src/crosslang/README.md b/rust/replay-anonymizer/src/crosslang/README.mdnew file mode 100644index 000000000000..d020e8ec9532--- /dev/null+++ b/rust/replay-anonymizer/src/crosslang/README.md@@ -0,0 +1,19 @@+# `crosslang/` — cross-language shared contract++Files in a `crosslang/` directory are a data contract that **more than one language+implementation must agree on**. Here, the default allow lists+(`default_text_words.txt`, `default_url_segments.txt`) are the single source of truth:+the Rust crate embeds them via `include_str!`, and the TypeScript ingestion pipeline's+`default-dict.ts` mirrors them, verified by `default-dict.test.ts` (which reads these+files — it does not parse the other language's source).++## The convention++Any repo path segment named `crosslang/` marks its contents as such a contract. CI path+filters match `**/crosslang/**`, so editing a file here triggers the test suites of every+consuming language — no per-file or per-crate entry to maintain as the set grows. See the+`nodejs:` filter in `.github/workflows/ci-nodejs.yml`.++Adopt this layout for any file two languages must keep in sync (e.g. the cookieless+`test_cases.json` shared between `rust/common/cookieless` and the Node ingestion tests):+move the shared file into a `crosslang/` folder and the CI trigger follows automatically.diff --git a/rust/replay-anonymizer/src/crosslang/default_text_words.txt b/rust/replay-anonymizer/src/crosslang/default_text_words.txtnew file mode 100644index 000000000000..b2c321a37e84--- /dev/null+++ b/rust/replay-anonymizer/src/crosslang/default_text_words.txt@@ -0,0 +1,1332 @@+'cause+'em+'tis+a+ab+about+accept+accepted+access+account+accounts+ach+across+action+actions+activate+activated+active+add+added+adding+address+admin+administrator+advanced+africa+after+afternoon+agent+agile+ago+ain't+alert+alerts+alias+all+allow+allowlist+almost+alpha+alt+alternate+always+am+americas+an+analyst+analytics+and+annotations+annual+annually+anomalies+anomaly+anonymous+another+any+api+approve+approved+apps+apr+april+arabic+archive+archived+are+aren't+argument+arguments+array+article+articles+as+asia+assign+assigned+at+attach+attached+aug+august+auth+authenticate+authorize+authorized+auto+automatic+available+average+avg+b+backlog+bad+balance+bank+basic+be+bearer+been+before+begin+being+best+beta+better+between+billing+block+blocked+blocklist+blocks+blog+board+boards+body+boolean+both+bought+branch+branches+breadcrumb+breadcrumbs+breakdown+browse+bug+bugs+build+builds+built+business+but+buy+by+c+cache+caches+can+can't+cancel+cancelled+cannot+card+cards+cell+cells+change+changed+changelog+channel+channels+charge+charged+charges+chart+charts+checkbox+checkout+chinese+choose+city+class+classes+cli+click+clicks+client+clients+clone+clones+close+closed+cluster+clusters+code+cohort+cohorts+collaborator+collapse+column+columns+combobox+comment+commit+commits+companies+company+compile+compiled+complete+completed+compliance+config+configuration+configure+configured+confirm+confirmed+conflict+connect+connected+constant+constants+contact+container+containers+continue+contributor+conversion+conversions+copied+copy+could+could've+couldn't+count+country+counts+coupon+coupons+create+created+creating+credit+credits+currencies+currency+current+custom+customer+cut+d+daily+dashboard+dashboards+data+database+databases+datasets+datepicker+day+days+db+deactivate+deauthorize+debit+debug+dec+december+decline+declined+decrease+default+delete+deleted+deleting+delta+demo+demos+deny+department+dependencies+dependency+deploy+deployed+deploying+deployment+deployments+deploys+designer+destinations+detach+dev+developer+development+device+devices+dialog+did+didn't+diff+directories+directory+disable+disabled+discard+disconnect+discount+discounts+dismiss+distinct+do+docs+documentation+does+doesn't+doing+domain+don't+done+down+downgrade+download+downloaded+downloading+draft+drafts+drag+drawer+drop+dropdown+duplicate+duplicated+during+dutch+e+each+earliest+easy+edit+edited+editing+editor+either+enable+enabled+end+endpoint+endpoints+engineer+english+enterprise+entities+entity+entries+entry+enum+enums+epic+error+errored+errors+etc+eu+europe+evening+event+events+every+example+examples+execute+executed+exit+expand+experiment+experimental+experiments+expire+expired+explore+export+exported+exports+external+f+failed+failing+failure+false+faq+fast+favorite+favorited+fax+feature+features+feb+february+fee+feedback+fees+fetch+fetched+fetching+few+field+fields+file+files+filter+filtered+filters+find+finding+finish+finished+first+flag+flagged+flags+folder+folders+follow+followed+footer+for+forbidden+forgot+fork+forks+form+forms+forward+found+framework+frameworks+free+french+fri+friday+from+function+functions+funnel+funnels+future+g+gateway+german+get+global+gmt+go+good+goto+grant+graph+graphql+graphs+great+grid+group+grouped+groups+growth+grpc+guest+guests+gui+guide+guides+h+had+hadn't+handle+hard+has+hasn't+have+haven't+having+he+he'd+he'll+he's+head+header+headers+hello+help+her+here's+hers+hi+hide+high+him+his+home+homepage+host+hour+hourly+hours+how+how's+hr+http+https+i+i'd+i'll+i'm+i've+if+import+imported+imports+impression+impressions+in+inactive+incomplete+increase+index+indexes+info+input+inputs+insight+insights+install+installed+installing+interaction+interactions+interface+interfaces+internal+international+interval+intervals+into+invite+invited+invoice+invoices+is+isn't+issue+issues+it+it'd+it'll+it's+italian+item+items+its+j+jan+january+japanese+job+jobs+join+joined+jul+july+jun+june+jwt+k+kanban+key+korean+kpi+l+label+labels+landing+language+large+last+later+latest+layer+layers+ldap+lead+least+leave+left+legal+less+let's+lg+libraries+library+lifecycle+like+liked+limit+limits+link+linked+list+lists+live+load+loaded+loading+local+locale+lock+locked+log+logged+login+logout+logs+long+low+m+ma'am+main+manager+manual+many+mar+march+max+maximize+may+maybe+md+me+mean+median+medium+member+members+mention+menu+menus+merge+merges+method+methods+metric+metrics+middle+might+might've+mightn't+migration+migrations+milestone+min+mine+minimize+minute+minutes+mobile+modal+model+models+moderator+modify+module+modules+mon+monday+month+monthly+months+more+morning+most+move+moved+much+must+must've+mustn't+mute+my+n+name+namespace+namespaces+narrow+nav+navigate+navigation+need+needn't+neither+never+new+news+next+nickname+night+no+node+nodes+none+nor+not+notfound+notice+notification+notifications+nov+november+now+null+number+o+o'clock+oauth+object+objects+oct+october+of+off+offline+often+ok+okay+old+on+onboarding+online+onto+oops+open+opened+opening+operator+options+or+order+ordered+org+organization+organizations+orgs+other+otp+ought+oughtn't+our+ours+out+over+own+owner+p+package+packages+page+pages+pageview+paid+panel+panels+parameter+parameters+params+partner+passcode+password+past+paste+patch+path+paths+pause+paused+pay+paying+payload+payment+payments+paypal+pending+per+percent+percentage+permission+permissions+permit+person+personal+persons+phone+pick+pin+pinned+pipeline+pipelines+placeholder+plan+plans+please+plot+plots+plugins+pm+pod+pods+policies+policy+popover+popup+port+portuguese+post+postal+posthog+posts+pr+preferences+prefix+premium+press+preview+previous+primary+prior+privacy+private+pro+process+processed+processing+prod+production+profile+profiles+progress+project+projects+promo+promote+promoted+properties+province+prs+public+publish+published+pull+purchase+purchased+put+q+qa+quarter+quarters+queries+query+queue+queued+queues+quick+quit+quota+quotas+r+radio+rarely+rate+rates+ratio+react+ready+reassign+receipt+receipts+receive+received+recent+record+recordings+records+recover+redirect+redo+refresh+refund+refunded+refunds+region+register+registered+reject+rejected+release+released+releases+reload+remember+remote+remove+removed+removing+rename+renamed+renew+renewed+replay+replica+replicas+reply+repo+report+reported+reports+repos+repositories+repository+request+requests+reset+resize+response+responses+rest+restart+restarting+restore+resume+resumed+retention+retry+return+returns+revert+review+revoke+ribbon+roadmap+rock'n'roll+role+roles+rollback+rollout+route+routes+row+rows+rpc+run+running+russian+s+same+saml+sandbox+sat+saturday+save+saved+saving+schedule+scheduled+schema+scope+scopes+screen+scrum+sdk+search+sec+second+secondary+seconds+secret+section+sections+security+select+self+send+sending+sent+sep+sept+september+server+servers+service+services+session+sessions+set+settings+setup+shall+shan't+share+shared+sharing+she+she'd+she'll+she's+ship+shipped+short+should+should've+shouldn't+show+sidebar+signin+signout+signup+simple+since+skip+skipped+slider+slow+sm+small+snippet+snippets+so+soap+some+sometimes+soon+sorry+sort+sorted+sources+span+spanish+spans+split+sprint+ssl+sso+stable+stack+stacktrace+stage+stages+staging+star+starred+start+started+starter+starting+stat+state+statistics+stats+status+step+steps+stickiness+stop+stopped+stopping+stories+story+stream+streams+street+string+stripe+subdomain+submit+subscribe+subscribed+subscription+subscriptions+succeeded+success+successful+such+suffix+sum+sun+sunday+supplier+support+surveys+switch+sync+synced+syncing+t+tab+table+tables+tabs+tag+tagged+tags+tall+tap+task+tasks+tax+taxes+tcp+team+teams+telemetry+terms+tertiary+test+tested+testing+tests+than+thank+thanks+that+that's+the+their+theirs+them+then+there+there's+these+they+they'd+they'll+they're+they've+thick+thin+this+those+through+thu+thursday+ticket+tickets+tier+tiers+tile+tiles+timeout+timepicker+timezone+title+tls+to+today+toggle+token+tomorrow+toolbar+toolbox+tooltip+topic+topics+total+totals+trace+traces+tracking+transaction+transactions+transfer+trash+tree+trend+trends+trial+trigger+triggered+true+tue+tuesday+tutorial+tutorials+type+types+u+udp+ui+uk+unarchive+unassign+unauthorized+unavailable+unblock+unblocked+undefined+under+undo+unfollow+ungroup+uninstall+unique+uniques+unlike+unlink+unlock+unlocked+unmute+unnamed+unpin+unprocessable+unpublished+unstar+unsubscribe+untag+until+untitled+unverified+up+upcoming+update+updated+updating+upgrade+upgraded+upload+uploaded+uploading+uptime+uri+url+us+usa+usage+user+username+users+usually+utc+ux+v+validate+validated+value+values+variable+variables+variant+variants+vat+vendor+verified+verify+version+versions+versus+via+video+videos+view+viewer+views+visit+visits+void+vs+w+wait+waiting+warehouse+warning+warnings+was+wasn't+we+we'd+we'll+we're+we've+websocket+wed+wednesday+week+weekly+weeks+welcome+were+weren't+what+what's+when+when's+where+where's+which+while+who+who's+whom+whose+why+why's+wide+will+window+wire+with+within+without+won't+workflow+workflows+workspace+workspaces+world+worse+worst+would+would've+wouldn't+wow+wrapper+x+xl+xs+xxl+y+y'all+ya'll+year+yearly+years+yes+yesterday+yet+you+you'd+you'll+you're+you've+your+yours+z+zipdiff --git a/rust/replay-anonymizer/src/crosslang/default_url_segments.txt b/rust/replay-anonymizer/src/crosslang/default_url_segments.txtnew file mode 100644index 000000000000..be94298f432b--- /dev/null+++ b/rust/replay-anonymizer/src/crosslang/default_url_segments.txt@@ -0,0 +1,439 @@+2fa+about+account+accounts+action+actions+activities+activity+admin+admins+alert+alerts+all+alpha+annotation+annotations+api+apis+app+apps+archive+article+articles+asset+assets+au+audio+audit+auditlog+auth+avatar+avatars+beta+billing+blog+blogs+br+brand+brands+build+ca+callback+callbacks+card+cards+careers+cart+catalog+categories+category+changelog+checkout+cli+clone+cn+code+cohort+cohorts+collection+collections+comment+comments+companies+company+compare+compliance+confirm+confirmation+console+contact+cookies+copy+create+cron+css+dashboard+dashboards+data+dataset+datasets+de+de-de+debug+delete+demo+demos+destination+destinations+detail+details+dev+developer+developers+discover+dist+dk+doc+docs+documentation+download+downloads+duplicate+edge+edit+embed+en+en-au+en-ca+en-gb+en-us+entries+error+errors+es+es-es+es-mx+eu+event+events+example+examples+experiment+experimental+experiments+explore+export+exports+external+faq+faqs+favorites+feature_flags+feed+feedback+fi+file+files+filter+first+flag+flags+font+fonts+forgot+fork+fr+fr-ca+fr-fr+funnel+funnels+gql+graph+graphql+group+groups+grpc+guest+guests+guide+guides+health+healthz+help+history+hk+home+html+icon+icons+image+images+img+import+imports+in+incident+incidents+index+info+insight+insights+internal+invitation+invitations+invite+invites+invoice+invoices+it+items+ja-jp+javascript+job+jobs+jp+js+json+jwt+kr+last+ldap+legal+libraries+library+lifecycle+like+likes+list+log+login+logo+logos+logout+logs+manual+markdown+md+me+media+member+members+metrics+mfa+monitor+monitoring+more+move+mx+new+news+next+nl+no+node_modules+notebook+notebooks+oauth+oauth2+objects+openid+order+orders+org+organization+organizations+orgs+otp+out+overview+owner+owners+package+packages+page+pages+passcode+password+path+paths+payment+payments+person+persons+ping+pipeline+pipelines+pl+plan+plans+playground+plugin+plugins+post+posts+preferences+press+prev+preview+previous+pricing+privacy+private+product+products+profile+profiles+project+projects+pt+pt-br+pt-pt+public+queries+query+queue+queues+reactions+ready+readyz+receipt+receipts+recording+recordings+records+recover+recovery+redirect+reference+register+registration+release+releases+remove+rename+replay+report+reports+reset+rest+restore+results+retention+review+reviews+roadmap+rpc+ru+saml+sample+samples+sandbox+saved+schedule+schedules+sdk+sdks+se+search+security+self+session+sessions+settings+share+shares+shop+show+signin+signout+signup+sitemap+snippet+snippets+soap+sort+source+sources+sql+sso+stat+static+stats+status+stickiness+store+stories+story+subscription+subscriptions+summary+support+survey+surveys+tag+tags+task+tasks+team+teams+terms+thumbnail+thumbnails+thumbs+timeline+toml+tool+tools+tos+totp+trace+traces+trend+trending+trends+trpc+ts+tutorial+tutorials+tw+txt+typescript+uk+update+upload+uploads+uptime+us+user+users+v1+v2+v3+v4+v5+v6+v7+vendor+verification+verify+version+versions+video+videos+view+warehouse+webhook+webhooks+wishlist+worker+workers+workspace+workspaces+ws+xml+yaml+you+zh-cn+zh-twdiff --git a/rust/replay-anonymizer/src/cv.rs b/rust/replay-anonymizer/src/cv.rsindex 5050ccb7f9b2..47a6fa3125d0 100644--- a/rust/replay-anonymizer/src/cv.rs+++ b/rust/replay-anonymizer/src/cv.rs@@ -6,17 +6,17 @@ use simd_json::prelude::Writable;use simd_json::StaticNode;use crate::bytewalk;+use crate::compression;use crate::context::Ctx;use crate::dom::{scrub_full_snapshot, scrub_mutation_adds, scrub_mutation_attributes, scrub_mutation_texts,};-use crate::gzip;use crate::json::{as_array_mut, key, parse_untrusted, reject_if_too_deep, string_value};/// PostHog wire format: each gzip byte stored as its U+00XX codepoint (latin-1). Per-char is/// deliberate — a hand-rolled byte loop measured slower than `chars()` on high-entropy gzip bytes./// The structural win is decoding off the escaped wire span (`bytewalk::latin1_from_wire`) instead.-fn latin1_to_bytes(s: &str) -> Result<Vec<u8>> {+pub(crate) fn latin1_to_bytes(s: &str) -> Result<Vec<u8>> {let mut out = Vec::with_capacity(s.len());for c in s.chars() {let cp = c as u32;@@ -28,7 +28,7 @@ fn latin1_to_bytes(s: &str) -> Result<Vec<u8>> {Ok(out)}-fn bytes_to_latin1(bytes: &[u8]) -> String {+pub(crate) fn bytes_to_latin1(bytes: &[u8]) -> String {// Exact presize: one two-byte UTF-8 sequence per byte >= 0x80 (the count pass vectorizes).let extra = bytes.iter().filter(|&&b| b >= 0x80).count();let mut out = String::with_capacity(bytes.len() + extra);@@ -40,14 +40,18 @@ fn bytes_to_latin1(bytes: &[u8]) -> String {/// Not depth-guarded: the byte walk that consumes the result self-bounds its recursion, so the/// whole-buffer depth scan (~6% of the pipeline) runs only in front of the parse fallbacks below.-fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<Vec<u8>> {+/// Also reports whether the wire held a zstd frame (the crate's own re-emit format) rather than+/// the SDK's gzip — unchanged zstd payloads can keep their original bytes.+fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<(Vec<u8>, bool)> {let raw = latin1_to_bytes(s)?;- ctx.gunzip_cv(&raw).context("gunzip cv data")+ let was_zstd = raw.starts_with(&compression::ZSTD_MAGIC);+ let out = ctx.decompress_cv(&raw).context("decompress cv data")?;+ Ok((out, was_zstd))}fn compress_bytes(json: &[u8]) -> Result<String> {Ok(bytes_to_latin1(- &gzip::compress_cv(json).context("compress cv payload")?,+ &compression::compress_cv(json).context("compress cv payload")?,))}@@ -55,19 +59,24 @@ fn compress_value(value: &Value<'_>) -> Result<String> {compress_bytes(value.encode().as_bytes())}-/// Scrub a `cv`-compressed FullSnapshot `data` value (a gzipped latin-1 string) in place. Returns-/// whether it changed. The caller has already checked the value is a string; non-string data routes-/// through the plain scrub instead.+/// Scrub a `cv`-compressed FullSnapshot `data` value (a compressed latin-1 string, gzip or zstd)+/// in place. Returns whether it changed. The caller has already checked the value is a string;+/// non-string data routes through the plain scrub instead.pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Result<bool> {let Value::String(s) = &*data else {bail!("compressed full snapshot data is not a string");};- let mut scratch = decompress_string(ctx, s)?;+ let (mut scratch, was_zstd) = decompress_string(ctx, s)?;// Byte-walk first; fall through to the parse below on decline.let mut walked = Vec::with_capacity(scratch.len() + 64);match bytewalk::scrub_cv_snapshot(ctx, &scratch, &mut walked) {- // Unchanged payloads re-emit too: the whole output is zstd, never mixed-format blocks.Some(false) => {+ // Unchanged zstd keeps its original bytes (safe: the walk proved it duplicate-key+ // free), so a re-scrub is a no-op. Unchanged gzip still re-emits: the whole output is+ // zstd, never mixed-format blocks.+ if was_zstd {+ return Ok(false);+ }*data = string_value(compress_bytes(&scratch)?);return Ok(true);}@@ -97,8 +106,9 @@ fn scrub_sub(ctx: &Ctx<'_>, sub_key: &str, arr: &mut Vec<Value<'_>>) -> bool {}/// Scrub a `cv`-compressed Mutation `data` object in place. Returns whether it changed. Sub-fields-/// arrive as gzipped strings or plain arrays; gzipped ones always re-emit as zstd (never-/// mixed-format blocks), plain arrays scrub in place.+/// arrive as compressed strings (gzip or zstd) or plain arrays; gzip ones always re-emit as zstd+/// (never mixed-format blocks), unchanged zstd ones keep their original bytes (so a re-scrub is a+/// no-op), plain arrays scrub in place.pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> Result<bool> {const KEYS: [(&str, bytewalk::CvMutationField); 3] = [("texts", bytewalk::CvMutationField::Texts),@@ -116,14 +126,23 @@ pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> ResultSome(Value::Static(StaticNode::Null)) => {} // null -> keep verbatimSome(Value::String(s)) if s.is_empty() => {} // empty string -> keep verbatimSome(Value::String(s)) => {- let mut scratch = decompress_string(ctx, s)?;+ let (mut scratch, was_zstd) = decompress_string(ctx, s)?;let mut walked = Vec::with_capacity(scratch.len() + 64);- changed = true;match bytewalk::scrub_cv_mutation_field(ctx, field, &scratch, &mut walked) {- Some(false) => recompress.push((sub_key, scratch)),- Some(true) => recompress.push((sub_key, walked)),+ // Unchanged zstd keeps its original bytes (the walk proved it duplicate-key+ // free); everything else re-emits as zstd.+ Some(false) if was_zstd => {}+ Some(false) => {+ changed = true;+ recompress.push((sub_key, scratch));+ }+ Some(true) => {+ changed = true;+ recompress.push((sub_key, walked));+ }None => {// As in the full-snapshot fallback: the parse recurses, the walk didn't.+ // Always re-emits (the parse can't prove the input duplicate-key free).reject_if_too_deep(&scratch, "cv mutation sub-field")?;let mut decoded =parse_untrusted(&mut scratch).context("parse cv mutation sub-field")?;@@ -132,6 +151,7 @@ pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> Resultbail!("cv mutation sub-field did not decode to an array");};scrub_sub(ctx, sub_key, arr);+ changed = true;recompress.push((sub_key, decoded.encode().into_bytes()));}}@@ -165,7 +185,12 @@ mod tests {// Test inputs model what the SDK sends, which is always gzip.fn compress_json(json: &[u8]) -> String {- bytes_to_latin1(&gzip::gzip(json).unwrap())+ bytes_to_latin1(&compression::gzip(json).unwrap())+ }++ // The crate's own re-emit format: what already-anonymized mirror data carries.+ fn compress_json_zstd(json: &[u8]) -> String {+ bytes_to_latin1(&compression::compress_cv(json).unwrap())}// Outputs are always zstd frames; assert the magic (the loader's dispatch contract) on decode.@@ -250,6 +275,81 @@ mod tests {assert_eq!(unzstd("adds"), adds_json);}+ #[test]+ fn zstd_full_snapshot_scrubs_to_the_same_result_as_its_gzip_twin() {+ let allow = AllowLists::new(["keep"], Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ let json = br#"{"node":{"type":0,"childNodes":[{"type":3,"textContent":"keep secret"}]},"initialOffset":{"top":0,"left":0}}"#;++ let mut gz_data = string_value(compress_json(json));+ assert!(scrub_compressed_full_snapshot(&ctx, &mut gz_data).unwrap());+ let mut zs_data = string_value(compress_json_zstd(json));+ assert!(scrub_compressed_full_snapshot(&ctx, &mut zs_data).unwrap());++ let gz_out = decompress_value(as_str(&gz_data).unwrap());+ assert_eq!(+ gz_out["node"]["childNodes"][0]["textContent"],+ "keep ******"+ );+ assert_eq!(gz_out, decompress_value(as_str(&zs_data).unwrap()));+ }++ #[test]+ fn zstd_mutation_subfield_scrubs_to_the_same_result_as_its_gzip_twin() {+ let allow = AllowLists::new(["keep"], Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ let json = br#"[{"id":5,"value":"keep secret"}]"#;++ let run = |texts: String| -> serde_json::Value {+ let mut data = Object::default();+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));+ data.insert(Cow::Borrowed("texts"), string_value(texts));+ assert!(scrub_compressed_mutation(&ctx, &mut data).unwrap());+ decompress_value(as_str(data.get("texts").unwrap()).unwrap())+ };++ let gz_out = run(compress_json(json));+ assert_eq!(gz_out[0]["value"], "keep ******");+ assert_eq!(gz_out, run(compress_json_zstd(json)));+ }++ #[test]+ fn rescrubbing_anonymized_cv_output_is_a_no_op() {+ // Mirror data has been through the anonymizer once (cv payloads re-emitted as zstd); a+ // second pass must succeed and report "unchanged" so the caller keeps its bytes verbatim.+ let allow = AllowLists::new(["keep"], Vec::<String>::new());+ let snapshot_gz = compress_json(+ br#"{"node":{"type":0,"childNodes":[{"type":3,"textContent":"keep secret"}]},"initialOffset":{"top":0,"left":0}}"#,+ );+ let texts_gz = compress_json(br#"[{"id":5,"value":"keep secret"}]"#);+ let message = serde_json::json!({ "w1": [+ { "type": 2, "cv": "2024-10", "data": snapshot_gz },+ { "type": 3, "cv": "2024-10", "data": { "source": 0, "texts": texts_gz } },+ ]});++ let mut first_pass = serde_json::to_vec(&message).unwrap();+ let scrubbed = crate::event::anonymize_message(&allow, &mut first_pass)+ .unwrap()+ .expect("the first pass scrubs and re-emits");++ let mut second_pass = scrubbed.into_bytes();+ assert!(+ crate::event::anonymize_message(&allow, &mut second_pass)+ .unwrap()+ .is_none(),+ "re-scrubbing already-anonymized output must be a no-op"+ );+ }++ #[test]+ fn compressed_payload_with_garbage_magic_fails_closed() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ // Valid latin-1, but neither gzip nor zstd magic.+ let mut data = string_value("XYZW not a compressed stream".to_string());+ assert!(scrub_compressed_full_snapshot(&ctx, &mut data).is_err());+ }+#[test]fn compressed_mutation_with_escaped_keys_scrubs_via_parse_fallback() {let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());diff --git a/rust/replay-anonymizer/src/event.rs b/rust/replay-anonymizer/src/event.rsindex 4cd6220b3206..e1bbf30f3402 100644--- a/rust/replay-anonymizer/src/event.rs+++ b/rust/replay-anonymizer/src/event.rs@@ -38,51 +38,129 @@ pub const SOURCE_ADOPTED_STYLESHEET: u8 = 15;pub const NETWORK_PLUGIN: &str = "rrweb/network@1";pub const CONSOLE_PLUGIN: &str = "rrweb/console@1";+/// Panic backstop for the anyhow-based entry points (see [`crate::unwind`]).+fn contain_panics<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {+ crate::unwind::contain_unwind(f, |msg| anyhow::anyhow!("panic while anonymizing: {msg}"))+}+/// Anonymizes every event in a parsed message (`{ windowId: Event[] }`) in place. `Ok(None)` means/// nothing changed (the caller can keep its original). `Err` means an event could not be anonymized —/// fail closed, the caller must drop the message. A single `Ctx` spans the whole message so its blur/// memo is shared across every event (an image recurring across events is blurred once).pub fn anonymize_message(allow: &AllowLists, json: &mut [u8]) -> Result<Option<String>> {- reject_if_too_deep(json, "eventsByWindowId")?;- let mut root = parse_untrusted(json).context("parse eventsByWindowId json")?;- let Some(obj) = as_object_mut(&mut root) else {- bail!("eventsByWindowId is not an object");- };- let ctx = Ctx::new(allow);- let mut changed = false;- for (_, events) in obj.iter_mut() {- if let Some(arr) = as_array_mut(events) {- for event in arr.iter_mut() {- changed |= route_event(&ctx, event)?;+ contain_panics(|| {+ reject_if_too_deep(json, "eventsByWindowId")?;+ let mut root = parse_untrusted(json).context("parse eventsByWindowId json")?;+ let Some(obj) = as_object_mut(&mut root) else {+ bail!("eventsByWindowId is not an object");+ };+ let ctx = Ctx::new(allow);+ let mut changed = false;+ for (_, events) in obj.iter_mut() {+ if let Some(arr) = as_array_mut(events) {+ for event in arr.iter_mut() {+ changed |= route_event(&ctx, event)?;+ }}}+ if !changed {+ return Ok(None);+ }+ Ok(Some(root.encode()))+ })+}++/// Scrub one JSONL line: a bare rrweb event object or the PostHog `["window_id", event]` tuple.+/// `Ok(Some(scrubbed))` = the line changed. `Ok(None)` = a recognized event the scrub policy left+/// unchanged (identical to the input). `Err` = could not anonymize; fail closed, drop the line.+///+/// "Unchanged" applies the production scrub policy, which deliberately passes some events through+/// untouched — DomContentLoaded/Load, and types/sources the router has no rule for — exactly as the+/// ingestion pipeline does (mirror data read offline was produced under this same policy). Callers+/// wanting a stricter policy than production must layer it themselves.+///+/// `line` is scratch — the in-place parse consumes it, so on `Ok(None)` keep a prior copy of the+/// bytes, not this buffer. Tuple lines come back with the wrapper intact and the window id+/// untouched. Anything that is not one of the two recognized shapes — a scalar, an array that is+/// not a `[string, object]` pair, or an object with no numeric rrweb `type` — is an `Err`, not a+/// silent pass-through: a scrubber must fail closed on input it doesn't understand rather than leave+/// the caller to guess whether unrecognized bytes were safe to keep. Invalid JSON is likewise an+/// `Err`.+pub fn anonymize_line(allow: &AllowLists, line: &mut [u8]) -> Result<Option<String>> {+ anonymize_line_with_ctx(&Ctx::new(allow), line)+}++/// Fail closed on an object that is not an rrweb event. Every rrweb event carries a numeric `type`;+/// an object without one is not something the scrubber recognizes, so — rather than pass it through+/// unscrubbed as `Ok(None)` — reject it (pass-through events like Load still have a `type`).+fn require_event_type(event: &Value<'_>) -> Result<()> {+ match as_object(event)+ .and_then(|o| o.get("type"))+ .and_then(as_small_uint)+ {+ Some(_) => Ok(()),+ None => bail!("jsonl line object has no numeric rrweb event `type`"),}- if !changed {- return Ok(None);- }- Ok(Some(root.encode()))+}++/// [`anonymize_line`] with a caller-owned [`Ctx`], so one blur memo spans a whole session file+/// (an image recurring across lines is decoded and blurred once, like `anonymize_message` does+/// across a message's events). The cumulative cv decompression budget is per line — it resets on+/// every call, so a long session cannot starve later lines.+pub fn anonymize_line_with_ctx(ctx: &Ctx<'_>, line: &mut [u8]) -> Result<Option<String>> {+ contain_panics(|| {+ reject_if_too_deep(line, "jsonl line")?;+ let mut root = parse_untrusted(line).context("parse jsonl line")?;+ ctx.reset_cv_budget();+ let changed = match &mut root {+ Value::Object(_) => {+ require_event_type(&root)?;+ route_event(ctx, &mut root)?+ }+ Value::Array(items) => match items.as_mut_slice() {+ [Value::String(_), event @ Value::Object(_)] => {+ require_event_type(event)?;+ route_event(ctx, event)?+ }+ _ => bail!("jsonl line is an array but not a [window_id, event] tuple"),+ },+ _ => {+ bail!("jsonl line is neither an rrweb event object nor a [window_id, event] tuple")+ }+ };+ if !changed {+ return Ok(None);+ }+ Ok(Some(root.encode()))+ })}/// Convenience for tests/callers holding a single event as a JSON string: parse, scrub, re-serialize.pub fn anonymize_event_str(allow: &AllowLists, event_json: &str) -> Result<String> {- let mut bytes = event_json.as_bytes().to_vec();- let mut value = parse_untrusted(&mut bytes).context("parse event json")?;- anonymize_event(allow, &mut value)?;- Ok(value.encode())+ contain_panics(|| {+ let mut bytes = event_json.as_bytes().to_vec();+ let mut value = parse_untrusted(&mut bytes).context("parse event json")?;+ route_event(&Ctx::new(allow), &mut value)?;+ Ok(value.encode())+ })}/// Scrubs a single event in place, returning whether it changed. `Err` = "could not anonymize"./// Builds its own `Ctx` (single-event scope); the message path uses [`anonymize_message`] instead so/// the blur memo is shared across events.pub fn anonymize_event(allow: &AllowLists, event: &mut Value<'_>) -> Result<bool> {- route_event(&Ctx::new(allow), event)+ contain_panics(|| route_event(&Ctx::new(allow), event))}/// True when the event's `cv` marker means "compressed" (present and non-null).+#[doc(hidden)]pub fn is_compressed_marker(v: Option<&Value<'_>>) -> bool {matches!(v, Some(v) if !matches!(v, Value::Static(StaticNode::Null)))}+/// Internal routing shared by the entry points — consume [`anonymize_event`] or+/// [`anonymize_line`] instead; this may change signature in any release.+#[doc(hidden)]pub fn route_event(ctx: &Ctx<'_>, event: &mut Value<'_>) -> Result<bool> {let Some(obj) = as_object_mut(event) else {return Ok(false);@@ -98,6 +176,7 @@ pub fn route_event(ctx: &Ctx<'_>, event: &mut Value<'_>) -> Result<bool> {/// Scrubs an event's `data` value in place given its routing shape (`type` + `cv` marker). This is the/// single routing implementation shared by the tree walk and the streaming span-splice path: everything/// the anonymizer changes lives inside `data`, so both paths agree by construction.+#[doc(hidden)]pub fn route_data(ctx: &Ctx<'_>,ty: Option<u8>,@@ -217,6 +296,125 @@ mod tests {assert!(anonymize_message(&allow, &mut json).unwrap().is_none());}+ #[test]+ fn line_scrubs_a_tuple_keeping_the_wrapper_and_window_id() {+ let allow = AllowLists::new(["keep"], Vec::<String>::new());+ let mut line =+ br#"["w-1",{"type":3,"data":{"source":5,"id":1,"text":"keep secret","isChecked":false}}]"#+ .to_vec();+ let out = anonymize_line(&allow, &mut line)+ .unwrap()+ .expect("the text changes");+ assert!(out.starts_with(r#"["w-1","#), "wrapper intact: {out}");+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert_eq!(v[1]["data"]["text"], "keep ******");+ }++ #[test]+ fn line_scrubs_a_bare_event_like_its_tuple_twin() {+ let allow = AllowLists::new(["keep"], Vec::<String>::new());+ let event =+ r#"{"type":3,"data":{"source":5,"id":1,"text":"keep secret","isChecked":false}}"#;++ let mut bare = event.as_bytes().to_vec();+ let bare_out = anonymize_line(&allow, &mut bare).unwrap().unwrap();++ let mut tuple = format!(r#"["w-1",{event}]"#).into_bytes();+ let tuple_out = anonymize_line(&allow, &mut tuple).unwrap().unwrap();++ let tuple_v: serde_json::Value = serde_json::from_str(&tuple_out).unwrap();+ let bare_v: serde_json::Value = serde_json::from_str(&bare_out).unwrap();+ assert_eq!(bare_v, tuple_v[1]);+ }++ #[test]+ fn line_returns_none_only_for_unchanged_recognized_events() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ // Recognized events that need no scrubbing (type 1 is pass-through), bare and tuple-wrapped.+ for line in [+ br#"{"type":1,"data":{}}"#.as_slice(),+ br#"["w-1",{"type":1,"data":{}}]"#.as_slice(),+ ] {+ let mut bytes = line.to_vec();+ assert!(+ anonymize_line(&allow, &mut bytes).unwrap().is_none(),+ "expected Ok(None) for {}",+ String::from_utf8_lossy(line)+ );+ }+ }++ #[test]+ fn line_fails_closed_on_unrecognized_shapes_and_invalid_json() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ // A scrubber must not silently pass through input it doesn't recognize as an event.+ for line in [+ br#"["w-1","not an event"]"#.as_slice(), // tuple with a non-object second element+ br#"[{"type":1},{"type":1}]"#.as_slice(), // array of events, not a [window_id, event] pair+ br#"["w-1",{"type":1},{"extra":1}]"#.as_slice(), // three-element array+ br#"{"foo":"bar"}"#.as_slice(), // object with no rrweb event `type`+ br#"["w-1",{"foo":"bar"}]"#.as_slice(), // tuple wrapping a non-event object+ br#"42"#.as_slice(), // scalar+ br#""just a string""#.as_slice(), // scalar+ br#"{not json"#.as_slice(), // invalid JSON+ ] {+ let mut bytes = line.to_vec();+ assert!(+ anonymize_line(&allow, &mut bytes).is_err(),+ "expected Err for {}",+ String::from_utf8_lossy(line)+ );+ }+ }++ #[test]+ fn line_streaming_shares_the_blur_memo_across_lines() {+ use crate::testkit::png_data_uri;+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ let uri = png_data_uri(40, 40, [12, 34, 56, 255]);+ let line = serde_json::to_string(&serde_json::json!({+ "type": 2,+ "data": {+ "node": { "type": 0, "childNodes": [+ { "type": 2, "tagName": "div", "attributes": { "rr_dataURL": uri }, "childNodes": [] }+ ]},+ "initialOffset": { "top": 0, "left": 0 }+ }+ }))+ .unwrap();++ let mut first = line.clone().into_bytes();+ let mut second = line.into_bytes();+ let first_out = anonymize_line_with_ctx(&ctx, &mut first).unwrap().unwrap();+ let second_out = anonymize_line_with_ctx(&ctx, &mut second).unwrap().unwrap();+ assert_eq!(+ first_out, second_out,+ "a recurring image must blur identically through the shared memo"+ );+ }++ #[test]+ fn line_resets_the_cv_budget_per_call() {+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());+ let ctx = Ctx::new(&allow);+ let texts_gz = crate::cv::bytes_to_latin1(+ &crate::compression::gzip(br#"[{"id":5,"value":"topsecret stuff"}]"#).unwrap(),+ );+ let line = serde_json::to_string(&serde_json::json!(+ { "type": 3, "cv": "2024-10", "data": { "source": 0, "texts": texts_gz } }+ ))+ .unwrap();++ // A prior line exhausted the budget; the next call must start from a fresh one.+ ctx.cv_budget.set(0);+ let mut bytes = line.into_bytes();+ let out = anonymize_line_with_ctx(&ctx, &mut bytes)+ .unwrap()+ .expect("the cv payload decompresses and scrubs");+ assert!(out.contains("source"), "still a mutation event: {out}");+ }+#[test]fn recurring_inline_image_is_neutralized_across_windows() {// An inline image can recur across events/windows in one message (the case the per-message blurdiff --git a/rust/replay-anonymizer/src/gzip.rs b/rust/replay-anonymizer/src/gzip.rsdeleted file mode 100644index 2813a56ec5b4..000000000000--- a/rust/replay-anonymizer/src/gzip.rs+++ /dev/null@@ -1,137 +0,0 @@-//! One-shot compression codecs: gzip on libdeflate (~2-3x the throughput of the streaming flate2-//! legs it replaced, at the cost of needing the output size up front — which gzip carries in its-//! ISIZE footer), plus the zstd leg that re-emits `cv` payloads.--use std::cell::RefCell;--use anyhow::{anyhow, bail, Result};-use libdeflater::{CompressionLvl, Compressor, Decompressor};--/// Compression-bomb cap: ~6x the 10.3 MB largest payload in a 1000-message production sample.-/// Exceeding it fails closed as a classified DLQ instead of an unclassifiable OOM crash-loop.-pub const MAX_DECOMPRESSED_BYTES: usize = 64 * 1024 * 1024;--/// zstd level for re-emitted cv payloads. Counterintuitively negative: raw codec ratio is 20%-/// worse than level 1 (0.145 vs 0.121 on the real cv corpus), but these bytes are stored-/// latin-1-in-JSON inside snappy blocks, where entropy-coded output pays twice — high bytes cost-/// 2 UTF-8 bytes each and are incompressible to the block snappy, while the raw ASCII literals-/// negative levels leave behind cost 1 byte and snappy still compresses them. Measured end to-/// end on the corpus, -1 beats 1 on every axis: 3.67 vs 3.88 ms/msg, snappy'd blocks 272.7 vs-/// 289.2 MB, and the loader-side decompress is ~30% faster. Levels below -1 gain nothing.-const CV_ZSTD_LEVEL: i32 = -1;--thread_local! {- // Reused per thread: each codec state is a one-time ~50-300 KB malloc and cv work runs several- // times per event.- static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());- static COMPRESSOR: RefCell<Compressor> =- RefCell::new(Compressor::new(CompressionLvl::default()));- static ZSTD_COMPRESSOR: RefCell<zstd::bulk::Compressor<'static>> = RefCell::new(- zstd::bulk::Compressor::new(CV_ZSTD_LEVEL).expect("static zstd level is valid"),- );-}--/// Gunzip a single-member stream. The output buffer is sized exactly from the stream's ISIZE-/// footer (uncompressed length mod 2^32, RFC 1952), so both footer lies fail closed: claiming-/// more than [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating, and claiming less than the-/// real size makes libdeflate stop at the buffer end with `InsufficientSpace`.-pub fn gunzip(raw: &[u8]) -> Result<Vec<u8>> {- let Some(footer) = raw.len().checked_sub(4).map(|start| &raw[start..]) else {- bail!("gzip stream too short");- };- let hint = u32::from_le_bytes(footer.try_into().expect("4-byte slice")) as usize;- if hint > MAX_DECOMPRESSED_BYTES {- bail!("gzip uncompressed size exceeds limit");- }- let mut out = vec![0u8; hint];- let n = DECOMPRESSOR- .with(|d| d.borrow_mut().gzip_decompress(raw, &mut out))- .map_err(|e| anyhow!("gunzip: {e:?}"))?;- out.truncate(n);- Ok(out)-}--/// Gzip `payload` as one default-level (6, matching both flate2's default and the TS pipeline's-/// pako default) member.-pub fn gzip(payload: &[u8]) -> Result<Vec<u8>> {- COMPRESSOR.with(|c| {- let mut c = c.borrow_mut();- let mut out = vec![0u8; c.gzip_compress_bound(payload.len())];- let n = c- .gzip_compress(payload, &mut out)- .map_err(|e| anyhow!("gzip: {e:?}"))?;- out.truncate(n);- Ok(out)- })-}--/// Re-compress a cv payload as zstd. The consumer distinguishes formats by magic bytes alone-/// (`1f 8b` gzip vs `28 b5 2f fd` zstd), so historical gzip blocks stay readable.-pub fn compress_cv(payload: &[u8]) -> Result<Vec<u8>> {- ZSTD_COMPRESSOR.with(|c| {- c.borrow_mut()- .compress(payload)- .map_err(|e| anyhow!("zstd: {e}"))- })-}--#[cfg(test)]-mod tests {- use super::*;- use std::io::{Read, Write};-- #[test]- fn round_trips_through_an_independent_codec() {- let payload = b"hello hello hello compression".repeat(50);-- // Ours -> flate2: the member we emit must be a standard gzip stream.- let ours = gzip(&payload).unwrap();- let mut via_flate2 = Vec::new();- flate2::read::GzDecoder::new(&ours[..])- .read_to_end(&mut via_flate2)- .unwrap();- assert_eq!(via_flate2, payload);-- // flate2 -> ours: we must decode members other encoders produced.- let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());- enc.write_all(&payload).unwrap();- let theirs = enc.finish().unwrap();- assert_eq!(gunzip(&theirs).unwrap(), payload);- }-- #[test]- fn rejects_a_footer_claiming_more_than_the_cap() {- let mut stream = gzip(b"small").unwrap();- let n = stream.len();- stream[n - 4..].copy_from_slice(&(u32::MAX).to_le_bytes());- let err = gunzip(&stream).unwrap_err().to_string();- assert!(err.contains("exceeds limit"), "got: {err}");- }-- #[test]- fn fails_closed_on_a_footer_claiming_less_than_the_real_size() {- let payload = b"0123456789".repeat(100);- let mut stream = gzip(&payload).unwrap();- let n = stream.len();- stream[n - 4..].copy_from_slice(&8u32.to_le_bytes());- assert!(gunzip(&stream).is_err());- }-- #[test]- fn rejects_truncated_and_empty_streams() {- assert!(gunzip(b"").is_err());- assert!(gunzip(&[0x1f, 0x8b, 0x08]).is_err());- }-- #[test]- fn compress_cv_emits_a_zstd_frame() {- // Magic-byte dispatch is the consumer contract, so pin the emitted magic.- let payload = b"payload".repeat(20);- let zs = compress_cv(&payload).unwrap();- assert_eq!(&zs[..4], &[0x28, 0xb5, 0x2f, 0xfd]);- assert_eq!(- zstd::bulk::decompress(&zs, payload.len() + 64).unwrap(),- payload- );- }-}diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 5d5481afa8c6..4dea2d7d95ca 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -8,35 +8,68 @@//! goes in, ready-to-write JSONL block lines plus envelope/per-event metadata come out — this crate//! owns the parse, the scrub, and the serialize.//!-//! Scrubbing operates on untrusted input and may panic on pathological payloads; callers that must-//! fail closed (drop the message rather than crash) should wrap calls in `catch_unwind` under-//! `panic = "unwind"`, as `replay-anonymizer-node` does.+//! Scrubbing operates on untrusted input. The public entry points contain panics on pathological+//! payloads and convert them to errors (fail closed: the caller drops the message) — no+//! `catch_unwind` obligation on consumers. Caveat: under `panic = "abort"` the backstop cannot run+//! and a panic still kills the process; builds that must fail closed need `panic = "unwind"` (the+//! Node addon enforces this at compile time).+//!+//! # Supported API+//!+//! The stable crates.io surface is what this page documents: [`AllowLists`], [`Ctx`], the event+//! entry points ([`anonymize_message`], [`anonymize_event`], [`anonymize_line`] and friends), the+//! byte-buffer snapshot pipeline ([`anonymize_kafka_payload`] and friends), the rrweb routing+//! constants in [`event`], and — behind the default `typed-parse` feature — the typed rrweb parse+//! in [`typed`] ([`parse_scrubbed_event`]). Everything `#[doc(hidden)]` stays `pub` only for this+//! workspace (the Node addon, the parity tests) — it is internal and may change or disappear in+//! any release.pub mod allow_lists;+#[doc(hidden)]pub mod assets;+#[doc(hidden)]pub mod blur;+#[doc(hidden)]pub mod bytewalk;+#[doc(hidden)]pub mod canvas;+#[doc(hidden)]+pub mod compression;pub mod context;+#[doc(hidden)]pub mod css;+#[doc(hidden)]pub mod cv;+#[doc(hidden)]pub mod dom;pub mod event;-pub mod gzip;+#[doc(hidden)]pub mod json;+#[doc(hidden)]pub mod scan;pub mod snapshot;+#[doc(hidden)]pub mod text;+#[cfg(feature = "typed-parse")]+pub mod typed;+mod unwind;+#[doc(hidden)]pub mod url;+#[doc(hidden)]pub mod value;pub use allow_lists::AllowLists;pub use context::Ctx;-pub use event::{anonymize_event, anonymize_event_str, anonymize_message};+pub use event::{+ anonymize_event, anonymize_event_str, anonymize_line, anonymize_line_with_ctx,+ anonymize_message,+};pub use snapshot::{anonymize_kafka_payload, anonymize_kafka_payload_opts, AnonymizeOpts, AnonymizedMessage,FailKind, Failure, Route,};+#[cfg(feature = "typed-parse")]+pub use typed::{parse_scrubbed_event, parse_scrubbed_event_with_ctx};/// Shared helpers for the image-neutralization tests across modules.#[cfg(test)]diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 73bdbd1302c2..efbd3e921880 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -87,6 +87,21 @@ impl Failure {type SResult<T> = Result<T, Failure>;+/// Panic backstop for the byte-buffer entry points (see [`crate::unwind`]): a panic on untrusted+/// input classifies as `anonymize_failed`, so the caller drops the message like any scrub error.+///+/// The panic message is deliberately dropped, not interpolated into the detail: this path runs on+/// the ingestion hot path where the detail is logged into the DLQ at volume, and a std slice/`expect`+/// panic embeds a chunk of the offending value — i.e. raw unscrubbed replay input. A static detail+/// keeps that PII out of logs (matching what the Node addon's own outer `catch_unwind` did before+/// this backstop existed). The offline `anyhow` entry points keep the message, where loud,+/// input-bearing errors are acceptable and not logged at volume.+fn contain_panics<T>(f: impl FnOnce() -> SResult<T>) -> SResult<T> {+ crate::unwind::contain_unwind(f, |_msg| {+ Failure::new(FailKind::AnonymizeFailed, "panic while anonymizing")+ })+}+// Per-event flags, mirroring `rrweb-types.ts` / `segmentation.ts` predicates.pub const FLAG_ACTIVE: u8 = 1;pub const FLAG_CLICK: u8 = 2;@@ -170,38 +185,20 @@ pub struct AnonymizedMessage {pub route: Route,}-/// Decompressed payloads are capped (shared with the gzip codec's bomb cap) so a forged lz4 size-/// prefix (a u32, so up to 4 GiB) cannot force the allocation; real replay payloads decompress to-/// tens of MB at most.-const MAX_DECOMPRESSED_LEN: usize = crate::gzip::MAX_DECOMPRESSED_BYTES;-const GZIP_MAGIC: &[u8; 4] = &[0x1f, 0x8b, 0x08, 0x00];/// Decompress a raw Kafka message value the way capture wraps it (mirrors the TS/// `decompressMessageValue`): lz4 block with a 4-byte LE uncompressed-size prefix when the/// `content-encoding` header says lz4, gzip when the magic bytes say so, else pass through.+/// Codec failures classify as `invalid_compressed_data`, matching the TS path.pub fn decompress_payload(raw: Vec<u8>, content_encoding: Option<&str>) -> SResult<Vec<u8>> {- let bad = |detail: &str| Failure::new(FailKind::InvalidCompressedData, detail);+ let bad = |e: anyhow::Error| Failure::new(FailKind::InvalidCompressedData, format!("{e:#}"));if content_encoding == Some("lz4") {- let size_bytes: [u8; 4] = raw- .get(..4)- .and_then(|b| b.try_into().ok())- .ok_or_else(|| bad("lz4 payload too short for size prefix"))?;- let size = u32::from_le_bytes(size_bytes) as usize;- if size > MAX_DECOMPRESSED_LEN {- return Err(bad("lz4 uncompressed size exceeds limit"));- }- let out = lz4::block::decompress(&raw[4..], Some(size as i32))- .map_err(|e| bad(&format!("lz4 decompress failed: {e}")))?;- // Classify a lying size prefix as invalid_compressed_data (matching the TS path) rather- // than letting the short/long buffer surface later as invalid_json.- if out.len() != size {- return Err(bad("lz4 decoded length does not match the size prefix"));- }- return Ok(out);+ return crate::compression::unlz4_block(&raw).map_err(bad);}if raw.starts_with(GZIP_MAGIC) {- return crate::gzip::gunzip(&raw).map_err(|e| bad(&format!("gzip decompress failed: {e}")));+ return crate::compression::gunzip(&raw)+ .map_err(|e| bad(e.context("gzip decompress failed")));}Ok(raw)}@@ -226,6 +223,15 @@ pub fn anonymize_kafka_payload_opts(payload: &mut [u8],opts: AnonymizeOpts,first_party_hosts: Vec<String>,+) -> SResult<AnonymizedMessage> {+ contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts, first_party_hosts))+}++fn anonymize_kafka_payload_opts_impl(+ allow: &AllowLists,+ payload: &mut [u8],+ opts: AnonymizeOpts,+ first_party_hosts: Vec<String>,) -> SResult<AnonymizedMessage> {if let Some((distinct_id_span, data_span)) = scan_outer_envelope(payload) {// Resolve distinct_id to an owned string first — the unescape below rewrites the buffer.@@ -378,16 +384,18 @@ pub fn anonymize_snapshot_data_opts(opts: AnonymizeOpts,first_party_hosts: Vec<String>,) -> SResult<AnonymizedMessage> {- // No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines- // past its limit, and every recursive parse below is preceded by a span-local- // reject_if_too_deep — so the common all-walked path never pays a depth scan at all.- let ctx = Ctx::with_first_party_hosts(allow, first_party_hosts);- match stream_message(&ctx, distinct_id, inner, opts)? {- Some(msg) => Ok(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),- }+ contain_panics(|| {+ // No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines+ // past its limit, and every recursive parse below is preceded by a span-local+ // reject_if_too_deep — so the common all-walked path never pays a depth scan at all.+ let ctx = Ctx::with_first_party_hosts(allow, first_party_hosts);+ match stream_message(&ctx, distinct_id, inner, opts)? {+ Some(msg) => Ok(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),+ }+ })}const MAX_FAIL_DETAIL: usize = 200;@@ -1285,8 +1293,10 @@ pub fn anonymize_via_tree(distinct_id: &str,inner: &[u8],) -> SResult<AnonymizedMessage> {- let mut buf = inner.to_vec();- anonymize_via_tree_mut(ctx, distinct_id, &mut buf)+ contain_panics(|| {+ let mut buf = inner.to_vec();+ anonymize_via_tree_mut(ctx, distinct_id, &mut buf)+ })}/// [`anonymize_via_tree`] parsing the buffer in place (it is consumed).diff --git a/rust/replay-anonymizer/src/typed.rs b/rust/replay-anonymizer/src/typed.rsnew file mode 100644index 000000000000..790bd9f510dc--- /dev/null+++ b/rust/replay-anonymizer/src/typed.rs@@ -0,0 +1,772 @@+//! Typed rrweb parse output for offline consumers (feature `typed-parse`).+//!+//! [`parse_scrubbed_event`] scrubs a JSONL line with the same routing as+//! [`crate::anonymize_line`], then hands back a typed [`Event`] — envelope, FullSnapshot DOM tree,+//! Mutation adds/removes/attributes/texts, interaction/input/scroll data — with every `cv`+//! payload (whole-event blobs and per-field Mutation compression, gzip or zstd) transparently+//! decompressed. Scrub-then-parse is one call by design: this module never hands back an AST the+//! scrub policy has not been applied to.+//!+//! This is additive and offline-only. Nothing on the scrubbing hot path+//! ([`crate::anonymize_message`], [`crate::snapshot`], [`crate::bytewalk`]) references this+//! module; without the `typed-parse` feature (the Node addon build) it is not even compiled.+//!+//! Payload shapes the renderer does not fold land in [`EventData::Other`] /+//! [`IncrementalData::Other`] as generic JSON, not cv-decompressed, in exactly the state the+//! production scrub policy leaves them: canvas, stylesheet, plugin, and custom payloads are+//! scrubbed by their routed scrubbers; event types and incremental sources the router has no rule+//! for (DomContentLoaded, Load, unknown/future values) pass through **untouched**, the same+//! pass-through the ingestion pipeline applies. "Scrubbed" here always means "production scrub+//! policy applied", not "every field redacted".++use std::collections::BTreeMap;++use anyhow::{bail, Context, Result};+use serde::{Deserialize, Deserializer, Serialize};+use simd_json::borrowed::Value;+use simd_json::StaticNode;++use crate::allow_lists::AllowLists;+use crate::context::Ctx;+use crate::event::{route_event, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META};+use crate::json::{+ as_f64, as_object_mut, as_small_uint, parse_untrusted, reject_if_too_deep, string_value,+};++/// rrweb `EventType` for the envelope's raw `type`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "u8", into = "u8")]+#[repr(u8)]+pub enum EventType {+ DomContentLoaded = 0,+ Load = 1,+ FullSnapshot = 2,+ IncrementalSnapshot = 3,+ Meta = 4,+ Custom = 5,+ Plugin = 6,+}++impl EventType {+ pub const fn from_u8(n: u8) -> Option<Self> {+ Some(match n {+ 0 => Self::DomContentLoaded,+ 1 => Self::Load,+ 2 => Self::FullSnapshot,+ 3 => Self::IncrementalSnapshot,+ 4 => Self::Meta,+ 5 => Self::Custom,+ 6 => Self::Plugin,+ _ => return None,+ })+ }+}++/// rrweb `IncrementalSource` for an IncrementalSnapshot's raw `source`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "u8", into = "u8")]+#[repr(u8)]+pub enum IncrementalSource {+ Mutation = 0,+ MouseMove = 1,+ MouseInteraction = 2,+ Scroll = 3,+ ViewportResize = 4,+ Input = 5,+ TouchMove = 6,+ MediaInteraction = 7,+ StyleSheetRule = 8,+ CanvasMutation = 9,+ Font = 10,+ Log = 11,+ Drag = 12,+ StyleDeclaration = 13,+ Selection = 14,+ AdoptedStyleSheet = 15,+ CustomElement = 16,+}++impl IncrementalSource {+ pub const fn from_u8(n: u8) -> Option<Self> {+ Some(match n {+ 0 => Self::Mutation,+ 1 => Self::MouseMove,+ 2 => Self::MouseInteraction,+ 3 => Self::Scroll,+ 4 => Self::ViewportResize,+ 5 => Self::Input,+ 6 => Self::TouchMove,+ 7 => Self::MediaInteraction,+ 8 => Self::StyleSheetRule,+ 9 => Self::CanvasMutation,+ 10 => Self::Font,+ 11 => Self::Log,+ 12 => Self::Drag,+ 13 => Self::StyleDeclaration,+ 14 => Self::Selection,+ 15 => Self::AdoptedStyleSheet,+ 16 => Self::CustomElement,+ _ => return None,+ })+ }+}++macro_rules! u8_enum_conversions {+ ($($ty:ty),+) => {$(+ impl TryFrom<u8> for $ty {+ type Error = String;+ fn try_from(n: u8) -> Result<Self, String> {+ Self::from_u8(n).ok_or_else(|| {+ format!(concat!("invalid ", stringify!($ty), " value: {}"), n)+ })+ }+ }+ impl From<$ty> for u8 {+ fn from(v: $ty) -> u8 {+ v as u8+ }+ }+ )+};+}++/// rrweb `MouseInteractions` for a MouseInteraction's `type`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "u8", into = "u8")]+#[repr(u8)]+pub enum MouseInteractionKind {+ MouseUp = 0,+ MouseDown = 1,+ Click = 2,+ ContextMenu = 3,+ DblClick = 4,+ Focus = 5,+ Blur = 6,+ TouchStart = 7,+ TouchMoveDeparted = 8,+ TouchEnd = 9,+ TouchCancel = 10,+}++impl MouseInteractionKind {+ pub const fn from_u8(n: u8) -> Option<Self> {+ Some(match n {+ 0 => Self::MouseUp,+ 1 => Self::MouseDown,+ 2 => Self::Click,+ 3 => Self::ContextMenu,+ 4 => Self::DblClick,+ 5 => Self::Focus,+ 6 => Self::Blur,+ 7 => Self::TouchStart,+ 8 => Self::TouchMoveDeparted,+ 9 => Self::TouchEnd,+ 10 => Self::TouchCancel,+ _ => return None,+ })+ }+}++/// rrweb `PointerTypes` for a MouseInteraction's optional `pointerType`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "u8", into = "u8")]+#[repr(u8)]+pub enum PointerType {+ Mouse = 0,+ Pen = 1,+ Touch = 2,+}++impl PointerType {+ pub const fn from_u8(n: u8) -> Option<Self> {+ Some(match n {+ 0 => Self::Mouse,+ 1 => Self::Pen,+ 2 => Self::Touch,+ _ => return None,+ })+ }+}++u8_enum_conversions!(+ EventType,+ IncrementalSource,+ MouseInteractionKind,+ PointerType+);++/// One typed, scrubbed rrweb event. `ty` is the raw envelope `type` (it can exceed the+/// [`EventType`] range for future rrweb versions — those carry [`EventData::Other`]).+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct Event {+ /// From the PostHog `["window_id", event]` tuple wrapping; `None` for a bare event line.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub window_id: Option<String>,+ #[serde(rename = "type")]+ pub ty: u8,+ /// Epoch milliseconds. rrweb allows fractional timestamps; they truncate here.+ pub timestamp: i64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub delay: Option<i64>,+ pub data: EventData,+}++impl Event {+ pub const fn event_type(&self) -> Option<EventType> {+ EventType::from_u8(self.ty)+ }+}++/// The typed payloads the offline renderer folds; everything else passes through as scrubbed+/// generic JSON in `Other`.+#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(untagged)]+pub enum EventData {+ FullSnapshot(FullSnapshotData),+ Incremental(IncrementalData),+ Meta(MetaData),+ Other(serde_json::Value),+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(untagged)]+pub enum IncrementalData {+ Mutation(MutationData),+ MouseInteraction(MouseInteractionData),+ Scroll(ScrollData),+ Input(InputData),+ Other(serde_json::Value),+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FullSnapshotData {+ pub node: SerializedNodeWithId,+ pub initial_offset: InitialOffset,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct InitialOffset {+ pub top: f64,+ pub left: f64,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SerializedNodeWithId {+ pub id: i64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub root_id: Option<i64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub is_shadow_host: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub is_shadow: Option<bool>,+ #[serde(flatten)]+ pub node: SerializedNode,+}++#[derive(Debug, Clone, PartialEq)]+pub enum SerializedNode {+ Document(DocumentNode),+ DocumentType(DocumentTypeNode),+ Element(ElementNode),+ Text(TextNode),+ Cdata(CdataNode),+ Comment(CommentNode),+}++/// rrweb serialized-node `type`, used only to dispatch [`SerializedNode`]'s (de)serialization.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "u8", into = "u8")]+#[repr(u8)]+enum NodeType {+ Document = 0,+ DocumentType = 1,+ Element = 2,+ Text = 3,+ Cdata = 4,+ Comment = 5,+}++impl NodeType {+ const fn from_u8(n: u8) -> Option<Self> {+ Some(match n {+ 0 => Self::Document,+ 1 => Self::DocumentType,+ 2 => Self::Element,+ 3 => Self::Text,+ 4 => Self::Cdata,+ 5 => Self::Comment,+ _ => return None,+ })+ }+}++u8_enum_conversions!(NodeType);++// Avoids serde's untagged-enum trial-and-error: dispatch on `type`.+#[derive(Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+struct NodeHelper {+ #[serde(rename = "type")]+ ty: NodeType,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ tag_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ attributes: Option<BTreeMap<String, AttrValue>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ child_nodes: Option<Vec<SerializedNodeWithId>>,+ #[serde(rename = "isSVG", default, skip_serializing_if = "Option::is_none")]+ is_svg: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ need_block: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ is_custom: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ text_content: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ is_style: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ public_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ system_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ compat_mode: Option<String>,+}++fn empty_helper(ty: NodeType) -> NodeHelper {+ NodeHelper {+ ty,+ tag_name: None,+ attributes: None,+ child_nodes: None,+ is_svg: None,+ need_block: None,+ is_custom: None,+ text_content: None,+ is_style: None,+ name: None,+ public_id: None,+ system_id: None,+ compat_mode: None,+ }+}++impl<'de> Deserialize<'de> for SerializedNode {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let h = NodeHelper::deserialize(d)?;+ Ok(match h.ty {+ NodeType::Document => SerializedNode::Document(DocumentNode {+ child_nodes: h.child_nodes.unwrap_or_default(),+ compat_mode: h.compat_mode,+ }),+ NodeType::DocumentType => SerializedNode::DocumentType(DocumentTypeNode {+ name: h.name.unwrap_or_default(),+ public_id: h.public_id.unwrap_or_default(),+ system_id: h.system_id.unwrap_or_default(),+ }),+ NodeType::Element => SerializedNode::Element(ElementNode {+ tag_name: h.tag_name.unwrap_or_default(),+ attributes: h.attributes.unwrap_or_default(),+ child_nodes: h.child_nodes.unwrap_or_default(),+ is_svg: h.is_svg,+ need_block: h.need_block,+ is_custom: h.is_custom,+ }),+ NodeType::Text => SerializedNode::Text(TextNode {+ text_content: h.text_content.unwrap_or_default(),+ is_style: h.is_style,+ }),+ NodeType::Cdata => SerializedNode::Cdata(CdataNode {+ text_content: h.text_content,+ }),+ NodeType::Comment => SerializedNode::Comment(CommentNode {+ text_content: h.text_content.unwrap_or_default(),+ }),+ })+ }+}++impl Serialize for SerializedNode {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ let h = match self {+ SerializedNode::Document(v) => NodeHelper {+ child_nodes: Some(v.child_nodes.clone()),+ compat_mode: v.compat_mode.clone(),+ ..empty_helper(NodeType::Document)+ },+ SerializedNode::DocumentType(v) => NodeHelper {+ name: Some(v.name.clone()),+ public_id: Some(v.public_id.clone()),+ system_id: Some(v.system_id.clone()),+ ..empty_helper(NodeType::DocumentType)+ },+ SerializedNode::Element(v) => NodeHelper {+ tag_name: Some(v.tag_name.clone()),+ attributes: Some(v.attributes.clone()),+ child_nodes: Some(v.child_nodes.clone()),+ is_svg: v.is_svg,+ need_block: v.need_block,+ is_custom: v.is_custom,+ ..empty_helper(NodeType::Element)+ },+ SerializedNode::Text(v) => NodeHelper {+ text_content: Some(v.text_content.clone()),+ is_style: v.is_style,+ ..empty_helper(NodeType::Text)+ },+ SerializedNode::Cdata(v) => NodeHelper {+ text_content: v.text_content.clone(),+ ..empty_helper(NodeType::Cdata)+ },+ SerializedNode::Comment(v) => NodeHelper {+ text_content: Some(v.text_content.clone()),+ ..empty_helper(NodeType::Comment)+ },+ };+ h.serialize(s)+ }+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DocumentNode {+ pub child_nodes: Vec<SerializedNodeWithId>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub compat_mode: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DocumentTypeNode {+ pub name: String,+ pub public_id: String,+ pub system_id: String,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ElementNode {+ pub tag_name: String,+ pub attributes: BTreeMap<String, AttrValue>,+ pub child_nodes: Vec<SerializedNodeWithId>,+ #[serde(rename = "isSVG", skip_serializing_if = "Option::is_none")]+ pub is_svg: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub need_block: Option<bool>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub is_custom: Option<bool>,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct TextNode {+ pub text_content: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub is_style: Option<bool>,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CdataNode {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub text_content: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CommentNode {+ pub text_content: String,+}++/// An rrweb attribute value: string, number, bool, `null`, an array, or the structured sentinels+/// rrweb uses (e.g. the `rr_captured_*` style objects). The variant set covers any JSON value so a+/// scrubber-accepted attribute can never make the whole event fail to parse — the scrub path treats+/// attribute values as generic JSON, so the typed model must be at least as permissive.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum AttrValue {+ Str(String),+ Num(f64),+ Bool(bool),+ Null,+ Arr(Vec<AttrValue>),+ Obj(BTreeMap<String, AttrValue>),+}++/// Deserialize a mutation sub-field that may be absent, `null`, or an array into a `Vec`. Both scrub+/// paths keep a `null` sub-field verbatim (`cv.rs` and `bytewalk::walk_cv_sub`), so `null` is valid,+/// expected data — not a reason to fail the typed parse. `#[serde(default)]` alone covers absent+/// keys but rejects an explicit `null`, so route through `Option` to fold both to an empty `Vec`.+fn null_tolerant_vec<'de, D, T>(d: D) -> Result<Vec<T>, D::Error>+where+ D: Deserializer<'de>,+ T: Deserialize<'de>,+{+ Ok(Option::<Vec<T>>::deserialize(d)?.unwrap_or_default())+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct MutationData {+ pub source: IncrementalSource, // == Mutation (0)+ #[serde(default, deserialize_with = "null_tolerant_vec")]+ pub texts: Vec<TextMutation>,+ #[serde(default, deserialize_with = "null_tolerant_vec")]+ pub attributes: Vec<AttributeMutation>,+ #[serde(default, deserialize_with = "null_tolerant_vec")]+ pub removes: Vec<RemovedNodeMutation>,+ #[serde(default, deserialize_with = "null_tolerant_vec")]+ pub adds: Vec<AddedNodeMutation>,+ #[serde(+ default,+ rename = "isAttachIframe",+ skip_serializing_if = "Option::is_none"+ )]+ pub is_attach_iframe: Option<bool>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct TextMutation {+ pub id: i64,+ pub value: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct AttributeMutation {+ pub id: i64,+ pub attributes: BTreeMap<String, AttrValue>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RemovedNodeMutation {+ pub parent_id: i64,+ pub id: i64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub is_shadow: Option<bool>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct AddedNodeMutation {+ pub parent_id: i64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub previous_id: Option<i64>,+ pub next_id: Option<i64>,+ pub node: SerializedNodeWithId,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MouseInteractionData {+ pub source: IncrementalSource, // == MouseInteraction (2)+ #[serde(rename = "type")]+ pub kind: MouseInteractionKind,+ pub id: i64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub x: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub y: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pointer_type: Option<PointerType>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct ScrollData {+ pub source: IncrementalSource, // == Scroll (3)+ pub id: i64,+ pub x: f64,+ pub y: f64,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct InputData {+ pub source: IncrementalSource, // == Input (5)+ pub id: i64,+ pub text: String,+ pub is_checked: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub user_triggered: Option<bool>,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct MetaData {+ pub href: String,+ pub width: u32,+ pub height: u32,+}++/// Typed, scrubbed rrweb event from one JSONL line (bare event or `["window_id", event]` tuple).+/// Offline/non-hot-path only: this parse allocates an AST.+///+/// `Ok(None)` = an object with no numeric `type`/`timestamp`, i.e. not an rrweb event envelope+/// (nothing typed to hand back). `Err` = a wrong top-level shape (mirrors [`crate::anonymize_line`],+/// fail closed), a scrub failure, or a payload the typed model can't represent — an unknown enum+/// discriminant from a newer rrweb, say, which is the signal to extend this crate rather than+/// silently drop or mis-type the event. Fail closed: drop the line on `Err`.+pub fn parse_scrubbed_event(allow: &AllowLists, line: &mut [u8]) -> Result<Option<Event>> {+ parse_scrubbed_event_with_ctx(&Ctx::new(allow), line)+}++/// [`parse_scrubbed_event`] with a caller-owned [`Ctx`] — same memo/budget semantics as+/// [`crate::anonymize_line_with_ctx`].+pub fn parse_scrubbed_event_with_ctx(ctx: &Ctx<'_>, line: &mut [u8]) -> Result<Option<Event>> {+ crate::unwind::contain_unwind(+ || {+ reject_if_too_deep(line, "jsonl line")?;+ let root = parse_untrusted(line).context("parse jsonl line")?;+ ctx.reset_cv_budget();+ let (window_id, mut event) = match root {+ event @ Value::Object(_) => (None, event),+ Value::Array(items) => {+ let mut it = items.into_iter();+ match (it.next(), it.next(), it.next()) {+ (Some(Value::String(id)), Some(event @ Value::Object(_)), None) => {+ (Some(id.into_owned()), event)+ }+ _ => bail!("jsonl line is an array but not a [window_id, event] tuple"),+ }+ }+ _ => bail!(+ "jsonl line is neither an rrweb event object nor a [window_id, event] tuple"+ ),+ };+ route_event(ctx, &mut event)?;+ build_typed(ctx, window_id, event)+ },+ |msg| anyhow::anyhow!("panic while parsing scrubbed event: {msg}"),+ )+}++fn build_typed(+ ctx: &Ctx<'_>,+ window_id: Option<String>,+ mut event: Value<'_>,+) -> Result<Option<Event>> {+ let obj = as_object_mut(&mut event).expect("caller matched an object");+ let Some(ty) = obj.get("type").and_then(as_small_uint) else {+ return Ok(None);+ };+ let Some(timestamp) = obj.get("timestamp").and_then(as_f64) else {+ return Ok(None);+ };+ let delay = obj.get("delay").and_then(as_f64).map(|d| d as i64);+ let compressed = crate::event::is_compressed_marker(obj.get("cv"));+ let mut data = obj+ .remove("data")+ .unwrap_or(Value::Static(StaticNode::Null));++ let source = crate::json::as_object(&data)+ .and_then(|d| d.get("source"))+ .and_then(as_small_uint);++ if compressed {+ decompress_cv_fields(ctx, ty, source, &mut data)?;+ }++ let typed = match ty {+ TYPE_FULL_SNAPSHOT if crate::json::is_object(&data) => {+ EventData::FullSnapshot(from_value(data).context("typed FullSnapshot data")?)+ }+ TYPE_INCREMENTAL => EventData::Incremental(match source.map(IncrementalSource::from_u8) {+ Some(Some(IncrementalSource::Mutation)) => {+ IncrementalData::Mutation(from_value(data).context("typed Mutation data")?)+ }+ Some(Some(IncrementalSource::MouseInteraction)) => IncrementalData::MouseInteraction(+ from_value(data).context("typed MouseInteraction data")?,+ ),+ Some(Some(IncrementalSource::Scroll)) => {+ IncrementalData::Scroll(from_value(data).context("typed Scroll data")?)+ }+ Some(Some(IncrementalSource::Input)) => {+ IncrementalData::Input(from_value(data).context("typed Input data")?)+ }+ _ => IncrementalData::Other(from_value(data).context("generic incremental data")?),+ }),+ TYPE_META if crate::json::is_object(&data) => {+ EventData::Meta(from_value(data).context("typed Meta data")?)+ }+ _ => EventData::Other(from_value(data).context("generic event data")?),+ };++ Ok(Some(Event {+ window_id,+ ty,+ timestamp: timestamp as i64,+ delay,+ data: typed,+ }))+}++/// Replace compressed `cv` payloads inside `data` with their decoded JSON, so the typed output is+/// transparently decompressed: the whole-blob FullSnapshot string, and each present Mutation+/// sub-field string (`texts`/`attributes`/`removes`/`adds` — `removes` is never re-emitted by the+/// scrub, so it can still be gzip while its siblings are zstd; the magic sniff handles both).+fn decompress_cv_fields(+ ctx: &Ctx<'_>,+ ty: u8,+ source: Option<u8>,+ data: &mut Value<'_>,+) -> Result<()> {+ match (ty, source, &mut *data) {+ (TYPE_FULL_SNAPSHOT, _, Value::String(s)) => {+ *data = decode_cv_string(ctx, s).context("decompress cv FullSnapshot data")?;+ }+ (TYPE_INCREMENTAL, Some(SOURCE_MUTATION), Value::Object(obj)) => {+ for sub_key in ["texts", "attributes", "removes", "adds"] {+ let Some(Value::String(s)) = obj.get(sub_key) else {+ continue;+ };+ if s.is_empty() {+ obj.insert(+ crate::json::key(sub_key),+ Value::Array(Box::new(Vec::new())),+ );+ continue;+ }+ let decoded = decode_cv_string(ctx, s)+ .with_context(|| format!("decompress cv mutation sub-field `{sub_key}`"))?;+ obj.insert(crate::json::key(sub_key), decoded);+ }+ }+ _ => {}+ }+ Ok(())+}++fn decode_cv_string(ctx: &Ctx<'_>, s: &str) -> Result<Value<'static>> {+ let raw = crate::cv::latin1_to_bytes(s)?;+ let mut decompressed = ctx.decompress_cv(&raw)?;+ reject_if_too_deep(&decompressed, "cv payload")?;+ // Round-trip through owned JSON: the decompressed scratch buffer dies at return, so the+ // borrowed parse cannot escape this function.+ let parsed = parse_untrusted(&mut decompressed).context("parse cv payload")?;+ Ok(string_to_owned_value(parsed))+}++/// Rebuild a borrowed simd-json value as `'static` (owning every string).+fn string_to_owned_value(v: Value<'_>) -> Value<'static> {+ match v {+ Value::Static(s) => Value::Static(s),+ Value::String(s) => string_value(s.into_owned()),+ Value::Array(items) => Value::Array(Box::new(+ items.into_iter().map(string_to_owned_value).collect(),+ )),+ Value::Object(obj) => {+ let mut out = simd_json::borrowed::Object::with_capacity(obj.len());+ for (k, val) in obj.into_iter() {+ out.insert(+ std::borrow::Cow::Owned(k.into_owned()),+ string_to_owned_value(val),+ );+ }+ Value::Object(Box::new(out))+ }+ }+}++fn from_value<T: serde::de::DeserializeOwned>(value: Value<'_>) -> Result<T> {+ simd_json::serde::from_borrowed_value(value).map_err(anyhow::Error::from)+}diff --git a/rust/replay-anonymizer/src/unwind.rs b/rust/replay-anonymizer/src/unwind.rsnew file mode 100644index 000000000000..8e969e50f42b--- /dev/null+++ b/rust/replay-anonymizer/src/unwind.rs@@ -0,0 +1,61 @@+//! Boundary backstop: convert a panic on untrusted input into an error at the public entry+//! points, so callers are fail-closed by construction instead of by a documented `catch_unwind`+//! obligation. Internal code stays panic-free-by-intent — this is the last line of defense, not a+//! license to panic. Under `panic = "abort"` the backstop cannot run (the process dies before+//! `catch_unwind` sees anything); builds that must fail closed need `panic = "unwind"`, which the+//! Node addon enforces at compile time.++use std::panic::{catch_unwind, AssertUnwindSafe};++/// Run `f`, converting an unwind into `err(message)`.+///+/// `AssertUnwindSafe` is sound at these boundaries because the fail-closed contract already+/// requires callers to discard whatever `f` mutated (buffers, parsed trees) whenever an error+/// comes back — a half-scrubbed value can never be observed on the `Err` path.+pub(crate) fn contain_unwind<T, E>(+ f: impl FnOnce() -> Result<T, E>,+ err: impl FnOnce(String) -> E,+) -> Result<T, E> {+ catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|panic| Err(err(panic_message(&*panic))))+}++/// Cap on the panic text carried into an error. Standard slice/`expect` panics interpolate a chunk+/// of the offending value (`byte index N is not a char boundary ... of \`<raw input>\``), so the+/// message can embed unscrubbed input. The ingestion path drops the message entirely (see+/// `snapshot::contain_panics`); the offline `anyhow` entry points keep it for diagnosis but bound+/// it here so a pathological payload can't splice an unbounded slice of itself into the error.+const MAX_PANIC_MESSAGE_LEN: usize = 200;++fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {+ let raw = if let Some(s) = panic.downcast_ref::<&str>() {+ *s+ } else if let Some(s) = panic.downcast_ref::<String>() {+ s.as_str()+ } else {+ "non-string panic payload"+ };+ match raw.char_indices().nth(MAX_PANIC_MESSAGE_LEN) {+ Some((cut, _)) => format!("{}…", &raw[..cut]),+ None => raw.to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn panics_become_errors_and_results_pass_through() {+ let caught = contain_unwind(+ || -> Result<(), String> { panic!("boom {}", 42) },+ |msg| format!("panic while anonymizing: {msg}"),+ );+ assert_eq!(caught.unwrap_err(), "panic while anonymizing: boom 42");++ assert_eq!(contain_unwind(|| Ok::<_, String>(7), |m| m).unwrap(), 7);+ assert_eq!(+ contain_unwind(|| Err::<(), _>("plain error".to_string()), |m| m).unwrap_err(),+ "plain error"+ );+ }+}diff --git a/rust/replay-anonymizer/tests/typed.rs b/rust/replay-anonymizer/tests/typed.rsnew file mode 100644index 000000000000..008deb156831--- /dev/null+++ b/rust/replay-anonymizer/tests/typed.rs@@ -0,0 +1,341 @@+//! Typed-parse (`typed-parse` feature) contract tests: scrub-then-parse returns a typed rrweb+//! AST that is already scrubbed and transparently cv-decompressed. The scrubbing hot path is+//! pinned elsewhere (parity + differential suites); nothing here touches it — the typed module+//! is not even compiled into the addon build (`default-features = false`).+#![cfg(feature = "typed-parse")]++use std::io::Write;+use std::path::Path;++use posthog_replay_anonymizer::typed::{+ AttrValue, Event, EventData, EventType, IncrementalData, SerializedNode,+};+use posthog_replay_anonymizer::{anonymize_line, parse_scrubbed_event, AllowLists};+use serde_json::json;++fn latin1(bytes: &[u8]) -> String {+ bytes.iter().map(|&b| b as char).collect()+}++// The SDK wire format for cv payloads: gzip stored as latin-1 codepoints.+fn gzip_latin1(json: &[u8]) -> String {+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ enc.write_all(json).unwrap();+ latin1(&enc.finish().unwrap())+}++fn parse(allow: &AllowLists, line: &str) -> Option<Event> {+ let mut bytes = line.as_bytes().to_vec();+ parse_scrubbed_event(allow, &mut bytes).unwrap()+}++fn allow_hello() -> AllowLists {+ AllowLists::new(["hello"], Vec::<String>::new())+}++fn full_snapshot_data() -> serde_json::Value {+ json!({+ "node": { "type": 0, "id": 1, "childNodes": [+ { "type": 2, "id": 2, "tagName": "html", "attributes": {}, "childNodes": [+ { "type": 2, "id": 3, "tagName": "body", "attributes": { "class": "main" }, "childNodes": [+ { "type": 3, "id": 4, "textContent": "hello John Fakename" }+ ]}+ ]}+ ]},+ "initialOffset": { "top": 1.0, "left": 2.0 }+ })+}++#[test]+fn full_snapshot_parses_to_a_scrubbed_typed_tree() {+ let allow = allow_hello();+ let line = json!({ "type": 2, "timestamp": 1700000000000i64, "data": full_snapshot_data() })+ .to_string();+ let event = parse(&allow, &line).expect("a full snapshot is recognizable");++ assert_eq!(event.event_type(), Some(EventType::FullSnapshot));+ assert_eq!(event.timestamp, 1700000000000);+ let EventData::FullSnapshot(snap) = &event.data else {+ panic!("expected FullSnapshot data, got {:?}", event.data);+ };+ assert_eq!(snap.initial_offset.top, 1.0);+ assert_eq!(snap.node.id, 1);++ let SerializedNode::Document(doc) = &snap.node.node else {+ panic!("root must be a Document");+ };+ let html = &doc.child_nodes[0];+ let SerializedNode::Element(html_el) = &html.node else {+ panic!("expected the html element");+ };+ assert_eq!((html.id, html_el.tag_name.as_str()), (2, "html"));++ let body = &html_el.child_nodes[0];+ let SerializedNode::Element(body_el) = &body.node else {+ panic!("expected the body element");+ };+ assert_eq!(body_el.tag_name, "body");+ assert_eq!(+ body_el.attributes.get("class"),+ Some(&AttrValue::Str("main".to_string()))+ );++ let SerializedNode::Text(text) = &body_el.child_nodes[0].node else {+ panic!("expected the text node");+ };+ // The typed tree is already scrubbed: no way to reach an unscrubbed AST.+ assert_eq!(text.text_content, "hello **** ********");+}++#[test]+fn mutation_parses_to_scrubbed_typed_subfields() {+ let allow = allow_hello();+ let rr_src = "https://cdn.fake.test/avatars/john.fakename.png";+ let line = json!({ "type": 3, "timestamp": 1.0, "data": {+ "source": 0,+ "texts": [{ "id": 5, "value": "hello secret" }],+ "attributes": [{ "id": 6, "attributes": { "rr_src": rr_src } }],+ "removes": [{ "parentId": 7, "id": 8 }],+ "adds": [{ "parentId": 9, "nextId": null,+ "node": { "type": 3, "id": 10, "textContent": "hello secret" } }],+ }})+ .to_string();+ let event = parse(&allow, &line).unwrap();++ let EventData::Incremental(IncrementalData::Mutation(m)) = &event.data else {+ panic!("expected Mutation data, got {:?}", event.data);+ };+ assert_eq!(+ (m.texts[0].id, m.texts[0].value.as_deref()),+ (5, Some("hello ******"))+ );++ assert_eq!(m.attributes[0].id, 6);+ let AttrValue::Str(scrubbed_src) = &m.attributes[0].attributes["rr_src"] else {+ panic!("rr_src must stay a string");+ };+ assert_ne!(+ scrubbed_src, rr_src,+ "the rr_src URL must be scrubbed (#68858)"+ );+ assert!(!scrubbed_src.contains("john"), "got: {scrubbed_src}");++ assert_eq!((m.removes[0].parent_id, m.removes[0].id), (7, 8));++ assert_eq!((m.adds[0].parent_id, m.adds[0].next_id), (9, None));+ let SerializedNode::Text(added) = &m.adds[0].node.node else {+ panic!("expected the added text node");+ };+ assert_eq!(added.text_content, "hello ******");+}++#[test]+fn array_valued_attribute_parses_instead_of_dropping_the_event() {+ // An attribute whose value is an array is valid JSON the scrub path passes through untouched, so+ // the typed model must represent it (as AttrValue::Arr) rather than failing `from_value` and+ // dropping the whole event line.+ let allow = allow_hello();+ let line = json!({ "type": 2, "timestamp": 1.0, "data": {+ "node": { "type": 0, "id": 1, "childNodes": [+ { "type": 2, "id": 2, "tagName": "div",+ "attributes": { "rr_width": [100, "auto"] }, "childNodes": [] }+ ]},+ "initialOffset": { "top": 0.0, "left": 0.0 }+ }})+ .to_string();+ let event = parse(&allow, &line).expect("an array-valued attribute must not drop the event");++ let EventData::FullSnapshot(snap) = &event.data else {+ panic!("expected FullSnapshot data, got {:?}", event.data);+ };+ let SerializedNode::Document(doc) = &snap.node.node else {+ panic!("root must be a Document");+ };+ let SerializedNode::Element(div) = &doc.child_nodes[0].node else {+ panic!("expected the div element");+ };+ assert_eq!(+ div.attributes["rr_width"],+ AttrValue::Arr(vec![+ AttrValue::Num(100.0),+ AttrValue::Str("auto".to_string())+ ])+ );+}++#[test]+fn cv_full_snapshot_parses_like_its_uncompressed_twin_gzip_and_zstd() {+ let allow = allow_hello();+ let data = full_snapshot_data();++ let plain = json!({ "type": 2, "timestamp": 1.0, "data": data }).to_string();+ let gzip = json!({ "type": 2, "timestamp": 1.0, "cv": "2024-10",+ "data": gzip_latin1(data.to_string().as_bytes()) })+ .to_string();+ // The anonymizer re-emits changed cv payloads as zstd — its output IS the zstd twin.+ let zstd = anonymize_line(&allow, &mut gzip.clone().into_bytes())+ .unwrap()+ .expect("the scrub rewrites the cv payload");++ let expected = parse(&allow, &plain).unwrap();+ assert_eq!(+ parse(&allow, &gzip).unwrap(),+ expected,+ "gzip cv twin diverged"+ );+ assert_eq!(+ parse(&allow, &zstd).unwrap(),+ expected,+ "zstd cv twin diverged"+ );+}++#[test]+fn cv_mutation_subfields_parse_like_their_uncompressed_twins_gzip_and_zstd() {+ let allow = allow_hello();+ let texts = json!([{ "id": 5, "value": "hello secret" }]);+ let removes = json!([{ "parentId": 7, "id": 8 }]);++ let plain = json!({ "type": 3, "timestamp": 1.0,+ "data": { "source": 0, "texts": texts, "removes": removes } })+ .to_string();+ let gzip = json!({ "type": 3, "timestamp": 1.0, "cv": "2024-10", "data": {+ "source": 0,+ "texts": gzip_latin1(texts.to_string().as_bytes()),+ "removes": gzip_latin1(removes.to_string().as_bytes()),+ }})+ .to_string();+ // Re-emitted sub-fields become zstd; `removes` is not scrub-routed and stays gzip, so this+ // twin also covers mixed-format payloads.+ let zstd = anonymize_line(&allow, &mut gzip.clone().into_bytes())+ .unwrap()+ .expect("the scrub rewrites the texts sub-field");++ let expected = parse(&allow, &plain).unwrap();+ assert_eq!(+ parse(&allow, &gzip).unwrap(),+ expected,+ "gzip cv twin diverged"+ );+ assert_eq!(+ parse(&allow, &zstd).unwrap(),+ expected,+ "zstd cv twin diverged"+ );+}++#[test]+fn tuple_lines_carry_the_window_id_and_bare_lines_do_not() {+ let allow = allow_hello();+ let event_json = json!({ "type": 3, "timestamp": 2.5,+ "data": { "source": 3, "id": 4, "x": 1.0, "y": 2.0 } });++ let tuple = parse(&allow, &json!(["w-1", event_json]).to_string()).unwrap();+ assert_eq!(tuple.window_id.as_deref(), Some("w-1"));+ assert_eq!(tuple.event_type(), Some(EventType::IncrementalSnapshot));+ assert_eq!(tuple.timestamp, 2, "fractional timestamps truncate");+ let EventData::Incremental(IncrementalData::Scroll(scroll)) = &tuple.data else {+ panic!("expected Scroll data, got {:?}", tuple.data);+ };+ assert_eq!((scroll.id, scroll.x, scroll.y), (4, 1.0, 2.0));++ let bare = parse(&allow, &event_json.to_string()).unwrap();+ assert_eq!(bare.window_id, None);+ assert_eq!(bare.data, tuple.data);++ // A wrong top-level shape fails closed (same policy as `anonymize_line`); an object with no+ // event envelope (missing type/timestamp) has nothing typed to return, so it is `Ok(None)`.+ let mut wrong_shape = br#"["w-1","not an event"]"#.to_vec();+ assert!(parse_scrubbed_event(&allow, &mut wrong_shape).is_err());+ assert!(+ parse(&allow, r#"{"type":2}"#).is_none(),+ "missing timestamp"+ );+}++#[test]+fn mutation_with_null_subfields_parses_as_empty() {+ // Both scrub paths keep a `null` mutation sub-field verbatim, so it is valid data the typed+ // parse must accept (as empty), not fail on.+ let allow = allow_hello();+ let line = json!({ "type": 3, "timestamp": 1.0, "data": {+ "source": 0,+ "texts": null,+ "attributes": null,+ "removes": null,+ "adds": null,+ }})+ .to_string();+ let event = parse(&allow, &line).unwrap();+ let EventData::Incremental(IncrementalData::Mutation(m)) = &event.data else {+ panic!("expected Mutation data, got {:?}", event.data);+ };+ assert!(+ m.texts.is_empty() && m.attributes.is_empty() && m.removes.is_empty() && m.adds.is_empty()+ );+}++#[test]+fn unknown_enum_discriminant_is_a_loud_error() {+ // A MouseInteraction kind newer than this crate knows must surface as `Err` (extend the crate),+ // not silently downgrade or mis-type. `source: 2` routes to the typed MouseInteraction model.+ let allow = allow_hello();+ let mut line = json!({ "type": 3, "timestamp": 1.0,+ "data": { "source": 2, "type": 99, "id": 4 } })+ .to_string()+ .into_bytes();+ assert!(parse_scrubbed_event(&allow, &mut line).is_err());+}++#[test]+fn unmodeled_types_and_sources_pass_through_as_scrubbed_generic_json() {+ let allow = allow_hello();++ // Unknown incremental source (selection, 14) stays generic.+ let line = json!({ "type": 3, "timestamp": 1.0,+ "data": { "source": 14, "ranges": [] } })+ .to_string();+ let event = parse(&allow, &line).unwrap();+ let EventData::Incremental(IncrementalData::Other(v)) = &event.data else {+ panic!("expected Other incremental data, got {:?}", event.data);+ };+ assert_eq!(v["source"], 14);++ // Custom event (type 5) payload is generic but still scrubbed.+ let line = json!({ "type": 5, "timestamp": 1.0,+ "data": { "tag": "note", "payload": "hello secret" } })+ .to_string();+ let event = parse(&allow, &line).unwrap();+ assert_eq!(event.event_type(), Some(EventType::Custom));+ let EventData::Other(v) = &event.data else {+ panic!("expected Other event data, got {:?}", event.data);+ };+ assert_eq!(v["payload"], "hello ******");+}++/// Every shared scrub fixture must round-trip the typed parse without an error — the typed+/// surface may downgrade an event to `Other`, but it must never fail on payloads the scrubbers+/// accept.+#[test]+fn every_shared_event_fixture_parses() {+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/events.json");+ let cases: Vec<serde_json::Value> =+ serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();+ assert!(!cases.is_empty());+ for case in &cases {+ let strings = |key: &str| -> Vec<String> {+ case["allow"][key]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(String::from))+ .collect()+ })+ .unwrap_or_default()+ };+ let allow = AllowLists::new(strings("text"), strings("url"));+ let mut line = serde_json::to_vec(&case["event"]).unwrap();+ parse_scrubbed_event(&allow, &mut line)+ .unwrap_or_else(|e| panic!("fixture {} failed the typed parse: {e:#}", case["name"]));+ }+}