-
Notifications
You must be signed in to change notification settings - Fork 91
/
processor.rs
1155 lines (1042 loc) · 40 KB
/
processor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::mem;
use once_cell::sync::OnceCell;
use regex::Regex;
use crate::pii::compiledconfig::RuleRef;
use crate::pii::regexes::{get_regex_for_rule_type, PatternType, ReplaceBehavior, ANYTHING_REGEX};
use crate::pii::utils::{hash_value, process_pairlist};
use crate::pii::{CompiledPiiConfig, Redaction, RuleType};
use crate::processor::{
process_chunked_value, Chunk, Pii, ProcessValue, ProcessingState, Processor, ValueType,
};
use crate::protocol::{AsPair, IpAddr, NativeImagePath, PairList, Replay, User};
use crate::types::{Meta, ProcessingAction, ProcessingResult, Remark, RemarkType, Value};
/// A processor that performs PII stripping.
pub struct PiiProcessor<'a> {
compiled_config: &'a CompiledPiiConfig,
}
impl<'a> PiiProcessor<'a> {
/// Creates a new processor based on a config.
pub fn new(compiled_config: &'a CompiledPiiConfig) -> PiiProcessor<'a> {
// this constructor needs to be cheap... a new PiiProcessor is created for each event. Move
// any init logic into CompiledPiiConfig::new.
PiiProcessor { compiled_config }
}
fn apply_all_rules(
&self,
meta: &mut Meta,
state: &ProcessingState<'_>,
mut value: Option<&mut String>,
) -> ProcessingResult {
let pii = state.attrs().pii;
if pii == Pii::False {
return Ok(());
}
for (selector, rules) in self.compiled_config.applications.iter() {
if state.path().matches_selector(selector) {
#[allow(clippy::needless_option_as_deref)]
for rule in rules {
let reborrowed_value = value.as_deref_mut();
apply_rule_to_value(meta, rule, state.path().key(), reborrowed_value)?;
}
}
}
Ok(())
}
}
impl<'a> Processor for PiiProcessor<'a> {
fn before_process<T: ProcessValue>(
&mut self,
value: Option<&T>,
meta: &mut Meta,
state: &ProcessingState<'_>,
) -> ProcessingResult {
if let Some(Value::String(original_value)) = meta.original_value_as_mut() {
// Also apply pii scrubbing to the original value (set by normalization or other processors),
// such that we do not leak sensitive data through meta. Deletes `original_value` if an Error
// value is returned.
if let Some(parent) = state.iter().next() {
let path = state.path();
let new_state = parent.enter_borrowed(
path.key().unwrap_or(""),
Some(Cow::Borrowed(state.attrs())),
enumset::enum_set!(ValueType::String),
);
if self
.apply_all_rules(&mut Meta::default(), &new_state, Some(original_value))
.is_err()
{
// `apply_all_rules` returned `DeleteValueHard` or `DeleteValueSoft`, so delete the original as well.
meta.set_original_value(Option::<String>::None);
}
}
}
// booleans cannot be PII, and strings are handled in process_string
if state.value_type().contains(ValueType::Boolean)
|| state.value_type().contains(ValueType::String)
{
return Ok(());
}
if value.is_none() {
return Ok(());
}
// apply rules based on key/path
self.apply_all_rules(meta, state, None)
}
fn process_string(
&mut self,
value: &mut String,
meta: &mut Meta,
state: &ProcessingState<'_>,
) -> ProcessingResult {
if let "" | "true" | "false" | "null" | "undefined" = value.as_str() {
return Ok(());
}
// same as before_process. duplicated here because we can only check for "true",
// "false" etc in process_string.
self.apply_all_rules(meta, state, Some(value))
}
fn process_native_image_path(
&mut self,
NativeImagePath(ref mut value): &mut NativeImagePath,
meta: &mut Meta,
state: &ProcessingState<'_>,
) -> ProcessingResult {
// In NativeImagePath we must not strip the file's basename because that would break
// processing.
//
// We pop the basename from the end of the string, call process_string and push the
// basename again.
//
// The ranges in Meta should still be right as long as we only pop/push from the end of the
// string. If we decide that we need to preserve anything other than suffixes all PII
// tooltips/annotations are potentially wrong.
if let Some(index) = value.rfind(|c| c == '/' || c == '\\') {
let basename = value.split_off(index);
match self.process_string(value, meta, state) {
Ok(()) => value.push_str(&basename),
Err(ProcessingAction::DeleteValueHard) | Err(ProcessingAction::DeleteValueSoft) => {
*value = basename[1..].to_owned();
}
Err(ProcessingAction::InvalidTransaction(x)) => {
return Err(ProcessingAction::InvalidTransaction(x))
}
}
}
Ok(())
}
fn process_pairlist<T: ProcessValue + AsPair>(
&mut self,
value: &mut PairList<T>,
_meta: &mut Meta,
state: &ProcessingState,
) -> ProcessingResult {
process_pairlist(self, value, state)
}
fn process_user(
&mut self,
user: &mut User,
_meta: &mut Meta,
state: &ProcessingState<'_>,
) -> ProcessingResult {
let ip_was_valid = user.ip_address.value().map_or(true, IpAddr::is_valid);
// Recurse into the user and does PII processing on fields.
user.process_child_values(self, state)?;
let has_other_fields = user.id.value().is_some()
|| user.username.value().is_some()
|| user.email.value().is_some();
let ip_is_still_valid = user.ip_address.value().map_or(true, IpAddr::is_valid);
// If the IP address has become invalid as part of PII processing, we move it into the user
// ID. That ensures people can do IP hashing and still have a correct users-affected count.
//
// Right now both Snuba and EventUser discard unparseable IPs for indexing, and we assume
// we want to keep it that way.
//
// If there are any other fields set that take priority over the IP for uniquely
// identifying a user (has_other_fields), we do not want to do anything. The value will be
// wiped out in renormalization anyway.
if ip_was_valid && !has_other_fields && !ip_is_still_valid {
user.id = mem::take(&mut user.ip_address).map_value(|ip| ip.into_inner().into());
}
Ok(())
}
// Replay PII processor entry point.
fn process_replay(
&mut self,
replay: &mut Replay,
_meta: &mut Meta,
state: &ProcessingState<'_>,
) -> ProcessingResult {
replay.process_child_values(self, state)?;
Ok(())
}
}
fn apply_rule_to_value(
meta: &mut Meta,
rule: &RuleRef,
key: Option<&str>,
mut value: Option<&mut String>,
) -> ProcessingResult {
// The rule might specify to remove or to redact. If redaction is chosen, we need to
// chunk up the value, otherwise we need to simply mark the value for deletion.
let should_redact_chunks = !matches!(rule.redaction, Redaction::Default | Redaction::Remove);
// In case the value is not a string (but a container, bool or number) and the rule matches on
// anything, we can only remove the value (not replace, hash, etc).
if rule.ty == RuleType::Anything && (value.is_none() || !should_redact_chunks) {
// The value is a container, @anything on a container can do nothing but delete.
meta.add_remark(Remark::new(RemarkType::Removed, rule.origin.clone()));
return Err(ProcessingAction::DeleteValueHard);
}
macro_rules! apply_regex {
($regex:expr, $replace_behavior:expr) => {
if let Some(ref mut value) = value {
process_chunked_value(value, meta, |chunks| {
apply_regex_to_chunks(chunks, rule, $regex, $replace_behavior)
});
}
};
}
for (pattern_type, regex, replace_behavior) in get_regex_for_rule_type(&rule.ty) {
match pattern_type {
PatternType::KeyValue => {
if regex.is_match(key.unwrap_or("")) {
if value.is_some() && should_redact_chunks {
// If we're given a string value here, redact the value like we would with
// @anything.
apply_regex!(&ANYTHING_REGEX, replace_behavior);
} else {
meta.add_remark(Remark::new(RemarkType::Removed, rule.origin.clone()));
return Err(ProcessingAction::DeleteValueHard);
}
} else {
// If we did not redact using the key, we will redact the entire value if the key
// appears in it.
apply_regex!(regex, replace_behavior);
}
}
PatternType::Value => {
apply_regex!(regex, replace_behavior);
}
}
}
Ok(())
}
fn apply_regex_to_chunks<'a>(
chunks: Vec<Chunk<'a>>,
rule: &RuleRef,
regex: &Regex,
replace_behavior: ReplaceBehavior,
) -> Vec<Chunk<'a>> {
// NB: This function allocates the entire string and all chunks a second time. This means it
// cannot reuse chunks and reallocates them. Ideally, we would be able to run the regex directly
// on the chunks, but the `regex` crate does not support that.
let mut search_string = String::new();
let mut has_text = false;
for chunk in &chunks {
match chunk {
Chunk::Text { text } => {
has_text = true;
search_string.push_str(&text.replace('\x00', ""));
}
Chunk::Redaction { .. } => search_string.push('\x00'),
}
}
if !has_text {
// Nothing to replace.
return chunks;
}
// Early exit if this regex does not match and return the original chunks.
let mut captures_iter = regex.captures_iter(&search_string).peekable();
if captures_iter.peek().is_none() {
return chunks;
}
let mut replacement_chunks = vec![];
for chunk in chunks {
if let Chunk::Redaction { .. } = chunk {
replacement_chunks.push(chunk);
}
}
replacement_chunks.reverse();
fn process_text<'a>(
text: &str,
rv: &mut Vec<Chunk<'a>>,
replacement_chunks: &mut Vec<Chunk<'a>>,
) {
if text.is_empty() {
return;
}
static NULL_SPLIT_RE: OnceCell<Regex> = OnceCell::new();
let regex = NULL_SPLIT_RE.get_or_init(|| {
#[allow(clippy::trivial_regex)]
Regex::new("\x00").unwrap()
});
let mut pos = 0;
for piece in regex.find_iter(text) {
rv.push(Chunk::Text {
text: Cow::Owned(text[pos..piece.start()].to_string()),
});
rv.push(replacement_chunks.pop().unwrap());
pos = piece.end();
}
rv.push(Chunk::Text {
text: Cow::Owned(text[pos..].to_string()),
});
}
let mut pos = 0;
let mut rv = Vec::with_capacity(replacement_chunks.len());
match replace_behavior {
ReplaceBehavior::Groups(ref groups) => {
for m in captures_iter {
for (idx, g) in m.iter().enumerate() {
if let Some(g) = g {
if groups.contains(&(idx as u8)) {
process_text(
&search_string[pos..g.start()],
&mut rv,
&mut replacement_chunks,
);
insert_replacement_chunks(rule, g.as_str(), &mut rv);
pos = g.end();
}
}
}
}
process_text(&search_string[pos..], &mut rv, &mut replacement_chunks);
debug_assert!(replacement_chunks.is_empty());
}
ReplaceBehavior::Value => {
// We only want to replace a string value, and the replacement chunk for that is
// inserted by insert_replacement_chunks. Adding chunks from replacement_chunks
// results in the incorrect behavior of a total of more chunks than the input.
insert_replacement_chunks(rule, &search_string, &mut rv);
}
}
rv
}
fn insert_replacement_chunks(rule: &RuleRef, text: &str, output: &mut Vec<Chunk<'_>>) {
match &rule.redaction {
Redaction::Default | Redaction::Remove => {
output.push(Chunk::Redaction {
text: Cow::Borrowed(""),
rule_id: Cow::Owned(rule.origin.to_string()),
ty: RemarkType::Removed,
});
}
Redaction::Mask => {
let buf = vec!['*'; text.chars().count()];
output.push(Chunk::Redaction {
ty: RemarkType::Masked,
rule_id: Cow::Owned(rule.origin.to_string()),
text: buf.into_iter().collect(),
})
}
Redaction::Hash => {
output.push(Chunk::Redaction {
ty: RemarkType::Pseudonymized,
rule_id: Cow::Owned(rule.origin.to_string()),
text: Cow::Owned(hash_value(text.as_bytes())),
});
}
Redaction::Replace(replace) => {
output.push(Chunk::Redaction {
ty: RemarkType::Substituted,
rule_id: Cow::Owned(rule.origin.to_string()),
text: Cow::Owned(replace.text.clone()),
});
}
Redaction::Other => relay_log::warn!("Incoming redaction is not supported"),
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use insta::assert_debug_snapshot;
use super::*;
use crate::pii::{DataScrubbingConfig, PiiConfig, ReplaceRedaction};
use crate::processor::process_value;
use crate::protocol::{
Addr, DataElement, DebugImage, DebugMeta, Event, ExtraValue, Headers, HttpElement,
LogEntry, NativeDebugImage, Request, Span, TagEntry, Tags,
};
use crate::testutils::assert_annotated_snapshot;
use crate::types::{Annotated, FromValue, Object, Value};
fn to_pii_config(datascrubbing_config: &DataScrubbingConfig) -> Option<PiiConfig> {
use crate::pii::convert::to_pii_config as to_pii_config_impl;
let rv = to_pii_config_impl(datascrubbing_config).unwrap();
if let Some(ref config) = rv {
let roundtrip: PiiConfig =
serde_json::from_value(serde_json::to_value(config).unwrap()).unwrap();
assert_eq!(&roundtrip, config);
}
rv
}
#[test]
fn test_scrub_original_value() {
let mut data = Event::from_value(
serde_json::json!({
"user": {
"username": "hey man 73.133.27.120", // should be stripped despite not being "known ip field"
"ip_address": "is this an ip address? 73.133.27.120", // <--------
},
"hpkp":"invalid data my ip address is 74.133.27.120 and my credit card number is 4571234567890111 ",
})
.into(),
);
let scrubbing_config = DataScrubbingConfig {
scrub_data: true,
scrub_ip_addresses: true,
scrub_defaults: true,
..Default::default()
};
let pii_config = to_pii_config(&scrubbing_config).unwrap();
let mut pii_processor = PiiProcessor::new(pii_config.compiled());
process_value(&mut data, &mut pii_processor, ProcessingState::root()).unwrap();
assert_debug_snapshot!(&data);
}
#[test]
fn test_basic_stripping() {
let config = PiiConfig::from_json(
r##"
{
"rules": {
"remove_bad_headers": {
"type": "redact_pair",
"keyPattern": "(?i)cookie|secret[-_]?key"
}
},
"applications": {
"$string": ["@ip"],
"$object.**": ["remove_bad_headers"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
logentry: Annotated::new(LogEntry {
formatted: Annotated::new("Hello world!".to_string().into()),
..Default::default()
}),
request: Annotated::new(Request {
env: {
let mut rv = Object::new();
rv.insert(
"SECRET_KEY".to_string(),
Annotated::new(Value::String("134141231231231231231312".into())),
);
Annotated::new(rv)
},
headers: {
let rv = vec![
Annotated::new((
Annotated::new("Cookie".to_string().into()),
Annotated::new("super secret".to_string().into()),
)),
Annotated::new((
Annotated::new("X-Forwarded-For".to_string().into()),
Annotated::new("127.0.0.1".to_string().into()),
)),
];
Annotated::new(Headers(PairList(rv)))
},
..Default::default()
}),
tags: Annotated::new(Tags(
vec![Annotated::new(TagEntry(
Annotated::new("forwarded_for".to_string()),
Annotated::new("127.0.0.1".to_string()),
))]
.into(),
)),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_redact_containers() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$object": ["@anything"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"foo".to_string(),
Annotated::new(ExtraValue(Value::String("bar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_redact_custom_pattern() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$string": ["myrule"]
},
"rules": {
"myrule": {
"type": "pattern",
"pattern": "foo",
"redaction": {
"method": "replace",
"text": "asd"
}
}
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"myvalue".to_string(),
Annotated::new(ExtraValue(Value::String("foobar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_no_field_upsert() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"**": ["@anything:remove"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"myvalue".to_string(),
Annotated::new(ExtraValue(Value::String("foobar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_anything_hash_on_string() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$string": ["@anything:hash"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"myvalue".to_string(),
Annotated::new(ExtraValue(Value::String("foobar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_anything_hash_on_container() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$object": ["@anything:hash"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"myvalue".to_string(),
Annotated::new(ExtraValue(Value::String("foobar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_remove_debugmeta_path() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"debug_meta.images.*.code_file": ["@anything:remove"],
"debug_meta.images.*.debug_file": ["@anything:remove"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
debug_meta: Annotated::new(DebugMeta {
images: Annotated::new(vec![Annotated::new(DebugImage::Symbolic(Box::new(
NativeDebugImage {
code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
debug_id: Annotated::new(
"971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap(),
),
debug_file: Annotated::new("wntdll.pdb".into()),
debug_checksum: Annotated::empty(),
arch: Annotated::new("arm64".to_string()),
image_addr: Annotated::new(Addr(0)),
image_size: Annotated::new(4096),
image_vmaddr: Annotated::new(Addr(32768)),
other: {
let mut map = Object::new();
map.insert(
"other".to_string(),
Annotated::new(Value::String("value".to_string())),
);
map
},
},
)))]),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_replace_debugmeta_path() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"debug_meta.images.*.code_file": ["@anything:replace"],
"debug_meta.images.*.debug_file": ["@anything:replace"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
debug_meta: Annotated::new(DebugMeta {
images: Annotated::new(vec![Annotated::new(DebugImage::Symbolic(Box::new(
NativeDebugImage {
code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
debug_id: Annotated::new(
"971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap(),
),
debug_file: Annotated::new("wntdll.pdb".into()),
debug_checksum: Annotated::empty(),
arch: Annotated::new("arm64".to_string()),
image_addr: Annotated::new(Addr(0)),
image_size: Annotated::new(4096),
image_vmaddr: Annotated::new(Addr(32768)),
other: {
let mut map = Object::new();
map.insert(
"other".to_string(),
Annotated::new(Value::String("value".to_string())),
);
map
},
},
)))]),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_hash_debugmeta_path() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"debug_meta.images.*.code_file": ["@anything:hash"],
"debug_meta.images.*.debug_file": ["@anything:hash"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
debug_meta: Annotated::new(DebugMeta {
images: Annotated::new(vec![Annotated::new(DebugImage::Symbolic(Box::new(
NativeDebugImage {
code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
debug_id: Annotated::new(
"971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap(),
),
debug_file: Annotated::new("wntdll.pdb".into()),
debug_checksum: Annotated::empty(),
arch: Annotated::new("arm64".to_string()),
image_addr: Annotated::new(Addr(0)),
image_size: Annotated::new(4096),
image_vmaddr: Annotated::new(Addr(32768)),
other: {
let mut map = Object::new();
map.insert(
"other".to_string(),
Annotated::new(Value::String("value".to_string())),
);
map
},
},
)))]),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_debugmeta_path_not_addressible_with_wildcard_selector() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$string": ["@anything:remove"],
"**": ["@anything:remove"],
"debug_meta.**": ["@anything:remove"],
"(debug_meta.images.**.code_file & $string)": ["@anything:remove"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
debug_meta: Annotated::new(DebugMeta {
images: Annotated::new(vec![Annotated::new(DebugImage::Symbolic(Box::new(
NativeDebugImage {
code_id: Annotated::new("59b0d8f3183000".parse().unwrap()),
code_file: Annotated::new("C:\\Windows\\System32\\ntdll.dll".into()),
debug_id: Annotated::new(
"971f98e5-ce60-41ff-b2d7-235bbeb34578-1".parse().unwrap(),
),
debug_file: Annotated::new("wntdll.pdb".into()),
debug_checksum: Annotated::empty(),
arch: Annotated::new("arm64".to_string()),
image_addr: Annotated::new(Addr(0)),
image_size: Annotated::new(4096),
image_vmaddr: Annotated::new(Addr(32768)),
other: {
let mut map = Object::new();
map.insert(
"other".to_string(),
Annotated::new(Value::String("value".to_string())),
);
map
},
},
)))]),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_quoted_keys() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"extra.'special ,./<>?!@#$%^&*())''gärbage'''": ["@anything:remove"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
extra: {
let mut map = Object::new();
map.insert(
"do not ,./<>?!@#$%^&*())'ßtrip'".to_string(),
Annotated::new(ExtraValue(Value::String("foo".to_string()))),
);
map.insert(
"special ,./<>?!@#$%^&*())'gärbage'".to_string(),
Annotated::new(ExtraValue(Value::String("bar".to_string()))),
);
Annotated::new(map)
},
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert_annotated_snapshot!(event);
}
#[test]
fn test_logentry_value_types() {
// Assert that logentry.formatted is addressable as $string, $message and $logentry.formatted
for formatted_selector in &[
"$logentry.formatted",
"$message",
"$logentry.formatted && $message",
"$string",
] {
let config = PiiConfig::from_json(&format!(
r##"
{{
"applications": {{
"{formatted_selector}": ["@anything:remove"]
}}
}}
"##,
formatted_selector = dbg!(formatted_selector),
))
.unwrap();
let mut event = Annotated::new(Event {
logentry: Annotated::new(LogEntry {
formatted: Annotated::new("Hello world!".to_string().into()),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
assert!(event
.value()
.unwrap()
.logentry
.value()
.unwrap()
.formatted
.value()
.is_none());
}
}
#[test]
fn test_ip_address_hashing() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$user.ip_address": ["@ip:hash"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
user: Annotated::new(User {
ip_address: Annotated::new(IpAddr("127.0.0.1".to_string())),
..Default::default()
}),
..Default::default()
});
let mut processor = PiiProcessor::new(config.compiled());
process_value(&mut event, &mut processor, ProcessingState::root()).unwrap();
let user = event.value().unwrap().user.value().unwrap();
assert!(user.ip_address.value().is_none());
assert_eq!(
user.id.value().unwrap().as_str(),
"AE12FE3B5F129B5CC4CDD2B136B7B7947C4D2741"
);
}
#[test]
fn test_ip_address_hashing_does_not_overwrite_id() {
let config = PiiConfig::from_json(
r##"
{
"applications": {
"$user.ip_address": ["@ip:hash"]
}
}
"##,
)
.unwrap();
let mut event = Annotated::new(Event {
user: Annotated::new(User {
id: Annotated::new("123".to_string().into()),
ip_address: Annotated::new(IpAddr("127.0.0.1".to_string())),