Skip to main content

moq_net/reconnect/
redirect.rs

1//! Judging the URI a peer's GOAWAY names, and catching peers that bounce a connection between them.
2
3use url::Url;
4
5use super::Failure;
6
7/// What to do with the URI a peer names in its GOAWAY.
8///
9/// The URI is dialed exactly as given, so it must carry whatever credentials the
10/// new endpoint needs. Nothing from the current session is copied onto it.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Redirect {
14	/// Follow any URI that does not downgrade the scheme, letting the peer name the
15	/// host as well as the port.
16	///
17	/// The host is dialed as written, so this hands the peer whatever this process
18	/// can reach: a name it controls can carry an A record for loopback, a private
19	/// range, or the metadata service, and nothing here resolves it to find out. A
20	/// *literal* loopback, private, link-local, or IPC target is still refused, but
21	/// that catches a misconfigured peer, not a hostile one. Use it only with an
22	/// upstream trusted with the local network and with the tokens every session presents.
23	Follow,
24	/// Follow only when the host matches the dialed URL, so a peer can move us
25	/// between ports or schemes but not to another host. The default.
26	#[default]
27	SameHost,
28	/// Ignore the URI and redial the current targets.
29	Ignore,
30}
31
32impl Redirect {
33	/// The URL a GOAWAY assigns. `Ok(None)` keeps the current targets (the peer named no
34	/// URI, or the policy ignores a URI it could parse), `Ok(Some)` replaces them, and `Err`
35	/// is an explicit URI this policy refuses. A malformed URI is refused even under
36	/// [`Self::Ignore`].
37	///
38	/// `pinned` is a certificate pin, which can only verify the host it was configured
39	/// for, so it refuses a host change from an encrypted scheme even under [`Self::Follow`].
40	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		// The URI can carry credentials, so the error names the reason, never the URI.
46		// Parse before `Ignore`: a malformed redirect is terminal even when the policy
47		// would otherwise stay on the current targets.
48		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		// Only as far as the URL itself says: a name is dialed, never resolved here,
60		// so this refuses a peer that names a local address outright and says
61		// nothing about one that hides the same address behind a hostname. That gap
62		// is why [`Self::SameHost`] is the default; see [`is_local`].
63		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		// Host only, not the full authority: the port is what a peer legitimately
70		// moves us across when it hands off to a sibling process on the same box.
71		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		// Only an encrypted dial installs the verifier a pin configures; tcp, unix, and
76		// plaintext WebSocket never consult it.
77		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
87/// Whether a dial over `scheme` is encrypted, verifying the peer's certificate.
88fn encrypted(scheme: &str) -> bool {
89	scheme_tier(scheme) == 2
90}
91
92/// Rank a scheme so a peer-supplied redirect cannot silently drop encryption.
93/// Unknown schemes rank lowest, so a forgotten classification is refused.
94fn scheme_tier(scheme: &str) -> u8 {
95	match scheme {
96		"https" | "moqt" | "moql" | "wss" | "tls" => 2,
97		"tcp" | "ws" | "http" => 1,
98		// `unix` lands here deliberately: local IPC is not an upgrade over a
99		// network transport, it is a different reachability class (see `is_local`).
100		_ => 0,
101	}
102}
103
104/// Whether a URL *says* it names something only reachable from this host or
105/// network.
106///
107/// A judgement about the URL, not about where a dial would land. Literals and
108/// `localhost` are decided here; every other name is left alone, since the
109/// address behind it is chosen by whoever runs its DNS and can change between
110/// this call and the dial. So a `false` here means "not local on its face", never
111/// "verified remote".
112fn is_local(url: &Url) -> bool {
113	match url.host() {
114		// A non-special scheme (`moqt://127.1`, and every other scheme but
115		// `http`/`https`/`ws`/`wss`) keeps its host opaque, while the dial resolves it
116		// like an address in any spelling `inet_aton` accepts. Reading it back through
117		// https decodes the same IPv4 spellings (WHATWG's host parser), as js/net does.
118		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				// A trailing dot names the same host from the root.
126				let name = name.strip_suffix('.').unwrap_or(&name);
127				name == "localhost" || name.ends_with(".localhost")
128			}
129			// Unparsable as a special host: judge the opaque text as written.
130			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		// No host at all, e.g. a `unix:` socket path.
138		None => true,
139	}
140}
141
142/// Whether an address literal is one only this host or network can reach.
143fn is_local_ip(ip: std::net::IpAddr) -> bool {
144	match ip {
145		std::net::IpAddr::V4(ip) => is_local_v4(ip),
146		// An IPv4-mapped address reaches the same host as the v4 it wraps, so judge
147		// it by that rather than by the v6 rules.
148		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
159/// Where `url` dials, without its userinfo, query, or fragment, where a peer may mint fresh
160/// credentials on every redirect. Two URLs that differ only there reach the same endpoint.
161pub(super) fn endpoint(url: &Url) -> Url {
162	let mut bare = url.clone();
163	// Only fails for a URL that cannot carry userinfo, which then has none to strip.
164	let _ = bare.set_username("");
165	let _ = bare.set_password(None);
166	bare.set_query(None);
167	bare.set_fragment(None);
168	bare
169}
170
171/// Formats a dial URL for logs and errors as scheme, host, and port only.
172///
173/// A URL can carry a credential in its userinfo, query, or path (raw QUIC has no headers,
174/// so a membership proof rides as a path segment). Dropping all three rather than redacting
175/// known-secret spellings is deliberate: a denylist only covers the credentials that exist
176/// today.
177pub(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			// No host at all, e.g. a `unix:` socket, where the path is the address
184			// rather than a credential and is the only thing that identifies it.
185			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
195/// A run of GOAWAY redirects, and whether it has revisited an endpoint.
196///
197/// The peer picks every hop, so remembering them all would grow without bound. Brent's cycle
198/// detection instead keeps one departed endpoint, replaced at doubling intervals, and catches a
199/// cycle of any length within a few laps of it. Once caught, the run stays a loop until reset.
200pub(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	/// Record leaving `from` for a different endpoint `to`, and return whether this run loops.
220	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	/// Start a new run.
234	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	/// A peer must not be able to redirect us somewhere we could not already
252	/// reach. IPv4-mapped and link-local forms are the easy ones to miss.
253	#[test]
254	fn local_targets_are_recognized() {
255		// Shared with js/net's endpoint test, so the two classifiers cannot drift.
256		#[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		// A public endpoint may not redirect us inward, but a local one may stay local.
268		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	/// The scheme ranking is what stops a peer from quietly moving us off an
291	/// encrypted transport. An unknown scheme ranks lowest so a classification we
292	/// forgot to add is refused rather than trusted.
293	#[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		// `unix` is not an upgrade over a network transport, it is a different
302		// reachability class, so it must not outrank one.
303		for scheme in ["unix", "gopher", ""] {
304			assert_eq!(scheme_tier(scheme), 0, "{scheme} is unclassified");
305		}
306	}
307
308	/// A redirect may hold the scheme or improve it, never weaken it. A downgrade
309	/// is a refusal, not a reason to redial the address the peer is leaving.
310	#[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		// Same tier and upgrades are followed.
323		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	/// Native schemes must classify address literals even when the URL parser returns a domain.
339	#[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	/// The reachability guard reads the URL, so it cannot see a local address
362	/// hiding behind a hostname: any name the peer controls can carry an A record
363	/// for loopback or a private range, and a second lookup at dial time may answer
364	/// differently anyway. The default policy is what closes that, by refusing to
365	/// let a peer name a host at all.
366	#[test]
367	fn a_peer_named_host_is_refused_by_default() {
368		let public = url("https://relay.example/");
369
370		// The bypass: a name is not local on its face, so the reachability guard
371		// passes it through whatever it resolves to.
372		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		// So the default refuses the host change instead of trying to judge it.
381		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	/// Only an explicit URI can assign, and one the policy will not follow is an
394	/// error rather than a quiet fallback: the loop ends on it instead of redialing.
395	#[test]
396	fn only_an_accepted_redirect_replaces_the_targets() {
397		let current = url("https://relay.example/");
398
399		// No URI, or a policy that ignores it: keep the current targets.
400		assert_eq!(Redirect::Follow.target("", &current, false).unwrap(), None);
401		assert_eq!(
402			Redirect::Ignore
403				.target("https://relay.example:5443/", &current, false)
404				.unwrap(),
405			None
406		);
407
408		// An explicit URI the policy will not follow is refused.
409		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, &current, false)), "{policy:?}: {uri}");
417		}
418
419		// An explicit assignment remains an assignment even if its URL is unchanged.
420		assert_eq!(
421			Redirect::SameHost.target(current.as_str(), &current, false).unwrap(),
422			Some(current.clone())
423		);
424		let moved = "https://relay.example:5443/";
425		assert_eq!(
426			Redirect::SameHost.target(moved, &current, false).unwrap(),
427			Some(url(moved))
428		);
429	}
430
431	/// A fingerprint is a Rustls check, installed only on encrypted dials. Schemes that
432	/// never install that verifier must not inherit the pin.
433	#[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	/// A certificate pin verifies only the host it was configured for, so it
451	/// refuses a host change even when the policy would follow one.
452	#[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			&current,
458			true
459		)));
460		let moved = "https://relay.example:5443/";
461		assert_eq!(
462			Redirect::Follow.target(moved, &current, true).unwrap(),
463			Some(url(moved))
464		);
465	}
466
467	/// `SameHost` lets a peer move us between ports or schemes on the endpoint we
468	/// already chose, but not onto a different host.
469	#[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/", &current, false)),
475			"another host is refused"
476		);
477
478		let moved = Redirect::SameHost
479			.target("https://relay.example:5443/", &current, 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				// `tail` one-way moves, then `cycle` endpoints redirecting around a ring.
494				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				// Never before the run first returns to an endpoint it left.
513				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		// The path is part of the request target, so it names a different endpoint.
535		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}