Skip to main content

base/
url_rule.rs

1//! A URL written one way, as permission rules and the MCP policy read it
2//! ([`NormalizedUrl`]): userinfo, query and fragment dropped, host lowercased
3//! without a trailing `.`, the scheme's default port left out, `ws` / `wss`
4//! read as `http` / `https`, a path's escapes of unreserved characters
5//! decoded. Pattern matching over it lives in `permissions::url_rule`.
6//!
7//! `web.allowed_domains` is not a rule of this kind: it lists domains and the
8//! network layer enforces it on hosts (`interface::exec::domains_name_host`).
9//! Its callers use [`NormalizedUrl`] to get at the host.
10
11/// A URL as rules see it: `scheme://host[:port]path`.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct NormalizedUrl {
14    scheme: String,
15    host: String,
16    port: Option<u16>,
17    path: String,
18}
19
20impl NormalizedUrl {
21    /// `None` when `raw` is not an absolute URL with a host.
22    pub fn parse(raw: &str) -> Option<Self> {
23        let url = url::Url::parse(raw.trim()).ok()?;
24        let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
25        if host.is_empty() {
26            return None;
27        }
28        let scheme = websocket_as_http(url.scheme()).to_string();
29        let port = url
30            .port_or_known_default()
31            .filter(|p| Some(*p) != default_port(&scheme));
32        Some(Self {
33            scheme,
34            host,
35            port,
36            path: normalize_escapes(url.path()),
37        })
38    }
39
40    pub fn scheme(&self) -> &str {
41        &self.scheme
42    }
43
44    pub fn host(&self) -> &str {
45        &self.host
46    }
47
48    pub fn port(&self) -> Option<u16> {
49        self.port
50    }
51
52    /// The same URL with any trailing `/` taken off its path, the form an
53    /// OAuth issuer is compared in.
54    pub fn without_trailing_slash(mut self) -> Self {
55        let trimmed = self.path.trim_end_matches('/').len();
56        self.path.truncate(trimmed);
57        self
58    }
59
60    pub fn path_or_root(&self) -> &str {
61        if self.path.is_empty() {
62            "/"
63        } else {
64            &self.path
65        }
66    }
67}
68
69impl std::fmt::Display for NormalizedUrl {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(f, "{}://{}", self.scheme, self.host)?;
72        if let Some(port) = self.port {
73            write!(f, ":{port}")?;
74        }
75        f.write_str(&self.path)
76    }
77}
78
79/// Percent-escapes of unreserved characters (letters, digits, `-`, `.`, `_`,
80/// `~`) decoded, every other escape kept with upper-case hex.
81pub fn normalize_escapes(path: &str) -> String {
82    let mut out = String::with_capacity(path.len());
83    let mut rest = path;
84    while let Some(c) = rest.chars().next() {
85        let escaped = rest
86            .strip_prefix('%')
87            .and_then(|r| r.get(..2))
88            .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
89            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
90        match escaped {
91            Some(b) if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') => {
92                out.push(b as char);
93                rest = &rest[3..];
94            }
95            Some(b) => {
96                out.push_str(&format!("%{b:02X}"));
97                rest = &rest[3..];
98            }
99            None => {
100                out.push(c);
101                rest = &rest[c.len_utf8()..];
102            }
103        }
104    }
105    out
106}
107
108pub fn websocket_as_http(scheme: &str) -> &str {
109    match scheme {
110        "ws" => "http",
111        "wss" => "https",
112        other => other,
113    }
114}
115
116pub fn default_port(scheme: &str) -> Option<u16> {
117    match scheme {
118        "http" => Some(80),
119        "https" => Some(443),
120        _ => None,
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn a_normalized_url_is_written_one_way() {
130        let u = NormalizedUrl::parse("WSS://User@Corp.Example.:443/a/?q#f").unwrap();
131        assert_eq!(u.to_string(), "https://corp.example/a/");
132        assert_eq!(
133            u.without_trailing_slash().to_string(),
134            "https://corp.example/a"
135        );
136        assert_eq!(
137            NormalizedUrl::parse("http://h.example:8080")
138                .unwrap()
139                .to_string(),
140            "http://h.example:8080/"
141        );
142    }
143}