-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathattrs.rs
912 lines (809 loc) · 28.5 KB
/
attrs.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
use std::borrow::Cow;
use std::fmt;
use std::ops::{Deref, RangeInclusive};
use enumset::{EnumSet, EnumSetType};
use smallvec::SmallVec;
use crate::macros::derive_fromstr_and_display;
use crate::processor::{ProcessValue, SelectorPathItem, SelectorSpec};
use crate::types::Annotated;
/// Error for unknown value types.
#[derive(Debug)]
pub struct UnknownValueTypeError;
impl fmt::Display for UnknownValueTypeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown value type")
}
}
impl std::error::Error for UnknownValueTypeError {}
/// The (simplified) type of a value.
#[derive(Debug, Ord, PartialOrd, EnumSetType)]
pub enum ValueType {
// Basic types
String,
Binary,
Number,
Boolean,
DateTime,
Array,
Object,
// Roots
Event,
Attachments,
Replay,
// Protocol types
Exception,
Stacktrace,
Frame,
Request,
User,
LogEntry,
Message,
Thread,
Breadcrumb,
Span,
ClientSdkInfo,
// Attachments and Contents
Minidump,
HeapMemory,
StackMemory,
}
impl ValueType {
pub fn for_field<T: ProcessValue>(field: &Annotated<T>) -> EnumSet<Self> {
field
.value()
.map(ProcessValue::value_type)
.unwrap_or_else(EnumSet::empty)
}
}
derive_fromstr_and_display!(ValueType, UnknownValueTypeError, {
ValueType::String => "string",
ValueType::Binary => "binary",
ValueType::Number => "number",
ValueType::Boolean => "boolean" | "bool",
ValueType::DateTime => "datetime",
ValueType::Array => "array" | "list",
ValueType::Object => "object",
ValueType::Event => "event",
ValueType::Attachments => "attachments",
ValueType::Replay => "replay",
ValueType::Exception => "error" | "exception",
ValueType::Stacktrace => "stack" | "stacktrace",
ValueType::Frame => "frame",
ValueType::Request => "http" | "request",
ValueType::User => "user",
ValueType::LogEntry => "logentry",
ValueType::Message => "message",
ValueType::Thread => "thread",
ValueType::Breadcrumb => "breadcrumb",
ValueType::Span => "span",
ValueType::ClientSdkInfo => "sdk",
ValueType::Minidump => "minidump",
ValueType::HeapMemory => "heap_memory",
ValueType::StackMemory => "stack_memory",
});
/// The maximum length of a field.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum MaxChars {
Hash,
EnumLike,
Summary,
Message,
Symbol,
Path,
ShortPath,
Logger,
Email,
Culprit,
TagKey,
TagValue,
Environment,
Distribution,
Hard(usize),
Soft(usize),
}
impl MaxChars {
/// The cap in number of unicode characters.
pub fn limit(self) -> usize {
match self {
MaxChars::Hash => 128,
MaxChars::EnumLike => 128,
MaxChars::Summary => 1024,
MaxChars::Message => 8192,
MaxChars::Symbol => 256,
MaxChars::Path => 256,
MaxChars::ShortPath => 128,
// these are from constants.py or limits imposed by the database
MaxChars::Logger => 64,
MaxChars::Email => 75,
MaxChars::Culprit => 200,
MaxChars::TagKey => 32,
MaxChars::TagValue => 200,
MaxChars::Environment => 64,
MaxChars::Distribution => 64,
MaxChars::Soft(len) | MaxChars::Hard(len) => len,
}
}
/// The number of extra characters permitted.
pub fn allowance(self) -> usize {
match self {
MaxChars::Hash => 0,
MaxChars::EnumLike => 0,
MaxChars::Summary => 100,
MaxChars::Message => 200,
MaxChars::Symbol => 20,
MaxChars::Path => 40,
MaxChars::ShortPath => 20,
MaxChars::Logger => 0,
MaxChars::Email => 0,
MaxChars::Culprit => 0,
MaxChars::TagKey => 0,
MaxChars::TagValue => 0,
MaxChars::Environment => 0,
MaxChars::Distribution => 0,
MaxChars::Soft(_) => 10,
MaxChars::Hard(_) => 0,
}
}
}
/// The maximum size of a databag.
#[derive(Debug, Clone, Copy, PartialEq, Hash)]
pub enum BagSize {
Small,
Medium,
Large,
Larger,
Massive,
}
impl BagSize {
/// Maximum depth of the structure.
pub fn max_depth(self) -> usize {
match self {
BagSize::Small => 3,
BagSize::Medium => 5,
BagSize::Large => 7,
BagSize::Larger => 7,
BagSize::Massive => 7,
}
}
/// Maximum estimated JSON bytes.
pub fn max_size(self) -> usize {
match self {
BagSize::Small => 1024,
BagSize::Medium => 2048,
BagSize::Large => 8192,
BagSize::Larger => 16384,
BagSize::Massive => 262_144,
}
}
}
/// Whether an attribute should be PII-strippable/should be subject to datascrubbers
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Pii {
/// The field will be stripped by default
True,
/// The field cannot be stripped at all
False,
/// The field will only be stripped when addressed with a specific path selector, but generic
/// selectors such as `$string` do not apply.
Maybe,
}
/// Meta information about a field.
#[derive(Debug, Clone, Copy)]
pub struct FieldAttrs {
/// Optionally the name of the field.
pub name: Option<&'static str>,
/// If the field is required.
pub required: bool,
/// If the field should be non-empty.
pub nonempty: bool,
/// Whether to trim whitespace from this string.
pub trim_whitespace: bool,
/// A set of allowed or denied character ranges for this string.
pub characters: Option<CharacterSet>,
/// The maximum char length of this field.
pub max_chars: Option<MaxChars>,
/// The maximum bag size of this field.
pub bag_size: Option<BagSize>,
/// The type of PII on the field.
pub pii: Pii,
/// Whether additional properties should be retained during normalization.
pub retain: bool,
}
/// A set of characters allowed or denied for a (string) field.
///
/// Note that this field is generated in the derive, it can't be constructed easily in tests.
#[derive(Clone, Copy)]
pub struct CharacterSet {
/// Generated in derive for performance. Can be left out when set is created manually.
pub char_is_valid: fn(char) -> bool,
/// A set of ranges that are allowed/denied within the character set
pub ranges: &'static [RangeInclusive<char>],
/// Whether the character set is inverted
pub is_negative: bool,
}
impl fmt::Debug for CharacterSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CharacterSet")
.field("ranges", &self.ranges)
.field("is_negative", &self.is_negative)
.finish()
}
}
impl FieldAttrs {
/// Creates default `FieldAttrs`.
pub const fn new() -> Self {
FieldAttrs {
name: None,
required: false,
nonempty: false,
trim_whitespace: false,
characters: None,
max_chars: None,
bag_size: None,
pii: Pii::False,
retain: false,
}
}
/// Sets whether a value in this field is required.
pub const fn required(mut self, required: bool) -> Self {
self.required = required;
self
}
/// Sets whether this field can have an empty value.
///
/// This is distinct from `required`. An empty string (`""`) passes the "required" check but not the
/// "nonempty" one.
pub const fn nonempty(mut self, nonempty: bool) -> Self {
self.nonempty = nonempty;
self
}
/// Sets whether whitespace should be trimmed before validation.
pub const fn trim_whitespace(mut self, trim_whitespace: bool) -> Self {
self.trim_whitespace = trim_whitespace;
self
}
/// Sets whether this field contains PII.
pub const fn pii(mut self, pii: Pii) -> Self {
self.pii = pii;
self
}
/// Sets the maximum number of characters allowed in the field.
pub const fn max_chars(mut self, max_chars: MaxChars) -> Self {
self.max_chars = Some(max_chars);
self
}
/// Sets the maximum size of all children in this field.
///
/// This applies particularly to objects and arrays, but also to structures.
pub const fn bag_size(mut self, bag_size: BagSize) -> Self {
self.bag_size = Some(bag_size);
self
}
/// Sets whether additional properties should be retained during normalization.
pub const fn retain(mut self, retain: bool) -> Self {
self.retain = retain;
self
}
}
static DEFAULT_FIELD_ATTRS: FieldAttrs = FieldAttrs::new();
static PII_TRUE_FIELD_ATTRS: FieldAttrs = FieldAttrs::new().pii(Pii::True);
static PII_MAYBE_FIELD_ATTRS: FieldAttrs = FieldAttrs::new().pii(Pii::Maybe);
impl Default for FieldAttrs {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Eq, Ord, PartialOrd)]
enum PathItem<'a> {
StaticKey(&'a str),
OwnedKey(String),
Index(usize),
}
impl<'a> PartialEq for PathItem<'a> {
fn eq(&self, other: &PathItem<'a>) -> bool {
self.key() == other.key() && self.index() == other.index()
}
}
impl<'a> PathItem<'a> {
/// Returns the key if there is one
#[inline]
pub fn key(&self) -> Option<&str> {
match self {
PathItem::StaticKey(s) => Some(s),
PathItem::OwnedKey(s) => Some(s.as_str()),
PathItem::Index(_) => None,
}
}
/// Returns the index if there is one
#[inline]
pub fn index(&self) -> Option<usize> {
match self {
PathItem::StaticKey(_) | PathItem::OwnedKey(_) => None,
PathItem::Index(idx) => Some(*idx),
}
}
}
impl<'a> fmt::Display for PathItem<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PathItem::StaticKey(s) => f.pad(s),
PathItem::OwnedKey(s) => f.pad(s.as_str()),
PathItem::Index(val) => write!(f, "{val}"),
}
}
}
/// Like [`std::borrow::Cow`], but with a boxed value.
///
/// This is useful for types that contain themselves, where otherwise the layout of the type
/// cannot be computed, for example
///
/// ```rust,ignore
/// struct Foo<'a>(Cow<'a, Foo<'a>>); // will not compile
/// struct Bar<'a>(BoxCow<'a, Bar<'a>>); // will compile
/// ```
#[derive(Debug, Clone)]
enum BoxCow<'a, T> {
Borrowed(&'a T),
Owned(Box<T>),
}
impl<T> Deref for BoxCow<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match self {
BoxCow::Borrowed(inner) => inner,
BoxCow::Owned(inner) => inner.deref(),
}
}
}
/// An event's processing state.
///
/// The processing state describes an item in an event which is being processed, an example
/// of processing might be scrubbing the event for PII. The processing state itself
/// describes the current item and it's parent, which allows you to follow all the items up
/// to the root item. You can think of processing an event as a visitor pattern visiting
/// all items in the event and the processing state is a stack describing the currently
/// visited item and all it's parents.
///
/// To use a processing state you most likely want to check whether a selector matches the
/// current state. For this you turn the state into a [`Path`] using
/// [`ProcessingState::path`] and call [`Path::matches_selector`] which will iterate through
/// the path items in the processing state and check whether a selector matches.
#[derive(Debug, Clone)]
pub struct ProcessingState<'a> {
// In event scrubbing, every state holds a reference to its parent.
// In Replay scrubbing, we do not call `process_*` recursively,
// but instead hold a single `ProcessingState` that represents the current item.
// This item owns its parent (plus ancestors) exclusively, which is why we use `BoxCow` here
// rather than `Rc` / `Arc`.
parent: Option<BoxCow<'a, ProcessingState<'a>>>,
path_item: Option<PathItem<'a>>,
attrs: Option<Cow<'a, FieldAttrs>>,
value_type: EnumSet<ValueType>,
depth: usize,
}
static ROOT_STATE: ProcessingState = ProcessingState {
parent: None,
path_item: None,
attrs: None,
value_type: enumset::enum_set!(),
depth: 0,
};
impl<'a> ProcessingState<'a> {
/// Returns the root processing state.
pub fn root() -> &'static ProcessingState<'static> {
&ROOT_STATE
}
/// Creates a new root state.
pub fn new_root(
attrs: Option<Cow<'static, FieldAttrs>>,
value_type: impl IntoIterator<Item = ValueType>,
) -> ProcessingState<'static> {
ProcessingState {
parent: None,
path_item: None,
attrs,
value_type: value_type.into_iter().collect(),
depth: 0,
}
}
/// Derives a processing state by entering a static key.
pub fn enter_static(
&'a self,
key: &'static str,
attrs: Option<Cow<'static, FieldAttrs>>,
value_type: impl IntoIterator<Item = ValueType>,
) -> Self {
ProcessingState {
parent: Some(BoxCow::Borrowed(self)),
path_item: Some(PathItem::StaticKey(key)),
attrs,
value_type: value_type.into_iter().collect(),
depth: self.depth + 1,
}
}
/// Derives a processing state by entering a borrowed key.
pub fn enter_borrowed(
&'a self,
key: &'a str,
attrs: Option<Cow<'a, FieldAttrs>>,
value_type: impl IntoIterator<Item = ValueType>,
) -> Self {
ProcessingState {
parent: Some(BoxCow::Borrowed(self)),
path_item: Some(PathItem::StaticKey(key)),
attrs,
value_type: value_type.into_iter().collect(),
depth: self.depth + 1,
}
}
/// Derives a processing state by entering an owned key.
///
/// The new (child) state takes ownership of the current (parent) state.
pub fn enter_owned(
self,
key: String,
attrs: Option<Cow<'a, FieldAttrs>>,
value_type: impl IntoIterator<Item = ValueType>,
) -> Self {
let depth = self.depth + 1;
ProcessingState {
parent: Some(BoxCow::Owned(self.into())),
path_item: Some(PathItem::OwnedKey(key)),
attrs,
value_type: value_type.into_iter().collect(),
depth,
}
}
/// Derives a processing state by entering an index.
pub fn enter_index(
&'a self,
idx: usize,
attrs: Option<Cow<'a, FieldAttrs>>,
value_type: impl IntoIterator<Item = ValueType>,
) -> Self {
ProcessingState {
parent: Some(BoxCow::Borrowed(self)),
path_item: Some(PathItem::Index(idx)),
attrs,
value_type: value_type.into_iter().collect(),
depth: self.depth + 1,
}
}
/// Derives a processing state without adding a path segment. Useful in newtype structs.
pub fn enter_nothing(&'a self, attrs: Option<Cow<'a, FieldAttrs>>) -> Self {
ProcessingState {
attrs,
path_item: None,
parent: Some(BoxCow::Borrowed(self)),
..self.clone()
}
}
/// Returns the path in the processing state.
pub fn path(&'a self) -> Path<'a> {
Path(self)
}
pub fn value_type(&self) -> EnumSet<ValueType> {
self.value_type
}
/// Returns the field attributes.
pub fn attrs(&self) -> &FieldAttrs {
match self.attrs {
Some(ref cow) => cow,
None => &DEFAULT_FIELD_ATTRS,
}
}
/// Derives the attrs for recursion.
pub fn inner_attrs(&self) -> Option<Cow<'_, FieldAttrs>> {
match self.attrs().pii {
Pii::True => Some(Cow::Borrowed(&PII_TRUE_FIELD_ATTRS)),
Pii::False => None,
Pii::Maybe => Some(Cow::Borrowed(&PII_MAYBE_FIELD_ATTRS)),
}
}
/// Iterates through this state and all its ancestors up the hierarchy.
///
/// This starts at the top of the stack of processing states and ends at the root. Thus
/// the first item returned is the currently visited leaf of the event structure.
pub fn iter(&'a self) -> ProcessingStateIter<'a> {
ProcessingStateIter {
state: Some(self),
size: self.depth,
}
}
/// Returns the contained parent state.
///
/// - Returns `Ok(None)` if the current state is the root.
/// - Returns `Err(self)` if the current state does not own the parent state.
pub fn try_into_parent(self) -> Result<Option<Self>, Self> {
match self.parent {
Some(BoxCow::Borrowed(_)) => Err(self),
Some(BoxCow::Owned(parent)) => Ok(Some(*parent)),
None => Ok(None),
}
}
/// Return the depth (~ indentation level) of the currently processed value.
pub fn depth(&'a self) -> usize {
self.depth
}
/// Return whether the depth changed between parent and self.
///
/// This is `false` when we entered a newtype struct.
pub fn entered_anything(&'a self) -> bool {
if let Some(parent) = &self.parent {
parent.depth() != self.depth()
} else {
true
}
}
/// Returns the last path item if there is one. Skips over "dummy" path segments that exist
/// because of newtypes.
#[inline]
fn path_item(&self) -> Option<&PathItem<'_>> {
for state in self.iter() {
if let Some(ref path_item) = state.path_item {
return Some(path_item);
}
}
None
}
}
pub struct ProcessingStateIter<'a> {
state: Option<&'a ProcessingState<'a>>,
size: usize,
}
impl<'a> Iterator for ProcessingStateIter<'a> {
type Item = &'a ProcessingState<'a>;
fn next(&mut self) -> Option<Self::Item> {
let current = self.state?;
self.state = current.parent.as_deref();
Some(current)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.size, Some(self.size))
}
}
impl<'a> ExactSizeIterator for ProcessingStateIter<'a> {}
impl<'a> Default for ProcessingState<'a> {
fn default() -> Self {
ProcessingState::root().clone()
}
}
/// Represents the [`ProcessingState`] as a path.
///
/// This is a view of a [`ProcessingState`] which treats the stack of states as a path. In
/// particular the [`Path::matches_selector`] method allows if a selector matches this path.
#[derive(Debug)]
pub struct Path<'a>(&'a ProcessingState<'a>);
impl<'a> Path<'a> {
/// Returns the current key if there is one
#[inline]
pub fn key(&self) -> Option<&str> {
PathItem::key(self.0.path_item()?)
}
/// Returns the current index if there is one
#[inline]
pub fn index(&self) -> Option<usize> {
PathItem::index(self.0.path_item()?)
}
/// Checks if a path matches given selector.
///
/// This walks both the selector and the path starting at the end and towards the root
/// to determine if the selector matches the current path.
pub fn matches_selector(&self, selector: &SelectorSpec) -> bool {
let pii = self.0.attrs().pii;
if pii == Pii::False {
return false;
}
match *selector {
SelectorSpec::Path(ref path) => {
// fastest path: the selector is deeper than the current structure.
if path.len() > self.0.depth {
return false;
}
// fast path: we do not have any deep matches
let mut state_iter = self.0.iter().filter(|state| state.entered_anything());
let mut selector_iter = path.iter().enumerate().rev();
let mut depth_match = false;
for state in &mut state_iter {
match selector_iter.next() {
Some((i, path_item)) => {
if !path_item.matches_state(pii, i, state) {
return false;
}
if matches!(path_item, SelectorPathItem::DeepWildcard) {
depth_match = true;
break;
}
}
None => break,
}
}
if !depth_match {
return true;
}
// slow path: we collect the remaining states and skip up to the first
// match of the selector.
let remaining_states = state_iter.collect::<SmallVec<[&ProcessingState<'_>; 16]>>();
let mut selector_iter = selector_iter.rev().peekable();
let (first_selector_i, first_selector_path) = match selector_iter.next() {
Some(selector_path) => selector_path,
None => return !remaining_states.is_empty(),
};
let mut path_match_iterator = remaining_states.iter().rev().skip_while(|state| {
!first_selector_path.matches_state(pii, first_selector_i, state)
});
if path_match_iterator.next().is_none() {
return false;
}
// then we check all remaining items and that nothing is left of the selector
path_match_iterator
.zip(&mut selector_iter)
.all(|(state, (i, selector_path))| selector_path.matches_state(pii, i, state))
&& selector_iter.next().is_none()
}
SelectorSpec::And(ref xs) => xs.iter().all(|x| self.matches_selector(x)),
SelectorSpec::Or(ref xs) => xs.iter().any(|x| self.matches_selector(x)),
SelectorSpec::Not(ref x) => !self.matches_selector(x),
}
}
}
impl<'a> fmt::Display for Path<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut items = Vec::with_capacity(self.0.depth);
for state in self.0.iter() {
if let Some(ref path_item) = state.path_item {
items.push(path_item)
}
}
for (idx, item) in items.into_iter().rev().enumerate() {
if idx > 0 {
write!(f, ".")?;
}
write!(f, "{item}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use itertools::Itertools;
use super::*;
macro_rules! assert_matches_raw {
($state:expr, $selector:expr, $expected:expr) => {{
let actual = $state.path().matches_selector(&$selector.parse().unwrap());
assert!(
actual == $expected,
"Matched {} against {}, expected {:?}, actually {:?}",
$selector,
$state.path(),
$expected,
actual
);
}};
}
macro_rules! assert_matches_pii_maybe {
($state:expr, $($selector:expr,)*) => {{
assert_matches_pii_true!($state, $($selector,)*);
let state = &$state;
let state = state.enter_nothing(Some(Cow::Borrowed(&PII_MAYBE_FIELD_ATTRS)));
$(
assert_matches_raw!(state, $selector, true);
)*
let joined = vec![$($selector),*].into_iter().join(" && ");
assert_matches_raw!(state, &joined, true);
let joined = vec![$($selector),*].into_iter().join(" || ");
assert_matches_raw!(state, &joined, true);
let joined = vec!["**", $($selector),*].into_iter().join(" || ");
assert_matches_raw!(state, &joined, true);
}}
}
macro_rules! assert_matches_pii_true {
($state:expr, $($selector:expr,)*) => {{
let state = &$state;
let state = state.enter_nothing(Some(Cow::Borrowed(&PII_TRUE_FIELD_ATTRS)));
$(
assert_matches_raw!(state, $selector, true);
)*
let joined = vec![$($selector),*].into_iter().join(" && ");
assert_matches_raw!(state, &joined, true);
let joined = vec![$($selector),*].into_iter().join(" || ");
assert_matches_raw!(state, &joined, true);
let joined = vec!["**", $($selector),*].into_iter().join(" || ");
assert_matches_raw!(state, &joined, true);
}}
}
macro_rules! assert_not_matches {
($state:expr, $($selector:expr,)*) => {{
let state = &$state;
$(
assert_matches_raw!(state, $selector, false);
)*
}}
}
#[test]
fn test_matching() {
let event_state = ProcessingState::new_root(None, Some(ValueType::Event)); // .
let user_state = event_state.enter_static("user", None, Some(ValueType::User)); // .user
let extra_state = user_state.enter_static("extra", None, Some(ValueType::Object)); // .user.extra
let foo_state = extra_state.enter_static("foo", None, Some(ValueType::Array)); // .user.extra.foo
let zero_state = foo_state.enter_index(0, None, None); // .user.extra.foo.0
assert_matches_pii_maybe!(
extra_state,
"user.extra", // this is an exact match to the state
"$user.extra", // this is a match below a type
"(** || user.*) && !(foo.bar.baz || a.b.c)",
);
assert_matches_pii_true!(
extra_state,
// known limitation: double-negations *could* be specific (I'd expect this as a user), but
// right now we don't support it
"!(!user.extra)",
"!(!$user.extra)",
);
assert_matches_pii_maybe!(
foo_state,
"$user.extra.*", // this is a wildcard match into a type
);
assert_matches_pii_maybe!(
zero_state,
"$user.extra.foo.*", // a wildcard match into an array
"$user.extra.foo.0", // a direct match into an array
);
assert_matches_pii_true!(
zero_state,
// deep matches are wild
"$user.extra.foo.**",
"$user.extra.**",
"$user.**",
"$event.**",
"$user.**.0",
// types are anywhere
"$user.$object.**.0",
"(**.0 | absolutebogus)",
"(~$object)",
"($object.** & (~absolutebogus))",
"($object.** & (~absolutebogus))",
);
assert_not_matches!(
zero_state,
"$user.extra.foo.1", // direct mismatch in an array
// deep matches are wild
"$user.extra.bar.**",
"$user.**.1",
"($object | absolutebogus)",
"($object & absolutebogus)",
"(~$object.**)",
"($object | (**.0 & absolutebogus))",
);
assert_matches_pii_true!(
foo_state,
"($array & $object.*)",
"(** & $object.*)",
"**.$array",
);
assert_not_matches!(foo_state, "($object & $object.*)",);
}
#[test]
fn test_attachments_matching() {
let event_state = ProcessingState::new_root(None, None);
let attachments_state = event_state.enter_static("", None, Some(ValueType::Attachments)); // .
let txt_state = attachments_state.enter_static("file.txt", None, Some(ValueType::Binary)); // .'file.txt'
let minidump_state =
attachments_state.enter_static("file.dmp", None, Some(ValueType::Minidump)); // .'file.txt'
let minidump_state_inner = minidump_state.enter_static("", None, Some(ValueType::Binary)); // .'file.txt'
assert_matches_pii_maybe!(attachments_state, "$attachments",);
assert_matches_pii_maybe!(txt_state, "$attachments.'file.txt'",);
assert_matches_pii_true!(txt_state, "$binary",);
// WAT. All entire attachments are binary, so why not be able to select them (specific)
// like this? Especially since we can select them with wildcard.
assert_matches_pii_true!(txt_state, "$attachments.$binary",);
// WAT. This is not problematic but rather... weird?
assert_matches_pii_maybe!(txt_state, "$attachments.*",);
assert_matches_pii_true!(txt_state, "$attachments.**",);
assert_matches_pii_maybe!(minidump_state, "$minidump",);
// WAT. This should not behave differently from plain $minidump
assert_matches_pii_true!(minidump_state, "$attachments.$minidump",);
// WAT. We have the full path to a field here.
assert_matches_pii_true!(minidump_state_inner, "$attachments.$minidump.$binary",);
}
}