Skip to main content

oxblade_adminlte/
url.rs

1use std::{fmt, str::FromStr};
2
3/// An application-resolved link or asset URL safe to put into a quoted HTML attribute.
4///
5/// This is a conservative replacement for the PHP asset and menu URL helpers'
6/// permissive output. Only HTTP(S), single-slash rooted paths and fragments are
7/// accepted. Escape the value for HTML separately; this type does not mark HTML as trusted.
8///
9/// ```
10/// use oxblade_adminlte::SafeUrl;
11/// let asset: SafeUrl = "/assets/adminlte.css".parse()?;
12/// assert_eq!(asset.as_str(), "/assets/adminlte.css");
13/// # Ok::<(), oxblade_adminlte::InvalidUrl>(())
14/// ```
15#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
16#[serde(transparent)]
17pub struct SafeUrl(String);
18
19impl SafeUrl {
20    /// Returns the validated URL before HTML escaping.
21    ///
22    /// ```
23    /// let page: oxblade_adminlte::SafeUrl = "#main-content".parse()?;
24    /// assert_eq!(page.as_str(), "#main-content");
25    /// # Ok::<(), oxblade_adminlte::InvalidUrl>(())
26    /// ```
27    pub fn as_str(&self) -> &str {
28        &self.0
29    }
30}
31
32/// A URL outside the accepted forms for a PHP menu link or asset reference.
33///
34/// ```
35/// assert!("//example.test/app.js".parse::<oxblade_adminlte::SafeUrl>().is_err());
36/// ```
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub struct InvalidUrl;
39
40impl fmt::Display for InvalidUrl {
41    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
42        formatter.write_str("expected an HTTP(S) URL, a rooted path, or a fragment")
43    }
44}
45
46impl std::error::Error for InvalidUrl {}
47
48impl FromStr for SafeUrl {
49    type Err = InvalidUrl;
50
51    fn from_str(raw: &str) -> Result<Self, Self::Err> {
52        if raw
53            .chars()
54            .any(|c| c.is_whitespace() || c.is_control() || c == '\\')
55        {
56            return Err(InvalidUrl);
57        }
58        if raw.starts_with('#') || (raw.starts_with('/') && !raw.starts_with("//")) {
59            return Ok(Self(raw.to_owned()));
60        }
61        let (scheme, rest) = raw.split_once("://").ok_or(InvalidUrl)?;
62        if !(scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http"))
63            || rest.starts_with('/')
64            || rest.is_empty()
65        {
66            return Err(InvalidUrl);
67        }
68        let parsed = ::url::Url::parse(raw).map_err(|_| InvalidUrl)?;
69        if parsed.host().is_none() || !parsed.username().is_empty() || parsed.password().is_some() {
70            return Err(InvalidUrl);
71        }
72        Ok(Self(raw.to_owned()))
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::SafeUrl;
79
80    #[test]
81    fn restricts_menu_and_asset_urls_to_supported_forms() {
82        for valid in [
83            "#navigation",
84            "/dashboard?view=weekly&sort=asc",
85            "HTTPS://example.test/asset.css",
86        ] {
87            assert!(valid.parse::<SafeUrl>().is_ok(), "{valid}");
88        }
89        for invalid in [
90            "",
91            "example.test",
92            "ftp://example.test",
93            "//example.test",
94            "/\\example.test",
95            " https://example.test",
96            "https:///example.test",
97            "https://user@example.test",
98        ] {
99            assert!(invalid.parse::<SafeUrl>().is_err(), "{invalid}");
100        }
101    }
102}