1use std::{fmt, str::FromStr};
2
3#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
16#[serde(transparent)]
17pub struct SafeUrl(String);
18
19impl SafeUrl {
20 pub fn as_str(&self) -> &str {
28 &self.0
29 }
30}
31
32#[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}