Skip to main content

relay_filter/
generic.rs

1//! Implements generic filtering based on the [`RuleCondition`] DSL.
2//!
3//! Multiple generic filters can be defined and they are going to be checked in FIFO order. The
4//! first one that matches, will result in the event being discarded with a [`FilterStatKey`]
5//! identifying the matching filter.
6
7use std::iter::FusedIterator;
8use std::net::IpAddr;
9
10use crate::{FilterStatKey, GenericFilterConfig, GenericFiltersConfig, GenericFiltersMap};
11
12use relay_protocol::{Getter, GetterIter, RuleCondition, Val};
13
14/// Path under which conditions read the IP address of the client that sent the envelope.
15///
16/// This is the same address the `clientIps` filter uses, not the user IP stored in the item.
17const CLIENT_IP_PATH: &str = "envelope.client_ip";
18
19/// An item together with the envelope data that conditions can reference.
20///
21/// Fields of the item resolve through its own [`Getter`]. [`CLIENT_IP_PATH`] resolves to the
22/// client IP of the envelope, which no item type carries itself.
23struct WithClientIp<'a, F> {
24    item: &'a F,
25    client_ip: Option<IpAddr>,
26}
27
28impl<F: Getter> Getter for WithClientIp<'_, F> {
29    fn get_value(&self, path: &str) -> Option<Val<'_>> {
30        match path {
31            CLIENT_IP_PATH => self.client_ip.map(Val::IpAddr),
32            other => self.item.get_value(other),
33        }
34    }
35
36    fn get_iter(&self, path: &str) -> Option<GetterIter<'_>> {
37        self.item.get_iter(path)
38    }
39}
40
41/// Maximum supported version of the generic filters schema.
42///
43/// If the version in the project config is higher, no generic filters are applied.
44const MAX_SUPPORTED_VERSION: u16 = 1;
45
46/// Returns whether the given generic config versions are supported.
47pub fn are_generic_filters_supported(
48    global_filters_version: Option<u16>,
49    project_filters_version: u16,
50) -> bool {
51    global_filters_version.is_none_or(|v| v <= MAX_SUPPORTED_VERSION)
52        && project_filters_version <= MAX_SUPPORTED_VERSION
53}
54
55/// Checks events by patterns in their error messages.
56fn matches<F: Getter>(item: &F, condition: Option<&RuleCondition>) -> bool {
57    // TODO: the condition DSL needs to be extended to support more complex semantics, such as
58    //  collections operations.
59    condition.is_some_and(|condition| condition.matches(item))
60}
61
62/// Filters events by any generic condition.
63///
64/// Note that conditions may have type-specific getter strings, e.g. `"event.some_field"`. In order
65/// to make such a generic filter apply to non-Event types, make sure that the [`Getter`] implementation
66/// for that type maps `"event.some_field"` to the corresponding field on that type.
67///
68/// Conditions can also read `envelope.client_ip`, the IP address of the client that sent the
69/// envelope, for every item type.
70pub(crate) fn should_filter<F: Getter>(
71    item: &F,
72    client_ip: Option<IpAddr>,
73    project_filters: &GenericFiltersConfig,
74    global_filters: Option<&GenericFiltersConfig>,
75) -> Result<(), FilterStatKey> {
76    let item = WithClientIp { item, client_ip };
77    let filters = merge_generic_filters(
78        project_filters,
79        global_filters,
80        #[cfg(test)]
81        MAX_SUPPORTED_VERSION,
82    );
83
84    for filter_config in filters {
85        if filter_config.is_enabled && matches(&item, filter_config.condition) {
86            return Err(FilterStatKey::GenericFilter(filter_config.id.to_owned()));
87        }
88    }
89
90    Ok(())
91}
92
93/// Returns an iterator that yields merged generic configs.
94///
95/// Since filters of project and global configs are complementary and don't
96/// provide much value in isolation, both versions must match
97/// [`MAX_SUPPORTED_VERSION`] to be compatible.  If filters aren't compatible,
98/// an empty iterator is returned.
99///
100/// If filters are compatible, an iterator over all filters is returned. This
101/// iterator yields filters according to the principles below:
102/// - Filters from project configs are evaluated before filters from global
103///   configs.
104/// - No duplicates: once a filter is evaluated (yielded or skipped), no filter
105///   with the same id is evaluated again.
106/// - If a filter with the same id exists in projects and global configs, both
107///   are merged and the filter is yielded. Values from the filter in the project
108///   config are prioritized.
109fn merge_generic_filters<'a>(
110    project: &'a GenericFiltersConfig,
111    global: Option<&'a GenericFiltersConfig>,
112    #[cfg(test)] max_supported_version: u16,
113) -> impl Iterator<Item = GenericFilterConfigRef<'a>> {
114    #[cfg(not(test))]
115    let max_supported_version = MAX_SUPPORTED_VERSION;
116
117    let is_supported = project.version <= max_supported_version
118        && global.is_none_or(|gf| gf.version <= max_supported_version);
119
120    is_supported
121        .then(|| {
122            DynamicGenericFiltersConfigIter::new(&project.filters, global.map(|gc| &gc.filters))
123        })
124        .into_iter()
125        .flatten()
126}
127
128/// Iterator over the generic filters of the project and global configs.
129struct DynamicGenericFiltersConfigIter<'a> {
130    /// Generic project filters.
131    project: &'a GenericFiltersMap,
132    /// Index of the next filter in project configs to evaluate.
133    project_index: usize,
134    /// Generic global filters.
135    global: Option<&'a GenericFiltersMap>,
136    /// Index of the next filter in global configs to evaluate.
137    global_index: usize,
138}
139
140impl<'a> DynamicGenericFiltersConfigIter<'a> {
141    pub fn new(project: &'a GenericFiltersMap, global: Option<&'a GenericFiltersMap>) -> Self {
142        DynamicGenericFiltersConfigIter {
143            project,
144            project_index: 0,
145            global,
146            global_index: 0,
147        }
148    }
149}
150
151impl<'a> Iterator for DynamicGenericFiltersConfigIter<'a> {
152    type Item = GenericFilterConfigRef<'a>;
153
154    fn next(&mut self) -> Option<Self::Item> {
155        if let Some((id, filter)) = self.project.get_index(self.project_index) {
156            self.project_index += 1;
157            let merged = merge_filters(filter, self.global.and_then(|gf| gf.get(id)));
158            return Some(merged);
159        }
160
161        loop {
162            let (id, filter) = self.global?.get_index(self.global_index)?;
163            self.global_index += 1;
164            if !self.project.contains_key(id) {
165                return Some(filter.into());
166            }
167        }
168    }
169}
170
171impl FusedIterator for DynamicGenericFiltersConfigIter<'_> {}
172
173/// Merges the two filters with the same id, prioritizing values from the primary.
174///
175/// It's assumed both filters share the same id. The returned filter will have
176/// the primary filter's ID.
177fn merge_filters<'a>(
178    primary: &'a GenericFilterConfig,
179    secondary: Option<&'a GenericFilterConfig>,
180) -> GenericFilterConfigRef<'a> {
181    GenericFilterConfigRef {
182        id: primary.id.as_str(),
183        is_enabled: primary.is_enabled,
184        condition: primary
185            .condition
186            .as_ref()
187            .or(secondary.and_then(|filter| filter.condition.as_ref())),
188    }
189}
190
191#[derive(Debug, Default, PartialEq)]
192struct GenericFilterConfigRef<'a> {
193    id: &'a str,
194    is_enabled: bool,
195    condition: Option<&'a RuleCondition>,
196}
197
198impl<'a> From<&'a GenericFilterConfig> for GenericFilterConfigRef<'a> {
199    fn from(value: &'a GenericFilterConfig) -> Self {
200        GenericFilterConfigRef {
201            id: value.id.as_str(),
202            is_enabled: value.is_enabled,
203            condition: value.condition.as_ref(),
204        }
205    }
206}
207
208#[cfg(test)]
209mod tests {
210
211    use super::*;
212
213    use relay_event_schema::protocol::{Event, LenientString, SessionAggregates, SessionUpdate};
214    use relay_protocol::{Annotated, FromValue as _};
215
216    fn mock_filters() -> GenericFiltersMap {
217        vec![
218            GenericFilterConfig {
219                id: "firstReleases".to_owned(),
220                is_enabled: true,
221                condition: Some(RuleCondition::eq("event.release", "1.0")),
222            },
223            GenericFilterConfig {
224                id: "helloTransactions".to_owned(),
225                is_enabled: true,
226                condition: Some(RuleCondition::eq("event.transaction", "/hello")),
227            },
228        ]
229        .into()
230    }
231
232    #[test]
233    fn test_should_filter_match_rules() {
234        let config = GenericFiltersConfig {
235            version: 1,
236            filters: mock_filters(),
237        };
238
239        // Matching first rule.
240        let event = Event {
241            release: Annotated::new(LenientString("1.0".to_owned())),
242            ..Default::default()
243        };
244        assert_eq!(
245            should_filter(&event, None, &config, None),
246            Err(FilterStatKey::GenericFilter("firstReleases".to_owned()))
247        );
248
249        // Matching second rule.
250        let event = Event {
251            transaction: Annotated::new("/hello".to_owned()),
252            ..Default::default()
253        };
254        assert_eq!(
255            should_filter(&event, None, &config, None),
256            Err(FilterStatKey::GenericFilter("helloTransactions".to_owned()))
257        );
258    }
259
260    #[test]
261    fn test_should_filter_fifo_match_rules() {
262        let config = GenericFiltersConfig {
263            version: 1,
264            filters: mock_filters(),
265        };
266
267        // Matching both rules (first is taken).
268        let event = Event {
269            release: Annotated::new(LenientString("1.0".to_owned())),
270            transaction: Annotated::new("/hello".to_owned()),
271            ..Default::default()
272        };
273        assert_eq!(
274            should_filter(&event, None, &config, None),
275            Err(FilterStatKey::GenericFilter("firstReleases".to_owned()))
276        );
277    }
278
279    #[test]
280    fn test_should_filter_match_no_rules() {
281        let config = GenericFiltersConfig {
282            version: 1,
283            filters: mock_filters(),
284        };
285
286        // Matching no rule.
287        let event = Event {
288            transaction: Annotated::new("/world".to_owned()),
289            ..Default::default()
290        };
291        assert_eq!(should_filter(&event, None, &config, None), Ok(()));
292    }
293
294    #[test]
295    fn test_should_filter_with_higher_config_version() {
296        let config = GenericFiltersConfig {
297            // We simulate receiving a higher configuration version, which we don't support.
298            version: MAX_SUPPORTED_VERSION + 1,
299            filters: mock_filters(),
300        };
301
302        let event = Event {
303            release: Annotated::new(LenientString("1.0".to_owned())),
304            transaction: Annotated::new("/hello".to_owned()),
305            ..Default::default()
306        };
307        assert_eq!(should_filter(&event, None, &config, None), Ok(()));
308    }
309
310    #[test]
311    fn test_should_filter_from_global_filters() {
312        let project = GenericFiltersConfig {
313            version: 1,
314            filters: vec![GenericFilterConfig {
315                id: "firstReleases".to_owned(),
316                is_enabled: true,
317                condition: Some(RuleCondition::eq("event.release", "1.0")),
318            }]
319            .into(),
320        };
321
322        let global = GenericFiltersConfig {
323            version: 1,
324            filters: vec![GenericFilterConfig {
325                id: "helloTransactions".to_owned(),
326                is_enabled: true,
327                condition: Some(RuleCondition::eq("event.transaction", "/hello")),
328            }]
329            .into(),
330        };
331
332        let event = Event {
333            transaction: Annotated::new("/hello".to_owned()),
334            ..Default::default()
335        };
336
337        assert_eq!(
338            should_filter(&event, None, &project, Some(&global)),
339            Err(FilterStatKey::GenericFilter("helloTransactions".to_owned()))
340        );
341    }
342
343    #[test]
344    fn test_should_filter_by_client_ip() {
345        let config = GenericFiltersConfig {
346            version: 1,
347            filters: vec![GenericFilterConfig {
348                id: "blockedIps".to_owned(),
349                is_enabled: true,
350                condition: Some(RuleCondition::cidr(
351                    "envelope.client_ip",
352                    &["10.0.0.0/8", "2001:db8::1"][..],
353                )),
354            }]
355            .into(),
356        };
357
358        let event = Event::default();
359
360        let inside_range = Some("10.1.2.3".parse().unwrap());
361        assert_eq!(
362            should_filter(&event, inside_range, &config, None),
363            Err(FilterStatKey::GenericFilter("blockedIps".to_owned()))
364        );
365
366        let exact_v6 = Some("2001:db8::1".parse().unwrap());
367        assert_eq!(
368            should_filter(&event, exact_v6, &config, None),
369            Err(FilterStatKey::GenericFilter("blockedIps".to_owned()))
370        );
371
372        let outside_range = Some("192.168.0.1".parse().unwrap());
373        assert_eq!(should_filter(&event, outside_range, &config, None), Ok(()));
374
375        assert_eq!(should_filter(&event, None, &config, None), Ok(()));
376    }
377
378    #[test]
379    fn test_client_ip_does_not_shadow_item_fields() {
380        let config = GenericFiltersConfig {
381            version: 1,
382            filters: vec![GenericFilterConfig {
383                id: "releaseAndIp".to_owned(),
384                is_enabled: true,
385                condition: Some(
386                    RuleCondition::eq("event.release", "1.0")
387                        & RuleCondition::cidr("envelope.client_ip", "10.0.0.0/8"),
388                ),
389            }]
390            .into(),
391        };
392
393        let client_ip = Some("10.1.2.3".parse().unwrap());
394
395        let event = Event {
396            release: Annotated::new(LenientString("1.0".to_owned())),
397            ..Default::default()
398        };
399        assert_eq!(
400            should_filter(&event, client_ip, &config, None),
401            Err(FilterStatKey::GenericFilter("releaseAndIp".to_owned()))
402        );
403
404        let event = Event {
405            release: Annotated::new(LenientString("2.0".to_owned())),
406            ..Default::default()
407        };
408        assert_eq!(should_filter(&event, client_ip, &config, None), Ok(()));
409    }
410
411    fn empty_filter() -> GenericFiltersConfig {
412        GenericFiltersConfig {
413            version: 1,
414            filters: GenericFiltersMap::new(),
415        }
416    }
417
418    /// Returns a complete and enabled [`GenericFiltersConfig`].
419    fn enabled_filter(id: &str) -> GenericFiltersConfig {
420        GenericFiltersConfig {
421            version: 1,
422            filters: vec![GenericFilterConfig {
423                id: id.to_owned(),
424                is_enabled: true,
425                condition: Some(RuleCondition::eq("event.exceptions", "myError")),
426            }]
427            .into(),
428        }
429    }
430
431    /// Returns an enabled flag of a [`GenericFiltersConfig`].
432    fn enabled_flag_filter(id: &str) -> GenericFiltersConfig {
433        GenericFiltersConfig {
434            version: 1,
435            filters: vec![GenericFilterConfig {
436                id: id.to_owned(),
437                is_enabled: true,
438                condition: None,
439            }]
440            .into(),
441        }
442    }
443
444    /// Returns a complete but disabled [`GenericFiltersConfig`].
445    fn disabled_filter(id: &str) -> GenericFiltersConfig {
446        GenericFiltersConfig {
447            version: 1,
448            filters: vec![GenericFilterConfig {
449                id: id.to_owned(),
450                is_enabled: false,
451                condition: Some(RuleCondition::eq("event.exceptions", "myError")),
452            }]
453            .into(),
454        }
455    }
456
457    /// Returns a disabled flag of a [`GenericFiltersConfig`].
458    fn disabled_flag_filter(id: &str) -> GenericFiltersConfig {
459        GenericFiltersConfig {
460            version: 1,
461            filters: vec![GenericFilterConfig {
462                id: id.to_owned(),
463                is_enabled: false,
464                condition: None,
465            }]
466            .into(),
467        }
468    }
469
470    #[test]
471    fn test_no_combined_when_unsupported_project_version() {
472        let mut project = enabled_filter("unsupported-project");
473        project.version = 2;
474        let global = enabled_filter("supported-global");
475        assert!(merge_generic_filters(&project, Some(&global), 1).eq(None.into_iter()));
476    }
477
478    #[test]
479    fn test_no_combined_when_unsupported_project_version_no_global() {
480        let mut project = enabled_filter("unsupported-project");
481        project.version = 2;
482        assert!(merge_generic_filters(&project, None, 1).eq(None.into_iter()));
483    }
484
485    #[test]
486    fn test_no_combined_when_unsupported_global_version() {
487        let project = enabled_filter("supported-project");
488        let mut global = enabled_filter("unsupported-global");
489        global.version = 2;
490        assert!(merge_generic_filters(&project, Some(&global), 1).eq(None.into_iter()));
491    }
492
493    #[test]
494    fn test_no_combined_when_unsupported_project_and_global_version() {
495        let mut project = enabled_filter("unsupported-project");
496        project.version = 2;
497        let mut global = enabled_filter("unsupported-global");
498        global.version = 2;
499        assert!(merge_generic_filters(&project, Some(&global), 1).eq(None.into_iter()));
500    }
501
502    #[test]
503    fn test_both_combined_when_supported_project_and_global_version() {
504        let project = enabled_filter("supported-project");
505        let global = enabled_filter("supported-global");
506        assert!(
507            merge_generic_filters(&project, Some(&global), 1).eq([
508                project.filters.first().unwrap().1.into(),
509                global.filters.first().unwrap().1.into()
510            ]
511            .into_iter())
512        );
513    }
514
515    #[test]
516    fn test_project_combined_when_duplicated_filter_project_and_global() {
517        let project = enabled_filter("filter");
518        let global = enabled_filter("filter");
519        assert!(
520            merge_generic_filters(&project, Some(&global), 1).eq([project
521                .filters
522                .first()
523                .unwrap()
524                .1
525                .into()]
526            .into_iter())
527        );
528    }
529
530    #[test]
531    fn test_no_combined_when_empty_project_and_global() {
532        let project = empty_filter();
533        let global = empty_filter();
534        assert!(merge_generic_filters(&project, Some(&global), 1).eq(None.into_iter()));
535    }
536
537    #[test]
538    fn test_global_combined_when_empty_project_disabled_global_filter() {
539        let project = empty_filter();
540        let global = disabled_filter("disabled-global");
541        assert!(
542            merge_generic_filters(&project, Some(&global), 1).eq([global
543                .filters
544                .first()
545                .unwrap()
546                .1
547                .into()]
548            .into_iter())
549        );
550    }
551
552    #[test]
553    fn test_global_combined_when_empty_project_enabled_global_filters() {
554        let project = empty_filter();
555        let global = enabled_filter("enabled-global");
556        assert!(
557            merge_generic_filters(&project, Some(&global), 1).eq([global
558                .filters
559                .first()
560                .unwrap()
561                .1
562                .into()]
563            .into_iter())
564        );
565    }
566
567    #[test]
568    fn test_global_combined_when_empty_project_enabled_flag_global() {
569        let project = empty_filter();
570        let global = enabled_flag_filter("skip");
571        assert!(
572            merge_generic_filters(&project, Some(&global), 1).eq([global
573                .filters
574                .first()
575                .unwrap()
576                .1
577                .into()])
578        );
579    }
580
581    #[test]
582    fn test_project_combined_when_disabled_project_empty_global() {
583        let project = disabled_filter("disabled-project");
584        let global = empty_filter();
585        assert!(
586            merge_generic_filters(&project, Some(&global), 1).eq([project
587                .filters
588                .first()
589                .unwrap()
590                .1
591                .into()]
592            .into_iter())
593        );
594    }
595
596    #[test]
597    fn test_project_combined_when_disabled_project_missing_global() {
598        let project = disabled_filter("disabled-project");
599        assert!(
600            merge_generic_filters(&project, None, 1).eq([project
601                .filters
602                .first()
603                .unwrap()
604                .1
605                .into(),]
606            .into_iter())
607        );
608    }
609
610    #[test]
611    fn test_both_combined_when_different_disabled_project_and_global() {
612        let project = disabled_filter("disabled-project");
613        let global = disabled_filter("disabled-global");
614        assert!(merge_generic_filters(&project, Some(&global), 1).eq([
615            project.filters.first().unwrap().1.into(),
616            global.filters.first().unwrap().1.into()
617        ]));
618    }
619
620    #[test]
621    fn test_project_combined_duplicated_disabled_project_and_global() {
622        let project = disabled_filter("filter");
623        let global = disabled_filter("filter");
624        assert!(
625            merge_generic_filters(&project, Some(&global), 1).eq([project
626                .filters
627                .first()
628                .unwrap()
629                .1
630                .into()])
631        );
632    }
633
634    #[test]
635    fn test_merged_combined_when_disabled_project_enabled_global() {
636        let project = disabled_filter("filter");
637        let global = enabled_filter("filter");
638        let expected = &GenericFilterConfig {
639            id: "filter".to_owned(),
640            is_enabled: false,
641            condition: global.filters.first().unwrap().1.condition.clone(),
642        };
643        assert!(
644            merge_generic_filters(&project, Some(&global), 1).eq([expected.into()].into_iter())
645        );
646    }
647
648    #[test]
649    fn test_no_combined_when_enabled_flag_project_empty_global() {
650        let project = enabled_flag_filter("filter");
651        let global = empty_filter();
652        assert!(
653            merge_generic_filters(&project, Some(&global), 1).eq([project
654                .filters
655                .first()
656                .unwrap()
657                .1
658                .into()]
659            .into_iter())
660        );
661    }
662
663    #[test]
664    fn test_project_combined_when_enabled_flag_project_missing_global() {
665        let project = enabled_flag_filter("filter");
666        assert!(
667            merge_generic_filters(&project, None, 1).eq([project
668                .filters
669                .first()
670                .unwrap()
671                .1
672                .into()]
673            .into_iter())
674        );
675    }
676
677    #[test]
678    fn test_project_combined_when_disabled_flag_project_empty_global() {
679        let project = disabled_flag_filter("filter");
680        let global = empty_filter();
681        assert!(
682            merge_generic_filters(&project, Some(&global), 1).eq([project
683                .filters
684                .first()
685                .unwrap()
686                .1
687                .into()])
688        );
689    }
690
691    #[test]
692    fn test_project_combined_when_disabled_flag_project_missing_global() {
693        let project = disabled_flag_filter("filter");
694        assert!(
695            merge_generic_filters(&project, None, 1).eq([project
696                .filters
697                .first()
698                .unwrap()
699                .1
700                .into()])
701        );
702    }
703
704    #[test]
705    fn test_project_combined_when_enabled_project_empty_global() {
706        let project = enabled_filter("enabled-project");
707        let global = empty_filter();
708        assert!(
709            merge_generic_filters(&project, Some(&global), 1).eq([project
710                .filters
711                .first()
712                .unwrap()
713                .1
714                .into()]
715            .into_iter())
716        );
717    }
718
719    #[test]
720    fn test_project_combined_when_enabled_project_missing_global() {
721        let project = enabled_filter("enabled-project");
722        assert!(
723            merge_generic_filters(&project, None, 1).eq([project
724                .filters
725                .first()
726                .unwrap()
727                .1
728                .into()]
729            .into_iter())
730        );
731    }
732
733    #[test]
734    fn test_merged_combined_when_enabled_flag_project_disabled_global() {
735        let project = enabled_flag_filter("filter");
736        let global = disabled_filter("filter");
737        let expected = &GenericFilterConfig {
738            id: "filter".to_owned(),
739            is_enabled: true,
740            condition: global.filters.first().unwrap().1.condition.clone(),
741        };
742        assert!(
743            merge_generic_filters(&project, Some(&global), 1).eq([expected.into()].into_iter())
744        );
745    }
746
747    #[test]
748    fn test_global_combined_when_disabled_flag_project_disabled_global() {
749        let project = disabled_flag_filter("filter");
750        let global = disabled_filter("filter");
751        assert!(
752            merge_generic_filters(&project, Some(&global), 1).eq([global
753                .filters
754                .first()
755                .unwrap()
756                .1
757                .into()])
758        );
759    }
760
761    #[test]
762    fn test_project_combined_when_enabled_project_disabled_global() {
763        let project = enabled_filter("filter");
764        let global = disabled_filter("filter");
765        assert!(
766            merge_generic_filters(&project, Some(&global), 1).eq([project
767                .filters
768                .first()
769                .unwrap()
770                .1
771                .into()]
772            .into_iter())
773        );
774    }
775
776    #[test]
777    fn test_global_combined_when_enabled_flag_project_enabled_global() {
778        let project = enabled_flag_filter("filter");
779        let global = enabled_filter("filter");
780        assert!(
781            merge_generic_filters(&project, Some(&global), 1).eq([global
782                .filters
783                .first()
784                .unwrap()
785                .1
786                .into()]
787            .into_iter())
788        );
789    }
790
791    #[test]
792    fn test_merged_combined_when_disabled_flag_project_enabled_global() {
793        let project = disabled_flag_filter("filter");
794        let global = enabled_filter("filter");
795        let expected = &GenericFilterConfig {
796            id: "filter".to_owned(),
797            is_enabled: false,
798            condition: global.filters.first().unwrap().1.condition.clone(),
799        };
800        assert!(
801            merge_generic_filters(&project, Some(&global), 1).eq([expected.into()].into_iter())
802        );
803    }
804
805    #[test]
806    fn test_project_combined_when_enabled_project_enabled_flag_global() {
807        let project = enabled_filter("filter");
808        let global = enabled_flag_filter("filter");
809        assert!(
810            merge_generic_filters(&project, Some(&global), 1).eq([project
811                .filters
812                .first()
813                .unwrap()
814                .1
815                .into()]
816            .into_iter())
817        );
818    }
819
820    #[test]
821    fn test_project_combined_when_enabled_flags_project_and_global() {
822        let project = enabled_flag_filter("filter");
823        let global = enabled_flag_filter("filter");
824        assert!(
825            merge_generic_filters(&project, Some(&global), 1).eq([project
826                .filters
827                .first()
828                .unwrap()
829                .1
830                .into()]
831            .into_iter())
832        );
833    }
834
835    #[test]
836    fn test_multiple_combined_filters() {
837        let project = GenericFiltersConfig {
838            version: 1,
839            filters: vec![
840                GenericFilterConfig {
841                    id: "0".to_owned(),
842                    is_enabled: true,
843                    condition: Some(RuleCondition::eq("event.exceptions", "myError")),
844                },
845                GenericFilterConfig {
846                    id: "1".to_owned(),
847                    is_enabled: true,
848                    condition: None,
849                },
850                GenericFilterConfig {
851                    id: "2".to_owned(),
852                    is_enabled: true,
853                    condition: Some(RuleCondition::eq("event.exceptions", "myError")),
854                },
855            ]
856            .into(),
857        };
858        let global = GenericFiltersConfig {
859            version: 1,
860            filters: vec![
861                GenericFilterConfig {
862                    id: "1".to_owned(),
863                    is_enabled: false,
864                    condition: Some(RuleCondition::eq("event.exceptions", "myOtherError")),
865                },
866                GenericFilterConfig {
867                    id: "3".to_owned(),
868                    is_enabled: false,
869                    condition: Some(RuleCondition::eq("event.exceptions", "myLastError")),
870                },
871            ]
872            .into(),
873        };
874
875        let expected0 = &project.filters[0];
876        let expected1 = &GenericFilterConfig {
877            id: "1".to_owned(),
878            is_enabled: true,
879            condition: Some(RuleCondition::eq("event.exceptions", "myOtherError")),
880        };
881        let expected2 = &project.filters[2];
882        let expected3 = &global.filters[1];
883
884        assert!(
885            merge_generic_filters(&project, Some(&global), 1).eq([
886                expected0.into(),
887                expected1.into(),
888                expected2.into(),
889                expected3.into()
890            ]
891            .into_iter())
892        );
893    }
894
895    #[test]
896    fn test_os_name_not_filter() {
897        let config = GenericFiltersConfig {
898            version: 1,
899            filters: vec![GenericFilterConfig {
900                id: "os_name".to_owned(),
901                is_enabled: true,
902                condition: Some(RuleCondition::eq("event.contexts.os.name", "fooBar").negate()),
903            }]
904            .into(),
905        };
906
907        let cases = [("fooBar", false), ("foobar", true), ("other", true)];
908        for (name, filters) in cases {
909            let event = Event::from_value(
910                serde_json::json!({
911                    "contexts": {
912                        "os": {
913                            "name": name,
914                        },
915                    },
916                })
917                .into(),
918            );
919
920            let expected = if filters {
921                Err(FilterStatKey::GenericFilter("os_name".to_owned()))
922            } else {
923                Ok(())
924            };
925
926            assert_eq!(
927                should_filter(event.value().unwrap(), None, &config, None),
928                expected
929            );
930        }
931    }
932
933    /// The catch-all release filter Sentry emits: an `or` over the release path of every data type.
934    fn catch_all_release_filter(release: &str) -> GenericFiltersConfig {
935        let condition = RuleCondition::glob("event.release", release)
936            .or(RuleCondition::glob(
937                "log.attributes.sentry.release.value",
938                release,
939            ))
940            .or(RuleCondition::glob(
941                "trace_metric.attributes.sentry.release.value",
942                release,
943            ));
944
945        GenericFiltersConfig {
946            version: 1,
947            filters: vec![GenericFilterConfig {
948                id: "catchAllRelease".to_owned(),
949                is_enabled: true,
950                condition: Some(condition),
951            }]
952            .into(),
953        }
954    }
955
956    fn session_update(release: &str) -> SessionUpdate {
957        SessionUpdate::parse(
958            format!(
959                r#"{{"started": "2020-02-07T14:16:00Z", "attrs": {{"release": "{release}"}}}}"#
960            )
961            .as_bytes(),
962        )
963        .unwrap()
964    }
965
966    fn session_aggregates(release: &str) -> SessionAggregates {
967        SessionAggregates::parse(
968            format!(
969                r#"{{"aggregates": [{{"started": "2020-02-07T14:16:00Z", "exited": 2}}], "attrs": {{"release": "{release}"}}}}"#
970            )
971            .as_bytes(),
972        )
973        .unwrap()
974    }
975
976    #[test]
977    fn test_should_filter_session_by_release() {
978        let config = catch_all_release_filter("1.0.0");
979
980        assert_eq!(
981            should_filter(&session_update("1.0.0"), None, &config, None),
982            Err(FilterStatKey::GenericFilter("catchAllRelease".to_owned()))
983        );
984        assert_eq!(
985            should_filter(&session_aggregates("1.0.0"), None, &config, None),
986            Err(FilterStatKey::GenericFilter("catchAllRelease".to_owned()))
987        );
988
989        assert_eq!(
990            should_filter(&session_update("2.0.0"), None, &config, None),
991            Ok(())
992        );
993        assert_eq!(
994            should_filter(&session_aggregates("2.0.0"), None, &config, None),
995            Ok(())
996        );
997    }
998
999    /// A filter that only lists other data types' release paths must never match a session.
1000    #[test]
1001    fn test_should_not_filter_session_by_foreign_release_path() {
1002        let config = GenericFiltersConfig {
1003            version: 1,
1004            filters: vec![GenericFilterConfig {
1005                id: "otherTypesOnly".to_owned(),
1006                is_enabled: true,
1007                condition: Some(
1008                    RuleCondition::glob("log.attributes.sentry.release.value", "1.0.0").or(
1009                        RuleCondition::glob(
1010                            "trace_metric.attributes.sentry.release.value",
1011                            "1.0.0",
1012                        ),
1013                    ),
1014                ),
1015            }]
1016            .into(),
1017        };
1018
1019        assert_eq!(
1020            should_filter(&session_update("1.0.0"), None, &config, None),
1021            Ok(())
1022        );
1023        assert_eq!(
1024            should_filter(&session_aggregates("1.0.0"), None, &config, None),
1025            Ok(())
1026        );
1027    }
1028}