1use 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
31static PII_FIELDS: LazyLock<[Vec<&str>; 2]> = LazyLock::new(|| {
35 [
36 vec!["data", "payload", "description"],
37 vec!["data", "payload", "data"],
38 ]
39});
40
41fn 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
48const FIELD_ATTRS_PII_TRUE: FieldAttrs = FieldAttrs::new().pii(Pii::True);
50
51const FIELD_ATTRS_PII_FALSE: FieldAttrs = FieldAttrs::new().pii(Pii::False);
53
54#[derive(Debug)]
56pub enum ParseRecordingError {
57 Parse(serde_json::Error),
59 Compression(std::io::Error),
61 TooLarge,
63 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
96struct ScrubberTransform<'a> {
100 processor1: Option<PiiProcessor<'a>>,
102 processor2: Option<PiiProcessor<'a>>,
103 state: ProcessingState<'a>,
105 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), )
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()); }
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
170struct 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
188struct EventStreamVisitor<'a, S> {
190 serializer: S,
191 scrubber: Rc<RefCell<ScrubberTransform<'a>>>,
192}
193
194impl<'a, S> EventStreamVisitor<'a, S> {
195 const SENTRY_EVENT_TYPE: u8 = 5;
199
200 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 #[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 while let Some(raw) = v.next_element::<&'de RawValue>()? {
248 let helper = serde_json::from_str::<TypeHelper>(raw.get()).map_err(s2d)?;
249 if helper.ty == Self::SENTRY_EVENT_TYPE {
251 seq.serialize_element(&ScrubbedValue(raw, self.scrubber.clone()))
252 .map_err(s2d)?;
253 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
265fn s2d<S, D>(s: S) -> D
267where
268 S: ser::Error,
269 D: de::Error,
270{
271 D::custom(s.to_string())
272}
273
274fn 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
291fn 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
308pub 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
326pub struct RecordingScrubber<'a> {
342 limit: usize,
343 transform: Rc<RefCell<ScrubberTransform<'a>>>,
344}
345
346impl<'a> RecordingScrubber<'a> {
347 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 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)] 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 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 output.reserve(body.len());
439 self.transcode_replay(body, &mut output)?;
440
441 Ok(output)
442 }
443}
444
445#[cfg(test)]
446mod tests {
447 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 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 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 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 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 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 #[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!(parsed.contains("\"textContent\":\"[ip]\"")) }
614
615 #[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 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 }
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 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 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}