Skip to main content

relay_filter/
origin.rs

1/// A pattern used to match allowed paths.
2///
3/// Scheme, domain and port are extracted from an url,
4/// they may be either a string (to be matched exactly, case insensitive)
5/// or None (matches anything in the respective position).
6#[derive(Hash, PartialEq, Eq)]
7pub struct SchemeDomainPort {
8    /// The scheme of the url.
9    pub scheme: Option<String>,
10    /// The domain of the url.
11    pub domain: Option<String>,
12    /// The port of the url.
13    pub port: Option<String>,
14}
15
16impl From<&str> for SchemeDomainPort {
17    /// parse a string into a SchemaDomainPort pattern
18    fn from(url: &str) -> SchemeDomainPort {
19        /// converts string into patterns for SchemeDomainPort
20        /// the convention is that a "*" matches everything which
21        /// we encode as a None (same as the absence of the pattern)
22        fn normalize(pattern: &str) -> Option<String> {
23            if pattern == "*" {
24                None
25            } else {
26                Some(pattern.to_lowercase())
27            }
28        }
29
30        //split the scheme from the url
31        let scheme_idx = url.find("://");
32        let (scheme, rest) = if let Some(idx) = scheme_idx {
33            (normalize(&url[..idx]), &url[idx + 3..]) // chop after the scheme + the "://" delimiter
34        } else {
35            (None, url) // no scheme, chop nothing form original string
36        };
37
38        // extract domain:port from the rest of the url
39        let end_domain_idx = rest.find('/');
40        let domain_port = if let Some(end_domain_idx) = end_domain_idx {
41            &rest[..end_domain_idx] // remove the path from rest
42        } else {
43            rest // no path, use everything
44        };
45
46        // split the domain and the port
47        let ipv6_end_bracket_idx = domain_port.rfind(']');
48        let port_separator_idx = if let Some(end_bracket_idx) = ipv6_end_bracket_idx {
49            // we have an ipv6 address, find the port separator after the closing bracket
50            domain_port[end_bracket_idx..]
51                .rfind(':')
52                .map(|x| x + end_bracket_idx)
53        } else {
54            // no ipv6 address, find the port separator in the whole string
55            domain_port.rfind(':')
56        };
57        let (domain, port) = if let Some(port_separator_idx) = port_separator_idx {
58            //we have a port separator, split the string into domain and port
59            (
60                normalize(&domain_port[..port_separator_idx]),
61                normalize(&domain_port[port_separator_idx + 1..]),
62            )
63        } else {
64            (normalize(domain_port), None) // no port, whole string represents the domain
65        };
66
67        SchemeDomainPort {
68            scheme,
69            domain,
70            port,
71        }
72    }
73}
74
75/// Checks if a url satisfies one of the specified origins.
76///
77/// An origin specification may be in any of the following formats:
78///
79///  - `http://domain.com[:port]`
80///  - an exact match is required
81///  - `*`: anything goes
82///  - `*.domain.com`: matches domain.com and any subdomains
83///  - `*:port`: matches any hostname as long as the port matches
84pub fn matches_any_origin(url: Option<&str>, origins: &[SchemeDomainPort]) -> bool {
85    // if we have a "*" (Any) option, anything matches so don't bother going forward
86    if origins
87        .iter()
88        .any(|o| o.scheme.is_none() && o.port.is_none() && o.domain.is_none())
89    {
90        return true;
91    }
92
93    if let Some(url) = url {
94        let url = SchemeDomainPort::from(url);
95
96        for origin in origins {
97            if origin.scheme.is_some() && url.scheme != origin.scheme {
98                continue; // scheme not matched
99            }
100            if origin.port.is_some() && url.port != origin.port {
101                continue; // port not matched
102            }
103            if origin.domain.is_some() && url.domain != origin.domain {
104                // no direct match for domain, look for  partial patterns (e.g. "*.domain.com")
105                if let (Some(origin_domain), Some(domain)) = (&origin.domain, &url.domain)
106                    && let Some(suffix) = origin_domain.strip_prefix('*')
107                    && host_matches_or_is_subdomain_of(
108                        domain,
109                        suffix.strip_prefix('.').unwrap_or(suffix),
110                    )
111                {
112                    return true; // partial domain pattern match
113                }
114                continue; // domain not matched
115            }
116            // if we are here all patterns have matched so we are done
117            return true;
118        }
119    }
120    false
121}
122
123/// Checks if `host` is `domain` itself or one of its subdomains.
124///
125/// The match only happens on a label boundary, so `notabc.com` and `bc.com` are not subdomains of
126/// `abc.com`. An empty `domain` never matches.
127pub fn host_matches_or_is_subdomain_of(host: &str, domain: &str) -> bool {
128    if domain.is_empty() {
129        return false;
130    }
131    host.strip_suffix(domain)
132        .is_some_and(|s| s.is_empty() || s.ends_with('.'))
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn test_host_matches_or_is_subdomain_of() {
141        for (host, domain, expected) in [
142            ("abc.com", "abc.com", true),
143            ("www.abc.com", "abc.com", true),
144            ("a.b.abc.com", "abc.com", true),
145            ("notabc.com", "abc.com", false),
146            ("bc.com", "abc.com", false),
147            ("abc.com.evil.org", "abc.com", false),
148            ("", "abc.com", false),
149            // an empty domain never matches
150            ("", "", false),
151            ("abc.com", "", false),
152            ("abc.", "", false),
153        ] {
154            assert_eq!(
155                host_matches_or_is_subdomain_of(host, domain),
156                expected,
157                "host `{host}` against domain `{domain}`"
158            );
159        }
160    }
161
162    #[test]
163    fn test_scheme_domain_port() {
164        let examples = &[
165            ("*", None, None, None),
166            ("*://*", None, None, None),
167            ("*://*:*", None, None, None),
168            ("https://*", Some("https"), None, None),
169            ("https://*.abc.net", Some("https"), Some("*.abc.net"), None),
170            ("https://*:*", Some("https"), None, None),
171            ("x.y.z", None, Some("x.y.z"), None),
172            ("x.y.z:*", None, Some("x.y.z"), None),
173            ("*://x.y.z:*", None, Some("x.y.z"), None),
174            ("*://*.x.y.z:*", None, Some("*.x.y.z"), None),
175            ("*:8000", None, None, Some("8000")),
176            ("*://*:8000", None, None, Some("8000")),
177            ("http://x.y.z", Some("http"), Some("x.y.z"), None),
178            ("http://*:8000", Some("http"), None, Some("8000")),
179            ("abc:8000", None, Some("abc"), Some("8000")),
180            ("*.abc.com:8000", None, Some("*.abc.com"), Some("8000")),
181            ("*.com:86", None, Some("*.com"), Some("86")),
182            (
183                "http://abc.com:86",
184                Some("http"),
185                Some("abc.com"),
186                Some("86"),
187            ),
188            (
189                "http://x.y.z:4000",
190                Some("http"),
191                Some("x.y.z"),
192                Some("4000"),
193            ),
194            ("http://", Some("http"), Some(""), None),
195            ("abc.com/[something]", None, Some("abc.com"), None),
196            ("abc.com/something]:", None, Some("abc.com"), None),
197            ("abc.co]m/[something:", None, Some("abc.co]m"), None),
198            ("]abc.com:9000", None, Some("]abc.com"), Some("9000")),
199            (
200                "https://api.example.com/foo/00000000-0000-0000-0000-000000000000?includes[]=user&includes[]=image&includes[]=author&includes[]=tag",
201                Some("https"),
202                Some("api.example.com"),
203                None,
204            ),
205        ];
206
207        for (url, scheme, domain, port) in examples {
208            let actual: SchemeDomainPort = (*url).into();
209            assert_eq!(
210                (actual.scheme, actual.domain, actual.port),
211                (
212                    scheme.map(|x| x.to_owned()),
213                    domain.map(|x| x.to_owned()),
214                    port.map(|x| x.to_owned())
215                )
216            );
217        }
218    }
219
220    #[test]
221    fn test_matches_any_origin() {
222        let examples = &[
223            //MATCH
224            //generic matches
225            ("http://abc1.com", vec!["*://*:*", "bbc.com"], true),
226            ("http://abc2.com", vec!["*:*", "bbc.com"], true),
227            ("http://abc3.com", vec!["*", "bbc.com"], true),
228            ("http://abc4.com", vec!["http://*", "bbc.com"], true),
229            (
230                "http://abc5.com",
231                vec!["http://abc5.com:*", "bbc.com"],
232                true,
233            ),
234            ("http://abc.com:80", vec!["*://*:*", "bbc.com"], true),
235            ("http://abc.com:81", vec!["*:*", "bbc.com"], true),
236            ("http://abc.com:82", vec!["*:82", "bbc.com"], true),
237            ("http://abc.com:83", vec!["http://*:83", "bbc.com"], true),
238            ("http://abc.com:84", vec!["abc.com:*", "bbc.com"], true),
239            //partial domain matches
240            ("http://abc.com:85", vec!["*.abc.com:85", "bbc.com"], true),
241            ("http://abc.com:86", vec!["*.com:86"], true),
242            ("http://abc.com:86", vec!["*.com:86", "bbc.com"], true),
243            ("http://abc.def.ghc.com:87", vec!["*.com:87"], true),
244            ("http://abc.def.ghc.com:88", vec!["*.ghc.com:88"], true),
245            ("http://abc.def.ghc.com:89", vec!["*.def.ghc.com:89"], true),
246            //exact matches
247            ("http://abc.com:90", vec!["abc.com", "bbc.com"], true),
248            ("http://abc.com:91", vec!["abc.com:91", "bbc.com"], true),
249            ("http://abc.com:92", vec!["http://abc.com:92"], true),
250            ("http://abc.com:93", vec!["http://abc.com", "bbc.com"], true),
251            //matches in various positions
252            ("http://abc6.com", vec!["abc6.com", "bbc.com"], true),
253            ("http://abc7.com", vec!["bbc.com", "abc7.com"], true),
254            ("http://abc8.com", vec!["bbc.com", "abc8.com", "def"], true),
255            //NON MATCH
256            //different domain
257            (
258                "http://abc9.com",
259                vec!["http://other.com", "bbc.com"],
260                false,
261            ),
262            ("http://abc10.com", vec!["http://*.other.com", "bbc"], false),
263            ("abc11.com", vec!["*.other.com", "bbc"], false),
264            //different scheme
265            (
266                "https://abc12.com",
267                vec!["http://abc12.com", "bbc.com"],
268                false,
269            ),
270            //different port
271            (
272                "http://abc13.com:80",
273                vec!["http://abc13.com:8080", "bbc.com"],
274                false,
275            ),
276            // this used to crash
277            ("http://y:80", vec!["http://x"], false),
278            // starts on both ends
279            (
280                "https://abc.software.example.com",
281                vec!["*abc.software.example.com*"],
282                false,
283            ),
284            // wildcard without a dot only matches on a label boundary
285            ("http://notabc.com", vec!["*abc.com"], false),
286            ("http://bc.com", vec!["*abc.com"], false),
287            ("http://abc.com", vec!["*abc.com"], true),
288            ("http://www.abc.com", vec!["*abc.com"], true),
289            ("http://bc.com", vec!["*.abc.com"], false),
290            ("http://notabc.com", vec!["*.abc.com"], false),
291            ("http://www.abc.com", vec!["*.abc.com"], true),
292            ("http://abc.com", vec!["*."], false),
293        ];
294
295        for (url, origins, expected) in examples {
296            let origins: Vec<_> = origins
297                .iter()
298                .map(|url| SchemeDomainPort::from(*url))
299                .collect();
300            let actual = matches_any_origin(Some(*url), &origins[..]);
301            assert_eq!(*expected, actual, "Could not match {url}.");
302        }
303    }
304}