1use url::Url;
4
5use super::Failure;
6
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Redirect {
14 Follow,
24 #[default]
27 SameHost,
28 Ignore,
30}
31
32impl Redirect {
33 pub(super) fn target(&self, uri: &str, current: &Url, pinned: bool) -> Result<Option<Url>, Failure> {
41 if uri.is_empty() {
42 return Ok(None);
43 }
44
45 let target = uri
49 .parse::<Url>()
50 .map_err(|_| Failure::Refused("the GOAWAY URI is malformed"))?;
51 if matches!(self, Self::Ignore) {
52 return Ok(None);
53 }
54
55 if scheme_tier(target.scheme()) < scheme_tier(current.scheme()) {
56 return Err(Failure::Refused("the GOAWAY redirect downgrades the scheme"));
57 }
58
59 if is_local(&target) && !is_local(current) {
64 return Err(Failure::Refused(
65 "the GOAWAY redirect widens reachability to a local address",
66 ));
67 }
68
69 let same_host = target.host_str() == current.host_str();
72 if matches!(self, Self::SameHost) && !same_host {
73 return Err(Failure::Refused("the GOAWAY redirect leaves the current host"));
74 }
75 if pinned && encrypted(current.scheme()) && !same_host {
78 return Err(Failure::Refused(
79 "the GOAWAY redirect leaves the host a certificate pin verifies",
80 ));
81 }
82
83 Ok(Some(target))
84 }
85}
86
87fn encrypted(scheme: &str) -> bool {
89 scheme_tier(scheme) == 2
90}
91
92fn scheme_tier(scheme: &str) -> u8 {
95 match scheme {
96 "https" | "moqt" | "moql" | "wss" | "tls" => 2,
97 "tcp" | "ws" | "http" => 1,
98 _ => 0,
101 }
102}
103
104fn is_local(url: &Url) -> bool {
113 match url.host() {
114 Some(url::Host::Domain(host)) => match Url::parse(&format!("https://{host}/"))
119 .ok()
120 .and_then(|u| u.host().map(|h| h.to_owned()))
121 {
122 Some(url::Host::Ipv4(ip)) => is_local_ip(ip.into()),
123 Some(url::Host::Ipv6(ip)) => is_local_ip(ip.into()),
124 Some(url::Host::Domain(name)) => {
125 let name = name.strip_suffix('.').unwrap_or(&name);
127 name == "localhost" || name.ends_with(".localhost")
128 }
129 None => match host.parse::<std::net::IpAddr>() {
131 Ok(ip) => is_local_ip(ip),
132 Err(_) => host == "localhost" || host.ends_with(".localhost"),
133 },
134 },
135 Some(url::Host::Ipv4(ip)) => is_local_ip(ip.into()),
136 Some(url::Host::Ipv6(ip)) => is_local_ip(ip.into()),
137 None => true,
139 }
140}
141
142fn is_local_ip(ip: std::net::IpAddr) -> bool {
144 match ip {
145 std::net::IpAddr::V4(ip) => is_local_v4(ip),
146 std::net::IpAddr::V6(ip) => match ip.to_ipv4_mapped() {
149 Some(v4) => is_local_v4(v4),
150 None => ip.is_loopback() || ip.is_unspecified() || ip.is_unique_local() || ip.is_unicast_link_local(),
151 },
152 }
153}
154
155fn is_local_v4(ip: std::net::Ipv4Addr) -> bool {
156 ip.is_loopback() || ip.is_private() || ip.is_link_local() || ip.is_unspecified()
157}
158
159pub(super) fn endpoint(url: &Url) -> Url {
162 let mut bare = url.clone();
163 let _ = bare.set_username("");
165 let _ = bare.set_password(None);
166 bare.set_query(None);
167 bare.set_fragment(None);
168 bare
169}
170
171pub(super) struct Shown<'a>(pub &'a Url);
178
179impl std::fmt::Display for Shown<'_> {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 write!(f, "{}://", self.0.scheme())?;
182 let Some(host) = self.0.host_str() else {
183 return write!(f, "{}", self.0.path());
186 };
187 write!(f, "{host}")?;
188 match self.0.port() {
189 Some(port) => write!(f, ":{port}"),
190 None => Ok(()),
191 }
192 }
193}
194
195pub(super) struct Redirects {
201 mark: Option<Url>,
202 span: u64,
203 hops: u64,
204 looped: bool,
205}
206
207impl Default for Redirects {
208 fn default() -> Self {
209 Self {
210 mark: None,
211 span: 1,
212 hops: 0,
213 looped: false,
214 }
215 }
216}
217
218impl Redirects {
219 pub(super) fn depart(&mut self, from: Url, to: &Url) -> bool {
221 if self.mark.as_ref() == Some(to) {
222 self.looped = true;
223 }
224 self.hops += 1;
225 if self.hops == self.span {
226 self.mark = Some(from);
227 self.span = self.span.saturating_mul(2);
228 self.hops = 0;
229 }
230 self.looped
231 }
232
233 pub(super) fn reset(&mut self) {
235 *self = Self::default();
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 fn url(value: &str) -> Url {
244 value.parse().expect("valid url")
245 }
246
247 fn refused(res: Result<Option<Url>, Failure>) -> bool {
248 matches!(res, Err(Failure::Refused(_)))
249 }
250
251 #[test]
254 fn local_targets_are_recognized() {
255 #[derive(serde::Deserialize)]
257 struct Case {
258 url: String,
259 local: bool,
260 }
261 let cases: Vec<Case> =
262 serde_json::from_str(include_str!("../../fixtures/endpoints.json")).expect("a malformed fixture");
263 for case in cases {
264 assert_eq!(is_local(&url(&case.url)), case.local, "{}", case.url);
265 }
266
267 let public = url("https://relay.example/");
269 let localhost = url("https://127.0.0.1:4443/");
270 assert!(refused(Redirect::Follow.target(
271 "https://[::ffff:127.0.0.1]/",
272 &public,
273 false
274 )));
275 assert!(refused(Redirect::Follow.target(
276 "moqt://127.1/",
277 &url("moqt://relay.example/"),
278 false
279 )));
280 assert_eq!(
281 Redirect::Follow
282 .target("https://127.0.0.1:9999/", &localhost, false)
283 .unwrap()
284 .unwrap()
285 .port(),
286 Some(9999)
287 );
288 }
289
290 #[test]
294 fn scheme_tiers_rank_encrypted_above_plaintext() {
295 for scheme in ["https", "moqt", "moql", "wss", "tls"] {
296 assert_eq!(scheme_tier(scheme), 2, "{scheme} is encrypted");
297 }
298 for scheme in ["tcp", "ws", "http"] {
299 assert_eq!(scheme_tier(scheme), 1, "{scheme} is plaintext");
300 }
301 for scheme in ["unix", "gopher", ""] {
304 assert_eq!(scheme_tier(scheme), 0, "{scheme} is unclassified");
305 }
306 }
307
308 #[test]
311 fn target_refuses_a_scheme_downgrade() {
312 let secure = url("https://relay.example/");
313 let plain = url("http://relay.example/");
314
315 assert!(refused(Redirect::Follow.target(
316 "http://other.example/",
317 &secure,
318 false
319 )));
320 assert!(refused(Redirect::Follow.target("unix:///tmp/moq.sock", &secure, false)));
321
322 let same = url("https://other.example/");
324 assert_eq!(
325 Redirect::Follow
326 .target("https://other.example/", &secure, false)
327 .unwrap(),
328 Some(same.clone())
329 );
330 assert_eq!(
331 Redirect::Follow
332 .target("https://other.example/", &plain, false)
333 .unwrap(),
334 Some(same)
335 );
336 }
337
338 #[test]
340 fn a_non_special_scheme_classifies_its_literal_host() {
341 for url in [
342 "moqt://127.0.0.1/",
343 "moql://10.0.0.1/",
344 "tcp://169.254.169.254/",
345 "moqt://[::1]/",
346 "moqt://[::ffff:127.0.0.1]/",
347 ] {
348 assert!(is_local(&url.parse().unwrap()), "{url} should be local");
349 }
350 for url in ["moqt://8.8.8.8/", "moql://[2606:4700::1]/", "tcp://relay.example/"] {
351 assert!(!is_local(&url.parse().unwrap()), "{url} should not be local");
352 }
353
354 let public = url("moqt://relay.example/");
355 assert!(
356 refused(Redirect::Follow.target("moqt://169.254.169.254/", &public, false)),
357 "a literal local target is refused whatever the scheme"
358 );
359 }
360
361 #[test]
367 fn a_peer_named_host_is_refused_by_default() {
368 let public = url("https://relay.example/");
369
370 let rebindable = url("https://rebind.attacker.example/");
373 assert!(!is_local(&rebindable), "a hostname is never classified as local");
374 assert_eq!(
375 Redirect::Follow.target(rebindable.as_str(), &public, false).unwrap(),
376 Some(rebindable.clone()),
377 "Follow is explicit trust: it dials the name the peer chose"
378 );
379
380 assert_eq!(Redirect::default(), Redirect::SameHost);
382 assert!(
383 refused(Redirect::default().target(rebindable.as_str(), &public, false)),
384 "a peer-named host is refused without resolving it"
385 );
386 assert_eq!(
387 super::super::Handover::default().redirect,
388 Redirect::SameHost,
389 "and the default config carries that default"
390 );
391 }
392
393 #[test]
396 fn only_an_accepted_redirect_replaces_the_targets() {
397 let current = url("https://relay.example/");
398
399 assert_eq!(Redirect::Follow.target("", ¤t, false).unwrap(), None);
401 assert_eq!(
402 Redirect::Ignore
403 .target("https://relay.example:5443/", ¤t, false)
404 .unwrap(),
405 None
406 );
407
408 for (policy, uri) in [
410 (Redirect::SameHost, "https://other.example/"),
411 (Redirect::Follow, "not a url"),
412 (Redirect::Ignore, "not a url"),
413 (Redirect::Follow, "http://relay.example/"),
414 (Redirect::Follow, "https://127.0.0.1/"),
415 ] {
416 assert!(refused(policy.target(uri, ¤t, false)), "{policy:?}: {uri}");
417 }
418
419 assert_eq!(
421 Redirect::SameHost.target(current.as_str(), ¤t, false).unwrap(),
422 Some(current.clone())
423 );
424 let moved = "https://relay.example:5443/";
425 assert_eq!(
426 Redirect::SameHost.target(moved, ¤t, false).unwrap(),
427 Some(url(moved))
428 );
429 }
430
431 #[test]
434 fn a_certificate_pin_only_covers_encrypted_schemes() {
435 for scheme in ["https", "wss", "moqt", "moql", "tls"] {
436 assert!(encrypted(scheme), "{scheme}");
437 }
438 for scheme in ["http", "ws", "tcp", "unix"] {
439 assert!(!encrypted(scheme), "{scheme}");
440 }
441 assert_eq!(
442 Redirect::Follow
443 .target("tcp://other.example:1/", &url("tcp://relay.example:1/"), true)
444 .unwrap(),
445 Some(url("tcp://other.example:1/")),
446 "a plaintext dial never consulted the pin"
447 );
448 }
449
450 #[test]
453 fn a_certificate_pin_holds_the_host() {
454 let current = url("https://relay.example/");
455 assert!(refused(Redirect::Follow.target(
456 "https://other.example/",
457 ¤t,
458 true
459 )));
460 let moved = "https://relay.example:5443/";
461 assert_eq!(
462 Redirect::Follow.target(moved, ¤t, true).unwrap(),
463 Some(url(moved))
464 );
465 }
466
467 #[test]
470 fn same_host_follows_a_port_not_a_host() {
471 let current = url("https://relay.example:4443/");
472
473 assert!(
474 refused(Redirect::SameHost.target("https://elsewhere.example/", ¤t, false)),
475 "another host is refused"
476 );
477
478 let moved = Redirect::SameHost
479 .target("https://relay.example:5443/", ¤t, false)
480 .unwrap()
481 .unwrap();
482 assert_eq!(
483 moved.port(),
484 Some(5443),
485 "a different port on the same host is followed"
486 );
487 }
488
489 #[test]
490 fn redirect_loop_detection_catches_any_cycle_in_constant_memory() {
491 for tail in 0..4 {
492 for cycle in 2..=8 {
493 let at = |hop: usize| {
495 if hop < tail {
496 url(&format!("tcp://tail{hop}/"))
497 } else {
498 url(&format!("tcp://ring{}/", (hop - tail) % cycle))
499 }
500 };
501 let mut redirects = Redirects::default();
502 let mut caught = None;
503 for hop in 0..4 * (tail + cycle) {
504 let looped = redirects.depart(at(hop), &at(hop + 1));
505 match caught {
506 Some(_) => assert!(looped, "a caught loop stays caught"),
507 None if looped => caught = Some(hop),
508 None => {}
509 }
510 }
511 let caught = caught.unwrap_or_else(|| panic!("tail {tail}, cycle {cycle}: never caught"));
512 assert!(
514 caught + 1 >= tail + cycle,
515 "tail {tail}, cycle {cycle}: caught at {caught}"
516 );
517 }
518 }
519
520 let mut redirects = Redirects::default();
521 for hop in 0..1000 {
522 let from = url(&format!("tcp://a{hop}/"));
523 let to = url(&format!("tcp://a{}/", hop + 1));
524 assert!(!redirects.depart(from, &to), "a one-way run never loops");
525 }
526 }
527
528 #[test]
529 fn an_endpoint_ignores_the_credentials() {
530 assert_eq!(
531 endpoint(&url("tcp://token-a:secret@relay:1/path?jwt=a#x")),
532 endpoint(&url("tcp://token-b@relay:1/path?jwt=b"))
533 );
534 assert_ne!(endpoint(&url("tcp://relay:1/a")), endpoint(&url("tcp://relay:1/b")));
536 }
537
538 #[test]
539 fn a_shown_url_drops_every_credential() {
540 let shown = Shown(&url("moqt://user:pass@relay:4443/.cluster/secret?jwt=token")).to_string();
541 assert_eq!(shown, "moqt://relay:4443");
542 assert_eq!(Shown(&url("unix:///run/moq.sock")).to_string(), "unix:///run/moq.sock");
543 }
544}