Skip to main content

base/
url_rule.rs

1//! URL rules: the one way a pattern like `https://*.corp.example/**` is
2//! matched against a URL, for permission rules on URL-valued tools
3//! (`WebFetch(...)`, `Ping(...)`) and the MCP policy's `url` and
4//! `allowed_authorization_servers` rules alike.
5//!
6//! Both sides are taken apart before they meet, and each part is brought to
7//! the form the request goes out in. A URL is parsed and written one way
8//! ([`NormalizedUrl`]): userinfo, query and fragment dropped, host lowercased
9//! (a Unicode host as its punycode) without a trailing `.`, the scheme's
10//! default port left out, `ws` / `wss` read as `http` / `https`. A pattern is
11//! split into scheme, host, port and path ([`UrlPattern`]); its host goes
12//! through the same IDNA mapping, label by label. On both sides a path's
13//! percent-escapes of unreserved characters are decoded (`/%61dmin` is
14//! `/admin`, as a server reads it) and the rest are kept, in upper case —
15//! `%2F` is not a `/`. Each part is then matched against the same part of the
16//! URL on its own. So a wildcard in the host stays in the
17//! host — it spans `.`-separated labels and nothing else, never `:`, `/`,
18//! `?` or `@` — and `https://*.example.com/**` cannot be met by
19//! `https://evil.net/.example.com/`. In the path `*` stays within one
20//! segment and `**` crosses them, as in path rules.
21//!
22//! `web.allowed_domains` is not a rule of this kind: it lists domains,
23//! each covering its subdomains, and the network layer enforces it on hosts
24//! (`interface::exec::domains_name_host`). Its callers use [`NormalizedUrl`]
25//! to get at the host.
26
27use globset::{GlobBuilder, GlobMatcher};
28
29/// A URL as rules see it: `scheme://host[:port]path`.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct NormalizedUrl {
32    scheme: String,
33    host: String,
34    port: Option<u16>,
35    path: String,
36}
37
38impl NormalizedUrl {
39    /// `None` when `raw` is not an absolute URL with a host.
40    pub fn parse(raw: &str) -> Option<Self> {
41        let url = url::Url::parse(raw.trim()).ok()?;
42        let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
43        if host.is_empty() {
44            return None;
45        }
46        let scheme = websocket_as_http(url.scheme()).to_string();
47        let port = url
48            .port_or_known_default()
49            .filter(|p| Some(*p) != default_port(&scheme));
50        Some(Self {
51            scheme,
52            host,
53            port,
54            path: normalize_escapes(url.path()),
55        })
56    }
57
58    pub fn host(&self) -> &str {
59        &self.host
60    }
61
62    /// The same URL with any trailing `/` taken off its path, the form an
63    /// OAuth issuer is compared in.
64    pub fn without_trailing_slash(mut self) -> Self {
65        let trimmed = self.path.trim_end_matches('/').len();
66        self.path.truncate(trimmed);
67        self
68    }
69
70    fn path_or_root(&self) -> &str {
71        if self.path.is_empty() {
72            "/"
73        } else {
74            &self.path
75        }
76    }
77}
78
79impl std::fmt::Display for NormalizedUrl {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{}://{}", self.scheme, self.host)?;
82        if let Some(port) = self.port {
83            write!(f, ":{port}")?;
84        }
85        f.write_str(&self.path)
86    }
87}
88
89/// A compiled `scheme://host[:port][/path]` pattern. Each part is a glob;
90/// a port of `*` takes any port, no port takes only the scheme's default,
91/// and no path is `/`.
92#[derive(Debug, Clone)]
93pub struct UrlPattern {
94    scheme: GlobMatcher,
95    host: GlobMatcher,
96    host_text: String,
97    port: PortPattern,
98    path: GlobMatcher,
99}
100
101#[derive(Debug, Clone, Copy)]
102enum PortPattern {
103    Default,
104    Any,
105    Exactly(u16),
106}
107
108impl UrlPattern {
109    /// `Err` for text that is not `scheme://host[:port][/path]`. A `?` or `#`
110    /// is refused rather than read as a wildcard: in a URL it opens the query
111    /// or fragment, and the text of a URL with a query (what "permit always"
112    /// records) must not match other URLs.
113    pub fn parse(pattern: &str) -> Result<Self, String> {
114        let pattern = pattern.trim();
115        if pattern.contains(['?', '#']) {
116            return Err(format!(
117                "{pattern:?}: a URL pattern has no query or fragment, and `?` is no wildcard in one"
118            ));
119        }
120        let (scheme, rest) = pattern
121            .split_once("://")
122            .filter(|(scheme, _)| !scheme.is_empty())
123            .ok_or_else(|| format!("{pattern:?} is not a URL pattern (scheme://host[/path])"))?;
124        let scheme = websocket_as_http(&scheme.to_ascii_lowercase()).to_string();
125        let (authority, path) = match rest.find('/') {
126            Some(slash) => rest.split_at(slash),
127            None => (rest, "/"),
128        };
129        if authority.contains('@') {
130            return Err(format!("{pattern:?}: a URL pattern names no userinfo"));
131        }
132        let (host, port) = split_port(authority).ok_or_else(|| {
133            format!("{pattern:?}: an IPv6 host is followed by nothing but `:port`")
134        })?;
135        let host = host.trim_end_matches('.').to_ascii_lowercase();
136        if host.is_empty() {
137            return Err(format!("{pattern:?} names no host"));
138        }
139        let ipv6 = is_ipv6_literal(&host);
140        let host = if ipv6 {
141            host
142        } else {
143            host_to_ascii(&host)
144                .ok_or_else(|| format!("{pattern:?}: the host is not a domain name IDNA can map"))?
145        };
146        let port = match port {
147            None => PortPattern::Default,
148            Some("*") => PortPattern::Any,
149            Some(digits) => match digits.parse::<u16>() {
150                Ok(p) if Some(p) == default_port(&scheme) => PortPattern::Default,
151                Ok(p) => PortPattern::Exactly(p),
152                Err(_) => {
153                    return Err(format!("{pattern:?}: port {digits:?} is not a number"));
154                }
155            },
156        };
157        // An IPv6 literal's brackets are part of the host, not a glob class.
158        let host_glob = if ipv6 {
159            globset::escape(&host)
160        } else {
161            host.clone()
162        };
163        let glob = |part: &str, what: &str| {
164            GlobBuilder::new(part)
165                .literal_separator(true)
166                .build()
167                .map(|g| g.compile_matcher())
168                .map_err(|e| format!("{pattern:?}: invalid glob in the {what}: {e}"))
169        };
170        Ok(Self {
171            scheme: glob(&scheme, "scheme")?,
172            host: glob(&host_glob, "host")?,
173            host_text: host,
174            port,
175            path: glob(&normalize_escapes(&encode_like_a_url_path(path)), "path")?,
176        })
177    }
178
179    pub fn matches(&self, url: &NormalizedUrl) -> bool {
180        let port = match self.port {
181            PortPattern::Default => url.port.is_none(),
182            PortPattern::Any => true,
183            PortPattern::Exactly(p) => url.port == Some(p),
184        };
185        port && self.scheme.is_match(&url.scheme)
186            && self.host.is_match(&url.host)
187            && self.path.is_match(url.path_or_root())
188    }
189
190    /// Whether the host part pins no domain: it has a wildcard, and the labels
191    /// written out after the last one holding a wildcard are not a domain
192    /// someone registered but a public suffix (`*`, `*.com`, `*.co.uk`,
193    /// `*.github.io`, `api.*`, `*example.com`) or numbers (`*.0.0.1`) — so it
194    /// reaches hosts anyone can register or address.
195    pub fn host_is_open(&self) -> bool {
196        let wildcard = |c: char| matches!(c, '*' | '?' | '[' | ']' | '{' | '}');
197        if is_ipv6_literal(&self.host_text) || !self.host_text.contains(wildcard) {
198            return false;
199        }
200        let labels: Vec<&str> = self.host_text.split('.').collect();
201        let tail_start = labels
202            .iter()
203            .rposition(|label| label.contains(wildcard))
204            .map_or(0, |i| i + 1);
205        let tail = &labels[tail_start..];
206        let numeric = tail
207            .last()
208            .is_none_or(|tld| tld.bytes().all(|b| b.is_ascii_digit()));
209        numeric || !crate::public_suffix::is_registrable_or_below(&tail.join("."))
210    }
211}
212
213/// Rule text that matches `url` and no other URL, for recording a "permit
214/// always" answer: the glob characters a URL may carry (`*`, `[`, `{`) are
215/// escaped. Text with a query or fragment, which [`UrlPattern::parse`]
216/// refuses, already only matches itself and is kept as it is.
217pub fn literal_pattern(url: &str) -> String {
218    if url.contains(['?', '#']) || !url.contains(['*', '[', ']', '{', '}']) {
219        return url.to_string();
220    }
221    let Some((scheme, rest)) = url.split_once("://") else {
222        return globset::escape(url);
223    };
224    let (authority, path) = rest
225        .find('/')
226        .map_or((rest, ""), |slash| rest.split_at(slash));
227    let authority = match split_port(authority) {
228        Some((host, _)) if is_ipv6_literal(host) => authority.to_string(),
229        _ => globset::escape(authority),
230    };
231    format!("{scheme}://{authority}{}", globset::escape(path))
232}
233
234/// Whether `url` matches `pattern`. `false` when either does not parse.
235pub fn matches(pattern: &str, url: &str) -> bool {
236    match (UrlPattern::parse(pattern), NormalizedUrl::parse(url)) {
237        (Ok(pattern), Some(url)) => pattern.matches(&url),
238        _ => false,
239    }
240}
241
242/// `host` and the text after its port's `:`, if any; `None` for an IPv6
243/// literal followed by something other than a port.
244fn split_port(authority: &str) -> Option<(&str, Option<&str>)> {
245    let bracketed = authority
246        .find(']')
247        .map(|close| authority.split_at(close + 1))
248        .filter(|(host, _)| is_ipv6_literal(host));
249    if let Some((host, rest)) = bracketed {
250        return match rest {
251            "" => Some((host, None)),
252            _ => rest.strip_prefix(':').map(|port| (host, Some(port))),
253        };
254    }
255    Some(match authority.rsplit_once(':') {
256        Some((host, port)) => (host, Some(port)),
257        None => (authority, None),
258    })
259}
260
261fn is_ipv6_literal(host: &str) -> bool {
262    host.strip_prefix('[')
263        .and_then(|h| h.strip_suffix(']'))
264        .is_some_and(|inner| {
265            inner.contains(':')
266                && inner
267                    .chars()
268                    .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.'))
269        })
270}
271
272/// A host pattern as the URL parser writes hosts: each label without a glob
273/// character through IDNA (`bücher` is `xn--bcher-kva`). A label that holds a
274/// glob and is not ASCII has no such form: `None`.
275fn host_to_ascii(host: &str) -> Option<String> {
276    if host.is_ascii() {
277        return Some(host.to_string());
278    }
279    let glob = |c: char| matches!(c, '*' | '?' | '[' | ']' | '{' | '}');
280    let labels = host
281        .split('.')
282        .map(|label| {
283            if label.is_ascii() {
284                Some(label.to_string())
285            } else if label.contains(glob) {
286                None
287            } else {
288                match url::Host::parse(label).ok()? {
289                    url::Host::Domain(d) => Some(d),
290                    _ => None,
291                }
292            }
293        })
294        .collect::<Option<Vec<_>>>()?;
295    Some(labels.join("."))
296}
297
298/// What the URL parser percent-encodes in a path — controls, space, `"`,
299/// `<`, `>`, `` ` `` and anything not ASCII — encoded, so a pattern written
300/// with them meets the URL that carries them. `{` and `}` stay: in a pattern
301/// they are glob syntax.
302fn encode_like_a_url_path(path: &str) -> String {
303    let mut out = String::with_capacity(path.len());
304    for c in path.chars() {
305        if c.is_ascii() && !c.is_ascii_control() && !matches!(c, ' ' | '"' | '<' | '>' | '`') {
306            out.push(c);
307        } else {
308            let mut buf = [0; 4];
309            for b in c.encode_utf8(&mut buf).bytes() {
310                out.push_str(&format!("%{b:02X}"));
311            }
312        }
313    }
314    out
315}
316
317/// Percent-escapes of unreserved characters (letters, digits, `-`, `.`, `_`,
318/// `~`) decoded, every other escape kept with upper-case hex.
319fn normalize_escapes(path: &str) -> String {
320    let mut out = String::with_capacity(path.len());
321    let mut rest = path;
322    while let Some(c) = rest.chars().next() {
323        let escaped = rest
324            .strip_prefix('%')
325            .and_then(|r| r.get(..2))
326            .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
327            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
328        match escaped {
329            Some(b) if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') => {
330                out.push(b as char);
331                rest = &rest[3..];
332            }
333            Some(b) => {
334                out.push_str(&format!("%{b:02X}"));
335                rest = &rest[3..];
336            }
337            None => {
338                out.push(c);
339                rest = &rest[c.len_utf8()..];
340            }
341        }
342    }
343    out
344}
345
346fn websocket_as_http(scheme: &str) -> &str {
347    match scheme {
348        "ws" => "http",
349        "wss" => "https",
350        other => other,
351    }
352}
353
354fn default_port(scheme: &str) -> Option<u16> {
355    match scheme {
356        "http" => Some(80),
357        "https" => Some(443),
358        _ => None,
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn a_host_wildcard_stays_in_the_host() {
368        let p = "https://*.example.com/**";
369        for url in [
370            "https://api.example.com/v1",
371            "https://a.b.example.com/",
372            "https://API.example.com./v1?x=1#f",
373            "https://api.example.com:443/v1",
374            "https://user:pw@api.example.com/v1",
375            "wss://api.example.com/socket",
376        ] {
377            assert!(matches(p, url), "{url}");
378        }
379        for url in [
380            "https://evil.net/.example.com/",
381            "https://evil.net/x.example.com/steal",
382            "https://evil.net/?q=.example.com/",
383            "https://evil.net#.example.com/",
384            "https://api.example.com@evil.net/",
385            "https://api.example.com.evil.net/",
386            "https://api.example.com:8443/",
387            "http://api.example.com/",
388            "not a url",
389        ] {
390            assert!(!matches(p, url), "{url}");
391        }
392    }
393
394    #[test]
395    fn the_path_glob_keeps_star_within_a_segment() {
396        assert!(matches("https://h.example/*", "https://h.example/mcp"));
397        assert!(!matches("https://h.example/*", "https://h.example/v1/mcp"));
398        assert!(matches("https://h.example/**", "https://h.example/v1/mcp"));
399        assert!(matches("https://h.example", "https://h.example/"));
400        assert!(!matches("https://h.example", "https://h.example/x"));
401    }
402
403    #[test]
404    fn ports_are_matched_on_their_own() {
405        assert!(matches(
406            "https://h.example:8443/**",
407            "https://h.example:8443/x"
408        ));
409        assert!(!matches("https://h.example:8443/**", "https://h.example/x"));
410        assert!(matches("https://h.example:*/**", "https://h.example:9/x"));
411        assert!(matches("https://h.example:443/**", "https://h.example/x"));
412        assert!(matches("http://[::1]:8080/**", "http://[::1]:8080/x"));
413        assert!(!matches("http://[::1]/**", "http://[::2]/x"));
414    }
415
416    #[test]
417    fn what_is_not_a_url_pattern_is_refused() {
418        for pattern in [
419            "**",
420            "*.example.com",
421            "example.com/**",
422            "https://",
423            "https://u@h/",
424        ] {
425            assert!(UrlPattern::parse(pattern).is_err(), "{pattern}");
426        }
427        assert!(UrlPattern::parse("https://h:port/").is_err());
428    }
429
430    #[test]
431    fn an_open_host_pins_no_domain() {
432        for p in [
433            "https://*/**",
434            "https://*.com/**",
435            "https://api.*/**",
436            "https://**",
437        ] {
438            assert!(UrlPattern::parse(p).unwrap().host_is_open(), "{p}");
439        }
440        for p in [
441            "https://*.example.com/**",
442            "https://example.com/**",
443            "https://localhost/**",
444        ] {
445            assert!(!UrlPattern::parse(p).unwrap().host_is_open(), "{p}");
446        }
447    }
448
449    /// A rule meets a URL in the form the request goes out in: a host written
450    /// in Unicode is the punycode the URL parser turns it into, and an
451    /// unreserved character spelled as a percent-escape is that character —
452    /// the server reads `/%61dmin/` as `/admin/`. Otherwise a deny written
453    /// for the host or the path does not refuse the very URL it names.
454    #[test]
455    fn a_rule_meets_the_url_the_request_goes_to() {
456        assert!(
457            matches("https://bücher.example/**", "https://bücher.example/x"),
458            "a Unicode host does not match itself"
459        );
460        assert!(
461            matches("https://h.example/admin/**", "https://h.example/%61dmin/x"),
462            "a percent-escaped letter walks past a path rule"
463        );
464    }
465
466    #[test]
467    fn a_unicode_host_in_a_pattern_is_its_punycode() {
468        for url in [
469            "https://bücher.example/x",
470            "https://BÜCHER.example/x",
471            "https://xn--bcher-kva.example/x",
472        ] {
473            assert!(matches("https://bücher.example/**", url), "{url}");
474            assert!(matches(
475                "https://*.bücher.example/**",
476                &url.replace("://", "://a.")
477            ));
478        }
479        assert!(matches(
480            "https://xn--bcher-kva.example/**",
481            "https://bücher.example/x"
482        ));
483        assert!(!matches(
484            "https://bücher.example/**",
485            "https://bucher.example/x"
486        ));
487        assert!(UrlPattern::parse("https://bü*.example/**").is_err());
488    }
489
490    #[test]
491    fn an_escaped_unreserved_character_is_that_character_and_nothing_else_is_decoded() {
492        let deny = "https://h.example/admin/**";
493        for url in [
494            "https://h.example/admin/x",
495            "https://h.example/%61dmin/x",
496            "https://h.example/%61%64%6D%69%6E/x",
497            "https://h.example/%61%64%6d%69%6e/x",
498        ] {
499            assert!(matches(deny, url), "{url}");
500        }
501        assert!(!matches(deny, "https://h.example/Admin/x"));
502        assert!(!matches("https://h.example/a/b", "https://h.example/a%2Fb"));
503        assert!(matches(
504            "https://h.example/a%2fb",
505            "https://h.example/a%2Fb"
506        ));
507        assert!(matches(
508            "https://h.example/a%2Fb",
509            "https://h.example/a%2fb"
510        ));
511        assert!(!matches("https://h.example/*", "https://h.example/a/b"));
512        assert!(matches("https://h.example/*", "https://h.example/a%2Fb"));
513        assert!(matches(
514            "https://h.example/%7euser/**",
515            "https://h.example/~user/x"
516        ));
517        assert!(matches(
518            "https://h.example/ä/**",
519            "https://h.example/%C3%A4/x"
520        ));
521        assert!(matches("https://h.example/a b", "https://h.example/a%20b"));
522        assert!(matches("https://h.example/100%", "https://h.example/100%"));
523    }
524
525    #[test]
526    fn a_query_or_fragment_makes_no_pattern() {
527        for pattern in [
528            "https://h.example/a?b",
529            "https://h.example/a#b",
530            "https://h?.example/",
531        ] {
532            assert!(UrlPattern::parse(pattern).is_err(), "{pattern}");
533        }
534    }
535
536    #[test]
537    fn a_literal_pattern_matches_only_its_own_url() {
538        assert_eq!(
539            literal_pattern("https://h.example/a"),
540            "https://h.example/a"
541        );
542        assert_eq!(
543            literal_pattern("https://h.example/a?b*"),
544            "https://h.example/a?b*"
545        );
546        let star = literal_pattern("https://h.example/**");
547        assert!(matches(&star, "https://h.example/**"));
548        assert!(!matches(&star, "https://h.example/x"));
549        let host = literal_pattern("https://*.com/x");
550        assert!(matches(&host, "https://*.com/x"), "{host}");
551        assert!(!matches(&host, "https://evil.com/x"));
552        let ipv6 = literal_pattern("http://[::1]:8080/a*");
553        assert!(matches(&ipv6, "http://[::1]:8080/a*"), "{ipv6}");
554        assert!(!matches(&ipv6, "http://[::1]:8080/ab"));
555    }
556
557    #[test]
558    fn a_host_wildcard_under_a_public_suffix_is_open() {
559        for p in [
560            "https://*.co.uk/**",
561            "https://*.com.cn/**",
562            "https://*.github.io/**",
563            "https://*example.com/**",
564            "https://a.*.com/**",
565            "https://*.0.0.1/**",
566            "https://example.com{,.evil.net}/**",
567        ] {
568            assert!(UrlPattern::parse(p).unwrap().host_is_open(), "{p}");
569        }
570        for p in [
571            "https://*.bbc.co.uk/**",
572            "https://*.alice.github.io/**",
573            "https://api-*.example.com/**",
574            "https://*.bücher.example/**",
575            "http://[::1]:8080/**",
576        ] {
577            assert!(!UrlPattern::parse(p).unwrap().host_is_open(), "{p}");
578        }
579    }
580
581    #[test]
582    fn a_normalized_url_is_written_one_way() {
583        let u = NormalizedUrl::parse("WSS://User@Corp.Example.:443/a/?q#f").unwrap();
584        assert_eq!(u.to_string(), "https://corp.example/a/");
585        assert_eq!(
586            u.without_trailing_slash().to_string(),
587            "https://corp.example/a"
588        );
589        assert_eq!(
590            NormalizedUrl::parse("http://h.example:8080")
591                .unwrap()
592                .to_string(),
593            "http://h.example:8080/"
594        );
595    }
596}