Skip to main content

relay_replays/
recording.rs

1//! Replay recordings payload and processor.
2//!
3//! # Data Scrubbing
4//!
5//! Since recordings contain snapshot of the browser's DOM, network traffic, and console logs, they
6//! are likely to contain sensitive data. This module provides [`RecordingScrubber`], which applies
7//! data scrubbing on the payload of recordings while leaving their structure and required fields
8//! intact.
9//!
10//! Data scrubbing applies to only Sentry event payloads within the recording event stream,
11//! identified by `type: 5`. The scrubber skips all other node types and does not perform any
12//! validation beyond JSON parsing.
13
14use std::cell::RefCell;
15use std::fmt;
16use std::io::{self, Read, Write};
17use std::rc::Rc;
18use std::{borrow::Cow, sync::LazyLock};
19
20use flate2::Compression;
21use flate2::bufread::ZlibDecoder;
22use flate2::write::ZlibEncoder;
23use relay_event_schema::processor::{FieldAttrs, Pii, ProcessingState, Processor, ValueType};
24use relay_pii::{PiiConfig, PiiProcessor};
25use relay_protocol::Meta;
26use serde::{Deserializer, de, ser};
27use serde_json::value::RawValue;
28
29use relay_pii::transform::Transform;
30
31/// Paths to fields on which datascrubbing rules should be applied.
32///
33/// This is equivalent to marking a field as `pii = true` in an `Annotated` schema.
34static PII_FIELDS: LazyLock<[Vec<&str>; 2]> = LazyLock::new(|| {
35    [
36        vec!["data", "payload", "description"],
37        vec!["data", "payload", "data"],
38    ]
39});
40
41/// Returns `True` if the given path should be treated as `pii = true`.
42fn scrub_at_path(path: &Vec<String>) -> bool {
43    PII_FIELDS.iter().any(|pii_path| {
44        path.len() >= pii_path.len() && pii_path.iter().zip(path).all(|(k1, k2)| k1 == k2)
45    })
46}
47
48/// Static field attributes used for fields in [`PII_FIELDS`].
49const FIELD_ATTRS_PII_TRUE: FieldAttrs = FieldAttrs::new().pii(Pii::True);
50
51/// Static field attributes used for fields without PII scrubbing.
52const FIELD_ATTRS_PII_FALSE: FieldAttrs = FieldAttrs::new().pii(Pii::False);
53
54/// Error returned from [`RecordingScrubber`].
55#[derive(Debug)]
56pub enum ParseRecordingError {
57    /// An error parsing the JSON payload.
58    Parse(serde_json::Error),
59    /// Invalid or broken compression.
60    Compression(std::io::Error),
61    /// The payload exceeds the size limit after decompression.
62    TooLarge,
63    /// Validation of the payload failed.
64    ///
65    /// The body is empty, is missing the headers, or the body.
66    Message(&'static str),
67}
68
69impl fmt::Display for ParseRecordingError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            ParseRecordingError::Parse(serde_error) => write!(f, "{serde_error}"),
73            ParseRecordingError::Compression(error) => write!(f, "{error}"),
74            ParseRecordingError::TooLarge => write!(f, "payload too large after decompression"),
75            ParseRecordingError::Message(message) => write!(f, "{message}"),
76        }
77    }
78}
79
80impl std::error::Error for ParseRecordingError {
81    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
82        match self {
83            ParseRecordingError::Parse(e) => Some(e),
84            ParseRecordingError::Compression(e) => Some(e),
85            ParseRecordingError::TooLarge | ParseRecordingError::Message(_) => None,
86        }
87    }
88}
89
90impl From<serde_json::Error> for ParseRecordingError {
91    fn from(err: serde_json::Error) -> Self {
92        ParseRecordingError::Parse(err)
93    }
94}
95
96/// The [`Transform`] implementation for data scrubbing.
97///
98/// This is used by [`EventStreamVisitor`] and [`ScrubbedValue`] to scrub recording events.
99struct ScrubberTransform<'a> {
100    /// PII processors that are applied one by one on each value.
101    processor1: Option<PiiProcessor<'a>>,
102    processor2: Option<PiiProcessor<'a>>,
103    /// The state encoding the current path, which is fed by `push_path` and `pop_path`.
104    state: ProcessingState<'a>,
105    /// The current path. This is redundant with `state`, which also contains the full path,
106    /// but easier to match on.
107    path: Vec<String>,
108}
109
110impl ScrubberTransform<'_> {
111    fn ensure_empty(&mut self) {
112        if !self.path.is_empty() || self.state.depth() > 0 {
113            debug_assert!(false, "ScrubberTransform not empty");
114            relay_log::error!("ScrubberTransform not empty");
115        }
116        self.state = ProcessingState::new_root(None, None);
117        self.path.clear();
118    }
119}
120
121impl<'de> Transform<'de> for &'_ mut ScrubberTransform<'_> {
122    fn push_path(&mut self, key: &str) {
123        self.path.push(key.to_owned());
124        let field_attrs = if scrub_at_path(&self.path) {
125            &FIELD_ATTRS_PII_TRUE
126        } else {
127            &FIELD_ATTRS_PII_FALSE
128        };
129
130        self.state = std::mem::take(&mut self.state).enter_owned(
131            key.to_owned(),
132            Some(Cow::Borrowed(field_attrs)),
133            Some(ValueType::String), // Pretend everything is a string.
134        )
135    }
136
137    fn pop_path(&mut self) {
138        if let Ok(Some(parent)) = std::mem::take(&mut self.state).try_into_parent() {
139            self.state = parent;
140        }
141        let popped = self.path.pop();
142        debug_assert!(popped.is_some()); // pop_path should never be called on an empty state.
143    }
144
145    fn transform_str<'a>(&mut self, v: &'a str) -> Cow<'a, str> {
146        self.transform_string(v.to_owned())
147    }
148
149    fn transform_string(&mut self, mut value: String) -> Cow<'static, str> {
150        if let Some(ref mut processor) = self.processor1
151            && processor
152                .process_string(&mut value, &mut Meta::default(), &self.state)
153                .is_err()
154        {
155            return Cow::Borrowed("");
156        }
157
158        if let Some(ref mut processor) = self.processor2
159            && processor
160                .process_string(&mut value, &mut Meta::default(), &self.state)
161                .is_err()
162        {
163            return Cow::Borrowed("");
164        }
165
166        Cow::Owned(value)
167    }
168}
169
170/// Helper that runs data scrubbing on a raw JSON value during serialization.
171///
172/// This is used by [`EventStreamVisitor`] to serialize recording events on-the-fly from a stream.
173/// It uses a [`ScrubberTransform`] holding all state to perform the actual work.
174struct ScrubbedValue<'a, 'b>(&'a RawValue, Rc<RefCell<ScrubberTransform<'b>>>);
175
176impl serde::Serialize for ScrubbedValue<'_, '_> {
177    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
178    where
179        S: serde::Serializer,
180    {
181        let mut transform = self.1.borrow_mut();
182        let mut deserializer = serde_json::Deserializer::from_str(self.0.get());
183        let scrubber = relay_pii::transform::Deserializer::new(&mut deserializer, &mut *transform);
184        serde_transcode::transcode(scrubber, serializer)
185    }
186}
187
188/// A visitor that deserializes, scrubs, and serializes a stream of recording events.
189struct EventStreamVisitor<'a, S> {
190    serializer: S,
191    scrubber: Rc<RefCell<ScrubberTransform<'a>>>,
192}
193
194impl<'a, S> EventStreamVisitor<'a, S> {
195    /// The proprietary rrweb node type that identifies Sentry payloads.
196    ///
197    /// The visitor exclusively scrubs these nodes.
198    const SENTRY_EVENT_TYPE: u8 = 5;
199
200    /// Creates a new visitor wrapping a `serializer`.
201    fn new(serializer: S, scrubber: Rc<RefCell<ScrubberTransform<'a>>>) -> Self {
202        Self {
203            serializer,
204            scrubber,
205        }
206    }
207}
208
209impl<'de, S> de::Visitor<'de> for EventStreamVisitor<'_, S>
210where
211    S: ser::Serializer,
212{
213    type Value = S::Ok;
214
215    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
216        write!(formatter, "a replay recording event stream")
217    }
218
219    fn visit_seq<A>(self, mut v: A) -> Result<Self::Value, A::Error>
220    where
221        A: de::SeqAccess<'de>,
222    {
223        /// Efficiently deserializes the type discriminator of event nodes.
224        #[derive(Clone, Copy, serde::Deserialize)]
225        struct TypeHelper {
226            #[serde(rename = "type")]
227            ty: u8,
228        }
229
230        use serde::ser::SerializeSeq;
231        let mut seq = self.serializer.serialize_seq(v.size_hint()).map_err(s2d)?;
232
233        // NOTE on performance: This loop parses every element 2-3 times:
234        //  1. In the call to next_element() to obtain the raw value. This pass is highly efficient
235        //     and cannot be removed.
236        //  2. Deserializing `TypeHelper` to obtain the node type. It skips most of the content, but
237        //     does require a full pass through the raw value.
238        //  3. If scrubbing is required, `ScrubbedValue` internally parses the value and runs it
239        //     through a transforming deserializer.
240        //
241        // These redundant passes come with slight performance overhead compared to an
242        // implementation that directly parses the `type` and raw `data` into a structure. Together
243        // with decompression and data scrubbing, the difference in benchmarks was small. In case
244        // this becomes a performance bottleneck, it is worth to first focus on data scrubbing, and
245        // then at the redundant parsing.
246
247        while let Some(raw) = v.next_element::<&'de RawValue>()? {
248            let helper = serde_json::from_str::<TypeHelper>(raw.get()).map_err(s2d)?;
249            // Scrub only sentry-specific events and serialize all others without modification.
250            if helper.ty == Self::SENTRY_EVENT_TYPE {
251                seq.serialize_element(&ScrubbedValue(raw, self.scrubber.clone()))
252                    .map_err(s2d)?;
253                // `pop_path` calls should have reset the scrubber's state, but force a
254                // reset here just to be sure:
255                self.scrubber.borrow_mut().ensure_empty();
256            } else {
257                seq.serialize_element(raw).map_err(s2d)?;
258            }
259        }
260
261        seq.end().map_err(s2d)
262    }
263}
264
265/// Maps a serialization error to a deserialization error.
266fn s2d<S, D>(s: S) -> D
267where
268    S: ser::Error,
269    D: de::Error,
270{
271    D::custom(s.to_string())
272}
273
274/// Splits a recording payload into its header line and body.
275fn split_recording(bytes: &[u8]) -> Result<(&[u8], &[u8]), ParseRecordingError> {
276    if bytes.is_empty() {
277        return Err(ParseRecordingError::Message("no data found"));
278    }
279
280    let mut split = bytes.splitn(2, |b| b == &b'\n');
281    let header = split
282        .next()
283        .ok_or(ParseRecordingError::Message("no headers found"))?;
284
285    match split.next() {
286        Some(b"") | None => Err(ParseRecordingError::Message("no body found")),
287        Some(body) => Ok((header, body)),
288    }
289}
290
291/// Inflates a zlib compressed recording body into `output`.
292///
293/// Reads at most one byte past `limit`, so oversized bodies are detected without inflating them
294/// fully.
295fn decompress(
296    body: &[u8],
297    limit: usize,
298    output: &mut impl Write,
299) -> Result<(), ParseRecordingError> {
300    let mut decoder = ZlibDecoder::new(body).take((limit as u64).saturating_add(1));
301    let size = io::copy(&mut decoder, output).map_err(ParseRecordingError::Compression)?;
302    if size > limit as u64 {
303        return Err(ParseRecordingError::TooLarge);
304    }
305    Ok(())
306}
307
308/// Checks that a recording payload does not exceed `limit` bytes after decompression.
309///
310/// This applies the same decompression and limit as [`RecordingScrubber::process_recording`],
311/// for recordings which are not scrubbed. Uncompressed bodies are not checked.
312///
313/// This is only a size check, not a validation of the recording. It returns
314/// [`ParseRecordingError::TooLarge`] for oversized payloads, but it also returns the other
315/// errors it hits on the way, such as a missing body or a broken zlib stream. Callers which
316/// only enforce the size limit can pass such malformed recordings through and leave them to
317/// downstream consumers, as Relay does for recordings which are not scrubbed.
318pub fn check_recording_size(bytes: &[u8], limit: usize) -> Result<(), ParseRecordingError> {
319    let (_, body) = split_recording(bytes)?;
320    if body.first() == Some(&b'[') {
321        return Ok(());
322    }
323    decompress(body, limit, &mut io::sink())
324}
325
326/// A utility that performs data scrubbing on compressed Replay recording payloads.
327///
328/// ### Example
329///
330/// ```
331/// use relay_replays::recording::RecordingScrubber;
332/// use relay_pii::PiiConfig;
333///
334/// // Obtain a PII config from the project state or create one on-demand.
335/// let pii_config = PiiConfig::default();
336/// let mut scrubber = RecordingScrubber::new(1_000_000, Some(&pii_config), None);
337///
338/// let payload = b"{}\n[]";
339/// let result = scrubber.process_recording(payload.as_slice());
340/// ```
341pub struct RecordingScrubber<'a> {
342    limit: usize,
343    transform: Rc<RefCell<ScrubberTransform<'a>>>,
344}
345
346impl<'a> RecordingScrubber<'a> {
347    /// Creates a new `RecordingScrubber` from PII configs.
348    ///
349    /// `limit` controls the maximum size in bytes during decompression. This function returns an
350    /// `Err` if decompressed contents exceed the limit. The two optional configs to be passed here
351    /// are from data scrubbing settings and from the dedicated PII config.
352    ///
353    /// # Performance
354    ///
355    /// The passed PII configs are [compiled](PiiConfig::compiled) by this constructor if their
356    /// compiled version is not yet cached. This can be a CPU-intensive process and should be called
357    /// from a blocking context.
358    pub fn new(
359        limit: usize,
360        config1: Option<&'a PiiConfig>,
361        config2: Option<&'a PiiConfig>,
362    ) -> Self {
363        Self {
364            limit,
365            transform: Rc::new(RefCell::new(ScrubberTransform {
366                processor1: config1.map(|c| PiiProcessor::new(c.compiled())),
367                processor2: config2.map(|c| PiiProcessor::new(c.compiled())),
368                state: ProcessingState::new_root(None, None),
369                path: vec![],
370            })),
371        }
372    }
373
374    /// Returns `true` if both configs are empty and no scrubbing would occur.
375    pub fn is_empty(&self) -> bool {
376        let tmp = self.transform.borrow();
377        tmp.processor1.is_none() && tmp.processor2.is_none()
378    }
379
380    fn scrub_replay<W>(&mut self, json: &[u8], write: W) -> Result<(), ParseRecordingError>
381    where
382        W: std::io::Write,
383    {
384        let mut deserializer = serde_json::Deserializer::from_slice(json);
385        let mut serializer = serde_json::Serializer::new(write);
386
387        deserializer.deserialize_seq(EventStreamVisitor::new(
388            &mut serializer,
389            self.transform.clone(),
390        ))?;
391
392        Ok(())
393    }
394
395    #[doc(hidden)] // Public for benchmarks.
396    pub fn transcode_replay(
397        &mut self,
398        body: &[u8],
399        output: &mut Vec<u8>,
400    ) -> Result<(), ParseRecordingError> {
401        let encoder = ZlibEncoder::new(output, Compression::default());
402
403        if body.first() == Some(&b'[') {
404            self.scrub_replay(body, encoder)
405        } else {
406            let mut decompressed = Vec::with_capacity(8 * 1024);
407            decompress(body, self.limit, &mut decompressed)?;
408            self.scrub_replay(&decompressed, encoder)
409        }
410    }
411
412    /// Parses a replay recording payload and applies data scrubbers.
413    ///
414    /// # Compression
415    ///
416    /// The recording `bytes` passed to this function can be a raw recording payload or compressed
417    /// with zlib. The result is always compressed, regardless of the input.
418    ///
419    /// During decompression, the scrubber applies a `limit`. If the decompressed buffer exceeds the
420    /// configured size, an `Err` is returned. This does not apply to decompressed payloads.
421    ///
422    /// # Errors
423    ///
424    /// This function requires a full recording payload including headers and body. This function
425    /// will return errors if:
426    ///  - Headers or the body are missing.
427    ///  - Headers and the body are separated by exactly one UNIX newline (`\n`).
428    ///  - The payload size exceeds the configured `limit` of the scrubber after decompression.
429    ///  - On errors during decompression or JSON parsing.
430    pub fn process_recording(&mut self, bytes: &[u8]) -> Result<Vec<u8>, ParseRecordingError> {
431        let (header, body) = split_recording(bytes)?;
432
433        let mut output = header.to_owned();
434        output.push(b'\n');
435        // Data scrubbing usually does not change the size of the output by much. We can preallocate
436        // enough space for the scrubbed output to avoid resizing the output buffer serveral times.
437        // Benchmarks have NOT shown a big difference, however.
438        output.reserve(body.len());
439        self.transcode_replay(body, &mut output)?;
440
441        Ok(output)
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    // End to end test coverage.
448
449    use std::io::Write;
450
451    use flate2::Compression;
452    use flate2::write::ZlibEncoder;
453    use relay_pii::{DataScrubbingConfig, PiiConfig};
454
455    use crate::recording::scrub_at_path;
456
457    use super::{ParseRecordingError, RecordingScrubber, check_recording_size};
458
459    fn default_pii_config() -> PiiConfig {
460        let mut scrubbing_config = DataScrubbingConfig::default();
461        scrubbing_config.scrub_data = true;
462        scrubbing_config.scrub_defaults = true;
463        scrubbing_config.scrub_ip_addresses = true;
464        scrubbing_config.pii_config_uncached().unwrap()
465    }
466
467    fn scrubber(config: &PiiConfig) -> RecordingScrubber<'_> {
468        RecordingScrubber::new(usize::MAX, Some(config), None)
469    }
470
471    #[test]
472    fn test_process_recording_end_to_end() {
473        // Valid compressed rrweb payload.  Contains a 16 byte header followed by a new line
474        // character and concludes with a gzipped rrweb payload.
475        let payload: &[u8] = &[
476            123, 34, 115, 101, 103, 109, 101, 110, 116, 95, 105, 100, 34, 58, 51, 125, 10, 120,
477            156, 149, 144, 91, 106, 196, 32, 20, 64, 247, 114, 191, 237, 160, 241, 145, 234, 38,
478            102, 1, 195, 124, 152, 104, 6, 33, 169, 193, 40, 52, 4, 247, 94, 91, 103, 40, 20, 108,
479            59, 191, 247, 30, 207, 225, 122, 57, 32, 238, 171, 5, 69, 17, 24, 29, 53, 168, 3, 54,
480            159, 194, 88, 70, 4, 193, 234, 55, 23, 157, 127, 219, 64, 93, 14, 120, 7, 37, 100, 1,
481            119, 80, 29, 102, 8, 156, 1, 213, 11, 4, 209, 45, 246, 60, 77, 155, 141, 160, 94, 232,
482            43, 206, 232, 206, 118, 127, 176, 132, 177, 7, 203, 42, 75, 36, 175, 44, 231, 63, 88,
483            217, 229, 107, 174, 179, 45, 234, 101, 45, 172, 232, 49, 163, 84, 22, 191, 232, 63, 61,
484            207, 93, 130, 229, 189, 216, 53, 138, 84, 182, 139, 178, 199, 191, 22, 139, 179, 238,
485            196, 227, 244, 134, 137, 240, 158, 60, 101, 34, 255, 18, 241, 6, 116, 42, 212, 119, 35,
486            234, 27, 40, 24, 130, 213, 102, 12, 105, 25, 160, 252, 147, 222, 103, 175, 205, 215,
487            182, 45, 168, 17, 48, 118, 210, 105, 142, 229, 217, 168, 163, 189, 249, 80, 254, 19,
488            146, 59, 13, 115, 10, 144, 115, 190, 126, 0, 2, 68, 180, 16,
489        ];
490
491        let config = default_pii_config();
492        let result = scrubber(&config).process_recording(payload);
493        assert!(!result.unwrap().is_empty());
494    }
495
496    #[test]
497    fn test_process_recording_no_body_data() {
498        // Empty bodies can not be decompressed and fail.
499        let payload: &[u8] = &[
500            123, 34, 115, 101, 103, 109, 101, 110, 116, 95, 105, 100, 34, 58, 51, 125, 10,
501        ];
502
503        let config = default_pii_config();
504        let result = scrubber(&config).process_recording(payload);
505        assert!(matches!(
506            result.unwrap_err(),
507            super::ParseRecordingError::Message("no body found"),
508        ));
509    }
510
511    #[test]
512    fn test_process_recording_bad_body_data() {
513        // Invalid gzip body contents.  Can not deflate.
514        let payload: &[u8] = &[
515            123, 34, 115, 101, 103, 109, 101, 110, 116, 95, 105, 100, 34, 58, 51, 125, 10, 22, 123,
516        ];
517
518        let config = default_pii_config();
519        let result = scrubber(&config).process_recording(payload);
520        assert!(matches!(
521            result.unwrap_err(),
522            super::ParseRecordingError::Compression(_),
523        ));
524    }
525
526    #[test]
527    fn test_process_recording_no_headers() {
528        // No header delimiter.  Entire payload is consumed as headers.  The empty body fails.
529        let payload: &[u8] = &[
530            123, 34, 115, 101, 103, 109, 101, 110, 116, 95, 105, 100, 34, 58, 51, 125,
531        ];
532
533        let config = default_pii_config();
534        let result = scrubber(&config).process_recording(payload);
535        assert!(matches!(
536            result.unwrap_err(),
537            super::ParseRecordingError::Message("no body found"),
538        ));
539    }
540
541    #[test]
542    fn test_process_recording_no_contents() {
543        // Empty payload can not be decompressed.  Header check never fails.
544        let payload: &[u8] = &[];
545
546        let config = default_pii_config();
547        let result = scrubber(&config).process_recording(payload);
548        assert!(matches!(
549            result.unwrap_err(),
550            super::ParseRecordingError::Message("no data found"),
551        ));
552    }
553
554    // RRWeb Payload Coverage
555
556    #[ignore = "type 3 nodes are not supported"]
557    #[test]
558    fn test_pii_credit_card_removal() {
559        let payload = include_bytes!("../tests/fixtures/rrweb-pii.json");
560
561        let mut transcoded = Vec::new();
562        let config = default_pii_config();
563        scrubber(&config)
564            .scrub_replay(payload.as_slice(), &mut transcoded)
565            .unwrap();
566
567        let parsed = std::str::from_utf8(&transcoded).unwrap();
568        assert!(parsed.contains(r#"{"type":3,"textContent":"[Filtered]","id":284}"#));
569    }
570
571    #[test]
572    fn test_scrub_pii_navigation() {
573        let payload = include_bytes!("../tests/fixtures/rrweb-performance-navigation.json");
574
575        let mut transcoded = Vec::new();
576        let config = default_pii_config();
577        scrubber(&config)
578            .scrub_replay(payload.as_slice(), &mut transcoded)
579            .unwrap();
580
581        let parsed = std::str::from_utf8(&transcoded).unwrap();
582        assert!(parsed.contains("https://sentry.io?credit-card=[Filtered]"));
583    }
584
585    #[test]
586    fn test_scrub_pii_resource() {
587        let payload = include_bytes!("../tests/fixtures/rrweb-performance-resource.json");
588
589        let mut transcoded = Vec::new();
590        let config = default_pii_config();
591        scrubber(&config)
592            .scrub_replay(payload.as_slice(), &mut transcoded)
593            .unwrap();
594
595        let parsed = std::str::from_utf8(&transcoded).unwrap();
596        assert!(parsed.contains("https://sentry.io?credit-card=[Filtered]"));
597    }
598
599    #[ignore = "type 3 nodes are not supported"]
600    #[test]
601    fn test_pii_ip_address_removal() {
602        let payload = include_bytes!("../tests/fixtures/rrweb-pii-ip-address.json");
603
604        let mut transcoded = Vec::new();
605        let config = default_pii_config();
606        scrubber(&config)
607            .scrub_replay(payload.as_slice(), &mut transcoded)
608            .unwrap();
609
610        let parsed = std::str::from_utf8(&transcoded).unwrap();
611        assert!(parsed.contains("\"value\":\"[ip]\"")); // Assert texts were mutated.
612        assert!(parsed.contains("\"textContent\":\"[ip]\"")) // Assert text node was mutated.
613    }
614
615    // Event Parsing and Scrubbing.
616
617    #[ignore = "type 2 nodes are not supported"]
618    #[test]
619    fn test_scrub_pii_full_snapshot_event() {
620        let payload = include_bytes!("../tests/fixtures/rrweb-event-2.json");
621
622        let mut transcoded = Vec::new();
623        let config = default_pii_config();
624        scrubber(&config)
625            .scrub_replay(payload.as_slice(), &mut transcoded)
626            .unwrap();
627
628        let scrubbed_result = std::str::from_utf8(&transcoded).unwrap();
629        // NOTE: The normalization below was removed
630        // assert!(scrubbed_result.contains("\"attributes\":{\"src\":\"#\"}"));
631        assert!(scrubbed_result.contains("\"textContent\":\"my ssn is [Filtered]\""));
632    }
633
634    #[ignore = "type 3 nodes are not supported"]
635    #[test]
636    fn test_scrub_pii_incremental_snapshot_event() {
637        let payload = include_bytes!("../tests/fixtures/rrweb-event-3.json");
638
639        let mut transcoded = Vec::new();
640        let config = default_pii_config();
641        scrubber(&config)
642            .scrub_replay(payload.as_slice(), &mut transcoded)
643            .unwrap();
644
645        let scrubbed_result = std::str::from_utf8(&transcoded).unwrap();
646        assert!(scrubbed_result.contains("\"textContent\":\"[Filtered]\""));
647        assert!(scrubbed_result.contains("\"value\":\"[Filtered]\""));
648    }
649
650    #[test]
651    fn test_scrub_pii_custom_event() {
652        let payload = include_bytes!("../tests/fixtures/rrweb-event-5.json");
653
654        let mut transcoded = Vec::new();
655        let config = default_pii_config();
656        scrubber(&config)
657            .scrub_replay(payload.as_slice(), &mut transcoded)
658            .unwrap();
659
660        let scrubbed_result = std::str::from_utf8(&transcoded).unwrap();
661        assert!(scrubbed_result.contains("\"description\":\"[Filtered]\""));
662        assert!(scrubbed_result.contains("\"description\":\"https://sentry.io?ip-address=[ip]\""));
663        // NOTE: default scrubbers do not remove email address
664        // assert!(scrubbed_result.contains("\"message\":\"[email]\""));
665    }
666
667    #[test]
668    fn test_scrub_pii_key_based() {
669        let payload = include_bytes!("../tests/fixtures/rrweb-request.json");
670
671        let mut transcoded = Vec::new();
672        let config = default_pii_config();
673
674        scrubber(&config)
675            .scrub_replay(payload.as_slice(), &mut transcoded)
676            .unwrap();
677
678        let scrubbed_result = std::str::from_utf8(&transcoded).unwrap();
679        let scrubbed: serde_json::Value = serde_json::from_str(scrubbed_result).unwrap();
680
681        // Normal fields are not scrubbed:
682        assert_eq!(scrubbed[0]["data"]["payload"]["data"]["method"], "POST");
683
684        assert_eq!(
685            scrubbed[0]["data"]["payload"]["data"]["request"]["body"]["api_key"],
686            "[Filtered]"
687        );
688    }
689
690    #[test]
691    fn test_scrub_pii_key_based_edge_cases() {
692        let payload = include_bytes!("../tests/fixtures/rrweb-request-edge-cases.json");
693
694        let mut transcoded = Vec::new();
695        let config = default_pii_config();
696
697        scrubber(&config)
698            .scrub_replay(payload.as_slice(), &mut transcoded)
699            .unwrap();
700
701        let scrubbed_result = std::str::from_utf8(&transcoded).unwrap();
702        let scrubbed: serde_json::Value = serde_json::from_str(scrubbed_result).unwrap();
703
704        insta::assert_ron_snapshot!(scrubbed);
705    }
706
707    #[test]
708    fn test_scrub_pii_key_with_json_escape() {
709        // A key containing an escape sequence (here `\n`) must not desynchronize the path
710        // tracking, later siblings must still be scrubbed.
711        let payload =
712            br#"[{"type":5,"data":{"payload":{"data":{"a\nb":"x","password":"hunter2"}}}}]"#;
713
714        let mut transcoded = Vec::new();
715        let config = default_pii_config();
716        scrubber(&config)
717            .scrub_replay(payload.as_slice(), &mut transcoded)
718            .unwrap();
719
720        let scrubbed: serde_json::Value = serde_json::from_slice(&transcoded).unwrap();
721        assert_eq!(
722            scrubbed[0]["data"]["payload"]["data"]["password"],
723            "[Filtered]"
724        );
725    }
726
727    fn compressed_recording(body: &[u8]) -> Vec<u8> {
728        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::best());
729        encoder.write_all(body).unwrap();
730        let mut recording = b"{\"segment_id\":0}\n".to_vec();
731        recording.extend(encoder.finish().unwrap());
732        recording
733    }
734
735    #[test]
736    fn test_check_recording_size_within_limit() {
737        let body = b"[{\"type\":4}]";
738        assert!(check_recording_size(&compressed_recording(body), body.len()).is_ok());
739    }
740
741    #[test]
742    fn test_check_recording_size_exceeds_limit() {
743        let body = b"[{\"type\":4}]";
744        assert!(matches!(
745            check_recording_size(&compressed_recording(body), body.len() - 1),
746            Err(ParseRecordingError::TooLarge)
747        ));
748    }
749
750    #[test]
751    fn test_check_recording_size_high_compression_ratio() {
752        let recording = compressed_recording(&vec![b' '; 1024 * 1024]);
753        assert!(recording.len() < 2048);
754        assert!(matches!(
755            check_recording_size(&recording, 1024),
756            Err(ParseRecordingError::TooLarge)
757        ));
758    }
759
760    #[test]
761    fn test_check_recording_size_uncompressed() {
762        assert!(check_recording_size(b"{\"segment_id\":0}\n[{\"type\":4}]", 1).is_ok());
763    }
764
765    #[test]
766    fn test_process_recording_exceeds_limit() {
767        let body = b"[{\"type\":4}]";
768        let config = default_pii_config();
769        let mut scrubber = RecordingScrubber::new(body.len() - 1, Some(&config), None);
770        assert!(matches!(
771            scrubber.process_recording(&compressed_recording(body)),
772            Err(ParseRecordingError::TooLarge)
773        ));
774    }
775
776    #[test]
777    fn test_scrub_at_path() {
778        for (should_scrub, path) in [
779            (false, vec![]),
780            (false, vec!["data"]),
781            (false, vec!["data", "payload"]),
782            (false, vec!["data", "payload", "foo"]),
783            (false, vec!["foo", "payload", "data"]),
784            (true, vec!["data", "payload", "data"]),
785            (true, vec!["data", "payload", "data", "request"]),
786            (true, vec!["data", "payload", "data", "request", "body"]),
787        ] {
788            let path = path.into_iter().map(|p| p.to_owned()).collect::<Vec<_>>();
789            assert_eq!(should_scrub, scrub_at_path(&path));
790        }
791    }
792}