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
//! Implements filtering for events originating from the localhost

use crate::{FilterConfig, FilterStatKey, Filterable};

const LOCAL_IPS: &[&str] = &["127.0.0.1", "::1"];
const LOCAL_DOMAINS: &[&str] = &["127.0.0.1", "localhost"];

/// Check if the event originates from the local host.
fn matches<F: Filterable>(item: &F) -> bool {
    if let Some(ip_addr) = item.ip_addr() {
        for &local_ip in LOCAL_IPS {
            if local_ip == ip_addr {
                return true;
            }
        }
    }

    if let Some(url) = item.url() {
        if url.scheme() == "file" {
            return true;
        }

        if let Some(host) = url.host_str() {
            for &local_domain in LOCAL_DOMAINS {
                if host_matches_or_is_subdomain_of(host, local_domain) {
                    return true;
                }
            }
        }
    }

    false
}

fn host_matches_or_is_subdomain_of(host: &str, domain: &str) -> bool {
    host.strip_suffix(domain)
        .map_or(false, |s| s.is_empty() || s.ends_with('.'))
}

/// Filters events originating from the local host.
pub fn should_filter<F: Filterable>(item: &F, config: &FilterConfig) -> Result<(), FilterStatKey> {
    if !config.is_enabled {
        return Ok(());
    }
    if matches(item) {
        return Err(FilterStatKey::Localhost);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use relay_event_schema::protocol::{Event, IpAddr, Request, User};
    use relay_protocol::Annotated;

    use super::*;

    fn get_event_with_ip_addr(val: &str) -> Event {
        Event {
            user: Annotated::from(User {
                ip_address: Annotated::from(IpAddr(val.to_string())),
                ..User::default()
            }),
            ..Event::default()
        }
    }

    fn get_event_with_domain(val: &str) -> Event {
        Event {
            request: Annotated::from(Request {
                url: Annotated::from(format!("http://{val}:8080/")),
                ..Request::default()
            }),
            ..Event::default()
        }
    }

    fn get_event_with_url(val: &str) -> Event {
        Event {
            request: Annotated::from(Request {
                url: Annotated::from(val.to_string()),
                ..Request::default()
            }),
            ..Event::default()
        }
    }

    #[test]
    fn test_dont_filter_when_disabled() {
        for event in &[
            get_event_with_ip_addr("127.0.0.1"),
            get_event_with_domain("localhost"),
        ] {
            let filter_result = should_filter(event, &FilterConfig { is_enabled: false });
            assert_eq!(
                filter_result,
                Ok(()),
                "Event filtered although filter should have been disabled."
            );
        }
    }

    #[test]
    fn test_filter_local_ip() {
        for ip_addr in &["127.0.0.1", "::1"] {
            let event = get_event_with_ip_addr(ip_addr);
            let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
            assert_ne!(
                filter_result,
                Ok(()),
                "Failed to filter address '{ip_addr}'"
            );
        }
    }

    #[test]
    fn test_dont_filter_non_local_ip() {
        for ip_addr in &["133.12.12.1", "2001:db8:0:0:0:ff00:42:8329"] {
            let event = get_event_with_ip_addr(ip_addr);
            let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
            assert_eq!(
                filter_result,
                Ok(()),
                "Filtered valid ip address '{ip_addr}'"
            );
        }
    }

    #[test]
    fn test_dont_filter_missing_ip_or_domains() {
        let event = Event::default();
        let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
        assert_eq!(
            filter_result,
            Ok(()),
            "Filtered event with no ip address and no domain."
        );
    }

    #[test]
    fn test_filter_local_domains() {
        for domain in &[
            "127.0.0.1",
            "localhost",
            "foo.localhost",
            "foo.bar.baz.localhost",
        ] {
            let event = get_event_with_domain(domain);
            let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
            assert_ne!(filter_result, Ok(()), "Failed to filter domain '{domain}'");
        }
    }

    #[test]
    fn test_dont_filter_non_local_domains() {
        for domain in &[
            "my.dom.com",
            "123.123.123.44",
            "localhost.com",
            "foolocalhost",
            "localhostbar",
            "alocalhostgoesintoabar",
        ] {
            let event = get_event_with_domain(domain);
            let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
            assert_eq!(
                filter_result,
                Ok(()),
                "Filtered perfectly valid domain '{domain}'"
            );
        }
    }

    #[test]
    fn test_filter_file_urls() {
        let url = "file:///Users/Maisey/work/squirrelchasers/src/leaderboard.html";
        let event = get_event_with_url(url);
        let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
        assert_ne!(
            filter_result,
            Ok(()),
            "Failed to filter event with url '{url}'"
        );
    }

    #[test]
    fn test_dont_filter_non_file_urls() {
        let url = "http://www.squirrelchasers.com/leaderboard";
        let event = get_event_with_url(url);
        let filter_result = should_filter(&event, &FilterConfig { is_enabled: true });
        assert_eq!(filter_result, Ok(()), "Filtered valid url '{url}'");
    }
}