iroh_relay/client/
tls.rs

1//! Functionality related to lower-level tls-based connection establishment.
2//!
3//! Primarily to support [`ClientBuilder::connect`].
4//!
5//! This doesn't work in the browser - thus separated into its own file.
6
7// Based on tailscale/derp/derphttp/derphttp_client.go
8
9use std::{collections::VecDeque, net::IpAddr};
10
11use bytes::Bytes;
12use data_encoding::BASE64;
13use http_body_util::Empty;
14use hyper::{Request, upgrade::Parts};
15use hyper_util::rt::TokioIo;
16use n0_error::e;
17use n0_future::{
18    FuturesUnordered, MaybeFuture, StreamExt, task,
19    time::{self},
20};
21use percent_encoding::percent_decode_str;
22use rustls::client::Resumption;
23use tokio::net::TcpStream;
24use tracing::{Instrument, error, info_span};
25
26use super::{
27    streams::{MaybeTlsStream, ProxyStream},
28    *,
29};
30use crate::defaults::timeouts::*;
31
32#[derive(Debug, Clone)]
33pub(super) struct MaybeTlsStreamBuilder {
34    url: Url,
35    dns_resolver: DnsResolver,
36    proxy_url: Option<Url>,
37    prefer_ipv6: bool,
38    tls_config: rustls::ClientConfig,
39}
40
41impl MaybeTlsStreamBuilder {
42    pub(super) fn new(
43        url: Url,
44        dns_resolver: DnsResolver,
45        tls_config: rustls::ClientConfig,
46    ) -> Self {
47        Self {
48            url,
49            dns_resolver,
50            proxy_url: None,
51            prefer_ipv6: false,
52            tls_config,
53        }
54    }
55
56    pub(super) fn proxy_url(mut self, proxy_url: Option<Url>) -> Self {
57        self.proxy_url = proxy_url;
58        self
59    }
60
61    pub(super) fn prefer_ipv6(mut self, prefer: bool) -> Self {
62        self.prefer_ipv6 = prefer;
63        self
64    }
65
66    pub(super) async fn connect(self) -> Result<MaybeTlsStream<ProxyStream>, ConnectError> {
67        let mut config = self.tls_config.clone();
68        config.resumption = Resumption::default();
69        let tls_connector: tokio_rustls::TlsConnector = Arc::new(config).into();
70
71        let tcp_stream = self.dial_url(&tls_connector).await?;
72
73        let local_addr = tcp_stream
74            .local_addr()
75            .map_err(|_| e!(ConnectError::NoLocalAddr))?;
76
77        debug!(server_addr = ?tcp_stream.peer_addr(), %local_addr, "TCP stream connected");
78
79        if self.use_tls() {
80            trace!("Starting TLS handshake");
81            let hostname = self
82                .tls_servername()
83                .ok_or_else(|| e!(ConnectError::InvalidTlsServername))?;
84
85            let hostname = hostname.to_owned();
86            let tls_stream = tls_connector
87                .connect(hostname, tcp_stream)
88                .await
89                .map_err(|err| e!(ConnectError::Tls, err))?;
90            trace!("tls_connector connect success");
91            Ok(MaybeTlsStream::Tls(tls_stream))
92        } else {
93            trace!("Starting handshake");
94            Ok(MaybeTlsStream::Raw(tcp_stream))
95        }
96    }
97
98    fn use_tls(&self) -> bool {
99        // only disable tls if we are explicitly dialing a http url
100        #[allow(clippy::match_like_matches_macro)]
101        match self.url.scheme() {
102            "http" => false,
103            "ws" => false,
104            _ => true,
105        }
106    }
107
108    fn tls_servername(&self) -> Option<rustls::pki_types::ServerName<'_>> {
109        let host_str = self.url.host_str()?;
110        let servername = rustls::pki_types::ServerName::try_from(host_str).ok()?;
111        Some(servername)
112    }
113
114    async fn dial_url(
115        &self,
116        tls_connector: &tokio_rustls::TlsConnector,
117    ) -> Result<ProxyStream, DialError> {
118        if let Some(ref proxy) = self.proxy_url {
119            let stream = self.dial_url_proxy(proxy.clone(), tls_connector).await?;
120            Ok(ProxyStream::Proxied(stream))
121        } else {
122            let stream =
123                dial_happy_eyeballs(&self.dns_resolver, &self.url, self.prefer_ipv6).await?;
124            Ok(ProxyStream::Raw(stream))
125        }
126    }
127
128    async fn dial_url_proxy(
129        &self,
130        proxy_url: Url,
131        tls_connector: &tokio_rustls::TlsConnector,
132    ) -> Result<util::Chain<std::io::Cursor<Bytes>, MaybeTlsStream<tokio::net::TcpStream>>, DialError>
133    {
134        debug!(%self.url, proxy_url = %with_password_masked(&proxy_url), "dial url via proxy");
135
136        let tcp_stream = dial_happy_eyeballs(&self.dns_resolver, &proxy_url, self.prefer_ipv6)
137            .await
138            .map_err(|err| match err {
139                DialError::InvalidTargetPort { meta } => DialError::ProxyInvalidTargetPort { meta },
140                err => err,
141            })?;
142
143        // Setup TLS if necessary
144        let io = if proxy_url.scheme() == "http" {
145            MaybeTlsStream::Raw(tcp_stream)
146        } else {
147            let hostname = proxy_url.host_str().ok_or_else(|| {
148                e!(DialError::ProxyInvalidUrl {
149                    proxy_url: proxy_url.clone()
150                })
151            })?;
152            let hostname =
153                rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|_| {
154                    e!(DialError::ProxyInvalidTlsServername {
155                        proxy_hostname: hostname.to_string()
156                    })
157                })?;
158            let tls_stream = tls_connector.connect(hostname, tcp_stream).await?;
159            MaybeTlsStream::Tls(tls_stream)
160        };
161        let io = TokioIo::new(io);
162
163        let target_host = self.url.host_str().ok_or_else(|| {
164            e!(DialError::InvalidUrl {
165                url: self.url.clone()
166            })
167        })?;
168
169        let port = url_port(&self.url).ok_or_else(|| e!(DialError::InvalidTargetPort))?;
170
171        // Establish Proxy Tunnel
172        let mut req_builder = Request::builder()
173            .uri(format!("{target_host}:{port}"))
174            .method("CONNECT")
175            .header("Host", target_host)
176            .header("Proxy-Connection", "Keep-Alive");
177        if !proxy_url.username().is_empty() {
178            // Passthrough authorization
179            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization
180            debug!(
181                "setting proxy-authorization: username={}",
182                proxy_url.username()
183            );
184            // `Url` keeps the username and password percent-encoded.
185            let mut to_encode: Vec<u8> = percent_decode_str(proxy_url.username()).collect();
186            to_encode.push(b':');
187            to_encode.extend(percent_decode_str(proxy_url.password().unwrap_or_default()));
188            let encoded = BASE64.encode(&to_encode);
189            let mut value = http::HeaderValue::try_from(format!("Basic {encoded}"))
190                .expect("base64 is a valid header value");
191            // Keeps the credentials out of the request's `Debug` output.
192            value.set_sensitive(true);
193            req_builder = req_builder.header("Proxy-Authorization", value);
194        }
195        let req = req_builder
196            .body(Empty::<Bytes>::new())
197            .expect("fixed config");
198
199        debug!("Sending proxy request: {:?}", req);
200
201        let (mut sender, conn) = hyper::client::conn::http1::handshake(io)
202            .await
203            .map_err(|err| e!(DialError::ProxyConnect, err))?;
204        task::spawn(async move {
205            if let Err(err) = conn.with_upgrades().await {
206                error!("Proxy connection failed: {:?}", err);
207            }
208        });
209
210        let res = sender
211            .send_request(req)
212            .await
213            .map_err(|err| e!(DialError::ProxyConnect, err))?;
214        if !res.status().is_success() {
215            return Err(e!(DialError::ProxyConnectInvalidStatus {
216                status: res.status()
217            }));
218        }
219
220        let upgraded = hyper::upgrade::on(res)
221            .await
222            .map_err(|err| e!(DialError::ProxyConnect, err))?;
223        let Parts { io, read_buf, .. } = upgraded
224            .downcast::<TokioIo<MaybeTlsStream<tokio::net::TcpStream>>>()
225            .expect("only this upgrade used");
226
227        let res = util::chain(std::io::Cursor::new(read_buf), io.into_inner());
228
229        Ok(res)
230    }
231}
232
233/// Resolves `url` and races TCP connections across the resulting addresses,
234/// Happy Eyeballs style (RFC 8305).
235///
236/// IPv4 and IPv6 addresses stream in as their lookups resolve and are appended
237/// to a single queue. The loop dials them one at a time, [`pop_family`] taking
238/// the next address interleaved by family, the preferred one (`prefer_ipv6`)
239/// first:
240///
241/// - the first attempt waits a [`RESOLUTION_DELAY`] head start for the preferred
242///   family while only the other family has resolved, and starts immediately
243///   once the preferred family resolves;
244/// - each later attempt starts [`CONNECTION_ATTEMPT_DELAY`] after the previous
245///   one, or as soon as the last in-flight attempt fails, whichever comes first;
246/// - every attempt is itself capped at [`DIAL_ENDPOINT_TIMEOUT`].
247///
248/// The first connection to succeed is returned; the rest are dropped, which
249/// cancels them.
250async fn dial_happy_eyeballs(
251    dns_resolver: &DnsResolver,
252    url: &Url,
253    prefer_ipv6: bool,
254) -> Result<TcpStream, DialError> {
255    let port = url_port(url).ok_or_else(|| e!(DialError::InvalidTargetPort))?;
256
257    // Stream of resolved addresses.
258    let resolve_stream = dns_resolver.resolve_host_all(url, DNS_TIMEOUT);
259    tokio::pin!(resolve_stream);
260    // Set to `true` once `resolve_stream` yielded `None`, to not poll it again after completion.
261    let mut resolve_stream_finished = false;
262    // Addresses resolved but not yet tried, in arrival order.
263    let mut queue: VecDeque<IpAddr> = VecDeque::new();
264    // Family to dial next, toggled to interleave.
265    let mut next_prefer_v6 = prefer_ipv6;
266    // In-progress connection attempts.
267    let mut dials = FuturesUnordered::new();
268    // Whether the first connection attempt has been started yet.
269    let mut started = false;
270    // Last error that occurred, returned if no connection attempt succeeded.
271    let mut last_err: Option<DialError> = None;
272    // Timer after which to start the next connection attempt, or `None` for immediately.
273    let next_dial_delayed_until = MaybeFuture::None;
274    tokio::pin!(next_dial_delayed_until);
275
276    loop {
277        if resolve_stream_finished && queue.is_empty() && dials.is_empty() {
278            // Nothing left to resolve, attempt, or wait on.
279            return Err(last_err.unwrap_or_else(|| e!(DnsError::NoResponse).into()));
280        }
281
282        // The next dial is due and an address is waiting: dial the next address,
283        // interleaved by family, and set the timer for the next attempt.
284        if next_dial_delayed_until.is_none()
285            && let Some(ip) = pop_family(&mut queue, &mut next_prefer_v6)
286        {
287            let addr = SocketAddr::new(ip, port);
288            dials.push(
289                async move {
290                    trace!("connecting TCP stream");
291                    let stream = time::timeout(DIAL_ENDPOINT_TIMEOUT, TcpStream::connect(addr))
292                        .await
293                        .map_err(DialError::from)
294                        .and_then(|res| res.map_err(DialError::from))
295                        .inspect_err(|err| debug!("failed to connect: {err:#}"))?;
296                    trace!("TCP stream connected");
297                    stream.set_nodelay(true)?;
298                    Ok(stream)
299                }
300                .instrument(info_span!("connect", %addr)),
301            );
302            started = true;
303            next_dial_delayed_until
304                .as_mut()
305                .set_future(time::sleep(CONNECTION_ATTEMPT_DELAY));
306        }
307
308        // All three arms are guarded, but it is guaranteed that at least one arm
309        // is enabled, otherwise the check at the top of the loop returns.
310        tokio::select! {
311            biased;
312            // Yields when a dial attempt completed.
313            Some(res) = dials.next(), if !dials.is_empty() => match res {
314                Ok(stream) => return Ok(stream),
315                Err(err) => {
316                    last_err = Some(err);
317                    if dials.is_empty() {
318                        // Fail fast: start the next attempt now rather than waiting it out.
319                        next_dial_delayed_until.as_mut().set_none();
320                    }
321                }
322            },
323            // Yields when the next address is resolved.
324            addr = resolve_stream.next(), if !resolve_stream_finished => {
325                match addr {
326                    Some(Ok(ip)) => {
327                        queue.push_back(ip);
328                        if !started {
329                            // If no connection attempt has been started, and a non-preferred
330                            // address is resolved, delay the connect by `RESOLUTION_DELAY`.
331                            // If a preferred address arrives later but before this delay expires,
332                            // it will be dialed instead.
333                            if prefer_ipv6 == ip.is_ipv6() {
334                                next_dial_delayed_until.as_mut().set_none();
335                            } else if next_dial_delayed_until.is_none() {
336                                next_dial_delayed_until.as_mut().set_future(time::sleep(RESOLUTION_DELAY));
337                            }
338                        }
339                    }
340                    Some(Err(err)) => {
341                        last_err = Some(err.into());
342                    }
343                    None => {
344                        resolve_stream_finished = true;
345                        if !started {
346                            next_dial_delayed_until.as_mut().set_none();
347                        }
348                    }
349                }
350            }
351            // Yields when the next dial attempt is due, if the timer is set.
352            () = &mut next_dial_delayed_until, if next_dial_delayed_until.is_some() => {},
353        }
354    }
355}
356
357/// Removes the next address to attempt, preferring `*next_is_v6`'s family and
358/// flipping it so families interleave; falls back to whatever is available.
359fn pop_family(addrs: &mut VecDeque<IpAddr>, next_is_v6: &mut bool) -> Option<IpAddr> {
360    let idx = addrs
361        .iter()
362        .position(|ip| ip.is_ipv6() == *next_is_v6)
363        .unwrap_or(0);
364    let addr = addrs.remove(idx)?;
365    *next_is_v6 = !*next_is_v6;
366    Some(addr)
367}
368
369fn url_port(url: &Url) -> Option<u16> {
370    if let Some(port) = url.port() {
371        return Some(port);
372    }
373
374    match url.scheme() {
375        "http" | "ws" => Some(80),
376        "https" | "wss" => Some(443),
377        _ => None,
378    }
379}
380
381/// Returns `url` with its password, if it has one, replaced by `***`, so it can be logged.
382fn with_password_masked(url: &Url) -> Url {
383    let mut url = url.clone();
384    if url.password().is_some() {
385        // Cannot fail: a URL that has a password can have one set.
386        url.set_password(Some("***")).ok();
387    }
388    url
389}
390
391#[cfg(test)]
392mod tests {
393    use std::net::{Ipv4Addr, Ipv6Addr};
394
395    use tokio::net::TcpListener;
396
397    use super::*;
398    use crate::test_utils::static_resolver;
399
400    fn relay_url(port: u16) -> Url {
401        format!("http://relay.test:{port}")
402            .parse()
403            .expect("valid url")
404    }
405
406    /// An unreachable IPv4 address (RFC 5737 TEST-NET-1).
407    fn dead_v4(n: u8) -> Ipv4Addr {
408        Ipv4Addr::new(192, 0, 2, n)
409    }
410
411    /// An unreachable IPv6 address (RFC 3849 documentation prefix).
412    fn dead_v6(n: u16) -> Ipv6Addr {
413        Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, n)
414    }
415
416    /// Tests that all addresses are tried until one succeeds.
417    #[tokio::test]
418    async fn tries_addresses_until_one_connects() {
419        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
420        let port = listener.local_addr().unwrap().port();
421
422        let addrs = (1..5).map(dead_v4).chain([Ipv4Addr::LOCALHOST]).collect();
423        let resolver = static_resolver(addrs, vec![]);
424        let stream = dial_happy_eyeballs(&resolver, &relay_url(port), false)
425            .await
426            .expect("should skip the invalid addrs and still connect");
427        assert_eq!(stream.peer_addr().unwrap().ip(), Ipv4Addr::LOCALHOST);
428    }
429
430    /// Tests if the preferred family is unreachable the non-preferred family is used.
431    #[tokio::test]
432    async fn falls_back_from_unreachable_preferred_family() {
433        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
434        let port = listener.local_addr().unwrap().port();
435        let resolver = static_resolver(vec![Ipv4Addr::LOCALHOST], vec![dead_v6(1), dead_v6(2)]);
436
437        let stream = dial_happy_eyeballs(&resolver, &relay_url(port), true)
438            .await
439            .expect("falls back to IPv4");
440        assert!(stream.peer_addr().unwrap().is_ipv4());
441    }
442
443    #[tokio::test]
444    async fn errors_when_all_addresses_unreachable() {
445        let resolver = static_resolver(vec![dead_v4(1), dead_v4(2)], vec![dead_v6(1)]);
446        let err = dial_happy_eyeballs(&resolver, &relay_url(80), true)
447            .await
448            .expect_err("nothing reachable");
449        dbg!(&err);
450        assert!(matches!(
451            err,
452            DialError::Io { .. } | DialError::Timeout { .. }
453        ));
454    }
455
456    #[tokio::test]
457    async fn errors_when_nothing_resolves() {
458        let resolver = static_resolver(vec![], vec![]);
459        let err = dial_happy_eyeballs(&resolver, &relay_url(80), false)
460            .await
461            .expect_err("no addresses to dial");
462        assert!(matches!(err, DialError::Dns { .. }));
463    }
464
465    /// Dials through a fake proxy with the given userinfo and returns the
466    /// `Proxy-Authorization` header the proxy received.
467    ///
468    /// The proxy reads the `CONNECT` request and hangs up, so the dial fails.
469    #[cfg(with_crypto_provider)]
470    async fn proxy_authorization_for(userinfo: &str) -> String {
471        use std::time::Duration;
472
473        use tokio::io::AsyncReadExt;
474
475        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
476        let port = listener.local_addr().unwrap().port();
477        let proxy = task::spawn(async move {
478            let (mut stream, _) = listener.accept().await.unwrap();
479            let mut head = Vec::new();
480            while !head.ends_with(b"\r\n\r\n") {
481                head.push(stream.read_u8().await.unwrap());
482            }
483            String::from_utf8(head).unwrap()
484        });
485
486        let proxy_url = format!("http://{userinfo}@proxy.test:{port}")
487            .parse()
488            .expect("valid url");
489        let resolver = static_resolver(vec![Ipv4Addr::LOCALHOST], vec![]);
490        let res = MaybeTlsStreamBuilder::new(
491            relay_url(443),
492            resolver,
493            crate::tls::make_dangerous_client_config(),
494        )
495        .proxy_url(Some(proxy_url))
496        .connect()
497        .await;
498        assert!(res.is_err(), "the proxy never opens the tunnel");
499
500        let head = time::timeout(Duration::from_secs(5), proxy)
501            .await
502            .expect("the proxy received no request")
503            .unwrap();
504        head.lines()
505            .find_map(|line| {
506                let (name, value) = line.split_once(':')?;
507                name.eq_ignore_ascii_case("proxy-authorization")
508                    .then(|| value.trim().to_string())
509            })
510            .expect("no Proxy-Authorization header")
511    }
512
513    /// Tests that the proxy credentials use the standard base64 alphabet (RFC 7617).
514    #[cfg(with_crypto_provider)]
515    #[tokio::test]
516    async fn proxy_authorization_uses_standard_base64() {
517        // The URL-safe alphabet gives "dXNlcjpzM2NyZXR-fg==".
518        assert_eq!(
519            proxy_authorization_for("user:s3cret~~").await,
520            "Basic dXNlcjpzM2NyZXR+fg=="
521        );
522    }
523
524    /// Tests that the proxy credentials are percent-decoded before they are encoded.
525    #[cfg(with_crypto_provider)]
526    #[tokio::test]
527    async fn proxy_authorization_decodes_credentials() {
528        // `Url` keeps these passwords as "s3cret%3E%3E" and "p%40ss".
529        assert_eq!(
530            proxy_authorization_for("user:s3cret>>").await,
531            "Basic dXNlcjpzM2NyZXQ+Pg=="
532        );
533        assert_eq!(
534            proxy_authorization_for("user:p%40ss").await,
535            "Basic dXNlcjpwQHNz"
536        );
537    }
538
539    /// Tests that the proxy password stays out of the debug log, in the proxy
540    /// URL and in the `Proxy-Authorization` header, while the username is kept.
541    #[cfg(with_crypto_provider)]
542    #[tokio::test]
543    #[n0_tracing_test::traced_test]
544    async fn proxy_credentials_are_not_logged() {
545        proxy_authorization_for("user:s3cret").await;
546        assert!(logs_contain("dial url via proxy"));
547        assert!(logs_contain("Sending proxy request"));
548        assert!(logs_contain("user:***@proxy.test"));
549        assert!(!logs_contain("s3cret"));
550        // "user:s3cret" in base64.
551        assert!(!logs_contain("dXNlcjpzM2NyZXQ="));
552    }
553}