1use std::{
7 borrow::Cow,
8 fmt::{self, Display, Write},
9};
10
11use http::Uri;
12use url::{Host, Url, form_urlencoded::Serializer};
13
14use super::string::is_unreserved_byte;
15
16#[must_use]
21pub fn url_encode(s: &str) -> String {
22 s.bytes()
23 .fold(String::with_capacity(s.len()), |mut out, b| {
24 if is_unreserved_byte(b) {
25 out.push(b.into());
26 } else {
27 write!(&mut out, "%{b:02X}").ok();
28 }
29
30 out
31 })
32}
33
34#[must_use]
40pub fn redirect_allowlisted(allowed: &[String], uri: &str) -> bool {
41 Url::parse(uri).is_ok_and(|url| {
42 let name = url.host_str().unwrap_or_else(|| url.scheme());
43
44 allowed
45 .iter()
46 .any(|entry| entry.eq_ignore_ascii_case(name))
47 })
48}
49
50#[must_use]
56pub fn hostname_matches_domain(hostname: &str, domain: &str) -> bool {
57 if domain == "." {
58 return hostname.ends_with('.');
59 }
60
61 let domain = domain.strip_prefix('.').unwrap_or(domain);
62
63 if domain.is_empty() {
64 return false;
65 }
66
67 if hostname.eq_ignore_ascii_case(domain) {
68 return true;
69 }
70
71 let Some(separator) = hostname
72 .len()
73 .checked_sub(domain.len())
74 .and_then(|index| index.checked_sub(1))
75 else {
76 return false;
77 };
78
79 let Some(suffix_start) = separator.checked_add(1) else {
80 return false;
81 };
82
83 hostname.as_bytes().get(separator) == Some(&b'.')
84 && hostname
85 .get(suffix_start..)
86 .is_some_and(|suffix| suffix.eq_ignore_ascii_case(domain))
87}
88
89#[must_use]
94pub fn is_loopback(url: &Url) -> bool {
95 match url.host() {
96 | Some(Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
97 | Some(Host::Ipv4(ip)) => ip.is_loopback(),
98 | Some(Host::Ipv6(ip)) => ip.is_loopback(),
99 | None => false,
100 }
101}
102
103#[must_use]
110pub fn is_plain_path(path: &str) -> bool {
111 path.bytes().all(is_path_byte) && !has_dot_segment(path)
112}
113
114#[must_use]
120pub fn is_path_byte(byte: u8) -> bool {
121 is_unreserved_byte(byte) || b"%!$&'()*+,;=:@/".contains(&byte)
122}
123
124#[must_use]
128pub fn with_query<Pairs, Key, Value>(path: &str, pairs: Pairs) -> Cow<'_, str>
129where
130 Pairs: ExactSizeIterator<Item = (Key, Value)>,
131 Key: AsRef<str>,
132 Value: AsRef<str>,
133{
134 match pairs.len() {
135 | 0 => Cow::Borrowed(path),
136 | _ => Serializer::for_suffix(format!("{path}?"), path.len().saturating_add(1))
137 .extend_pairs(pairs)
138 .finish()
139 .into(),
140 }
141}
142
143#[must_use]
147pub fn strip_trailing_slash(value: &str) -> &str { value.strip_suffix('/').unwrap_or(value) }
148
149#[must_use]
154pub fn has_dot_segment(path: &str) -> bool {
155 path.split('/')
156 .flat_map(|part| part.split("%2F"))
157 .flat_map(|part| part.split("%2f"))
158 .any(is_dot_segment)
159}
160
161fn is_dot_segment(segment: &str) -> bool {
162 strip_dot(segment).is_some_and(|rest| rest.is_empty() || strip_dot(rest) == Some(""))
163}
164
165fn strip_dot(segment: &str) -> Option<&str> {
166 segment.strip_prefix('.').or_else(|| {
167 segment
168 .get(..3)
169 .filter(|unit| unit.eq_ignore_ascii_case("%2e"))
170 .and_then(|_| segment.get(3..))
171 })
172}
173
174pub struct SanitizedUri<'a> {
179 uri: &'a Uri,
180 path: Option<&'a str>,
181}
182
183impl<'a> SanitizedUri<'a> {
184 #[must_use]
188 pub const fn new(uri: &'a Uri) -> Self { Self { uri, path: None } }
189
190 #[must_use]
194 pub const fn with_path(uri: &'a Uri, path: &'a str) -> Self { Self { uri, path: Some(path) } }
195}
196
197impl Display for SanitizedUri<'_> {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 let path = self.path.unwrap_or_else(|| self.uri.path());
200
201 match self.uri.query() {
202 | Some(_) => write!(f, "{path}?<redacted>"),
203 | None => f.write_str(path),
204 }
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn dot_segments_are_found_through_one_encoding() {
214 for path in [
215 "/a/./b",
216 "/a/../b",
217 "/a/..",
218 "..",
219 "/a/%2e%2e/b",
220 "/a/%2E./b",
221 "/a/.%2e",
222 "/a/%2e/b",
223 "/a%2F..%2Fb",
224 "/a%2f.",
225 ] {
226 assert!(has_dot_segment(path), "{path}");
227 }
228
229 for path in [
230 "/a/b",
231 "/a/.../b",
232 "/a/.b/c",
233 "/a/b.",
234 "/a/%252e%252e/b",
235 "/a/%2e%2e%2e",
236 "/a/%2",
237 "",
238 "/",
239 ] {
240 assert!(!has_dot_segment(path), "{path}");
241 }
242 }
243
244 #[test]
245 fn path_bytes_exclude_query_fragment_and_whitespace() {
246 assert!(
247 "/_matrix/federation/v1/a%20b:c@d!$&'()*+,;=-._~"
248 .bytes()
249 .all(is_path_byte)
250 );
251
252 for byte in [b'?', b'#', b' ', b'\\', b'"', b'<', b'^', b'`', b'{', b'|', 0, 0x7F, 0x80] {
253 assert!(!is_path_byte(byte), "{byte:#x}");
254 }
255 }
256
257 #[test]
258 fn plain_paths_hold_no_rewritable_byte_or_segment() {
259 assert!(is_plain_path("/_matrix/client/v1/rtc/livekit/get_token"));
260 assert!(is_plain_path("/a/%2Fb/.c"));
261
262 for path in ["/a/../b", "/a/%2e%2e/b", "/a/x\\..\\..\\b", "/a b", "/a?b", "/a#b"] {
263 assert!(!is_plain_path(path), "{path}");
264 }
265 }
266
267 #[test]
268 fn query_pairs_are_form_encoded_onto_the_path() {
269 let none: [(&str, &str); 0] = [];
270
271 assert!(matches!(with_query("/p", none.into_iter()), Cow::Borrowed("/p")));
272 assert_eq!(
273 with_query("/p", [("a", "1 2"), ("b&", "=")].into_iter()),
274 "/p?a=1+2&b%26=%3D"
275 );
276 }
277
278 #[test]
279 fn one_trailing_slash_is_stripped() {
280 for (value, expected) in [("a", "a"), ("a/", "a"), ("a//", "a/"), ("/", ""), ("", "")] {
281 assert_eq!(strip_trailing_slash(value), expected, "{value}");
282 }
283 }
284
285 #[test]
286 fn redacts_query() {
287 let uri: Uri = "/_matrix/client/v3/sync?access_token=syt_realtoken"
288 .parse()
289 .expect("valid uri");
290
291 let out = SanitizedUri::new(&uri).to_string();
292
293 assert_eq!(out, "/_matrix/client/v3/sync?<redacted>");
294 assert!(!out.contains("access_token"));
295 assert!(!out.contains("syt_realtoken"));
296 }
297
298 #[test]
299 fn preserves_path_without_query() {
300 let uri: Uri = "/_matrix/client/v3/sync"
301 .parse()
302 .expect("valid uri");
303
304 assert_eq!(SanitizedUri::new(&uri).to_string(), "/_matrix/client/v3/sync");
305 }
306
307 #[test]
308 fn replaces_concrete_path_parameters() {
309 let uri = Uri::builder()
310 .path_and_query(
311 "/_matrix/client/unstable/org.matrix.msc4140/delayed_events/secret?action=send",
312 )
313 .build()
314 .expect("valid uri");
315
316 let out = SanitizedUri::with_path(
317 &uri,
318 "/_matrix/client/unstable/org.matrix.msc4140/delayed_events/{delay_id}",
319 )
320 .to_string();
321
322 assert_eq!(
323 out,
324 "/_matrix/client/unstable/org.matrix.msc4140/delayed_events/{delay_id}?<redacted>"
325 );
326 assert!(!out.contains("secret"));
327 }
328}