iroh_relay/
server.rs

1//! A fully-fledged iroh-relay server over HTTP or HTTPS.
2//!
3//! This module provides an API to run a full fledged iroh-relay server.  It is primarily
4//! used by the `iroh-relay` binary in this crate.  It can be used to run a relay server in
5//! other locations however.
6//!
7//! This code is fully written in a form of structured-concurrency: every spawned task is
8//! always attached to a handle and when the handle is dropped the tasks abort.  So tasks
9//! can not outlive their handle.  It is also always possible to await for completion of a
10//! task.  Some tasks additionally have a method to do graceful shutdown.
11//!
12//! The relay server hosts the following services:
13//!
14//! - HTTPS `/relay`: The main URL endpoint to which clients connect and sends traffic over.
15//! - HTTPS `/ping`: Used for net_report probes.
16//! - HTTPS `/generate_204`: Used for net_report probes.
17
18use std::{
19    borrow::Cow,
20    future::Future,
21    net::SocketAddr,
22    num::NonZeroU32,
23    path::PathBuf,
24    pin::Pin,
25    sync::{
26        Arc,
27        atomic::{AtomicU64, Ordering},
28    },
29    time::Duration,
30};
31
32use derive_more::Debug;
33use http::{
34    HeaderMap, HeaderValue, Method, Request, Response, StatusCode,
35    header::{AUTHORIZATION, InvalidHeaderValue},
36    response::Builder as ResponseBuilder,
37};
38use http_body_util::Full;
39use hyper::body::Incoming;
40use iroh_base::EndpointId;
41#[cfg(feature = "test-utils")]
42use iroh_base::RelayUrl;
43use n0_error::{e, stack_error};
44use n0_future::{StreamExt, task::AbortOnDropHandle};
45use rustls::server::WantsServerCert;
46use serde::Serialize;
47use tokio::{
48    net::TcpListener,
49    task::{JoinError, JoinSet},
50};
51use tokio_rustls_acme::{
52    acme::{LETS_ENCRYPT_PRODUCTION_DIRECTORY, LETS_ENCRYPT_STAGING_DIRECTORY},
53    caches::DirCache,
54};
55use tracing::{Instrument, debug, error, info, info_span, instrument};
56
57use self::http_server::{BytesBody, HyperError, HyperResult};
58use crate::{
59    defaults::{DEFAULT_KEY_CACHE_CAPACITY, DEFAULT_LISTEN_BACKLOG},
60    http::{AUTH_TOKEN_URL_QUERY_PARAM, ProtocolVersion, RELAY_PROBE_RELATIVE_PATH},
61    quic::server::{QuicServer, QuicSpawnError, ServerHandle as QuicServerHandle},
62    tls::CaTlsConfig,
63};
64
65pub mod client;
66pub mod clients;
67pub mod http_server;
68mod metrics;
69pub(crate) mod resolver;
70pub mod streams;
71#[cfg(feature = "test-utils")]
72pub mod testing;
73
74pub use self::{
75    http_server::{Handlers, RelayService},
76    metrics::{Metrics, RelayMetrics},
77    resolver::{DEFAULT_CERT_RELOAD_INTERVAL, reloading_resolver},
78};
79
80const NO_CONTENT_CHALLENGE_HEADER: &str = "X-Iroh-Challenge";
81const NO_CONTENT_RESPONSE_HEADER: &str = "X-Iroh-Response";
82const NOTFOUND: &[u8] = b"Not Found";
83const ROBOTS_TXT: &[u8] = b"User-agent: *\nDisallow: /\n";
84const INDEX: &[u8] = br#"<html><body>
85<h1>Iroh Relay</h1>
86<p>
87  This is an <a href="https://iroh.computer/">Iroh</a> Relay server.
88</p>
89"#;
90const TLS_HEADERS: [(&str, &str); 2] = [
91    (
92        "Strict-Transport-Security",
93        "max-age=63072000; includeSubDomains",
94    ),
95    (
96        "Content-Security-Policy",
97        "default-src 'none'; frame-ancestors 'none'; form-action 'none'; base-uri 'self'; block-all-mixed-content; plugin-types 'none'",
98    ),
99];
100
101/// Creates a new [`BytesBody`] with no content.
102fn body_empty() -> BytesBody {
103    Box::new(http_body_util::Full::new(hyper::body::Bytes::new()))
104}
105
106/// Configuration for the full Relay.
107///
108/// Be aware the generic parameters are for when using the Let's Encrypt TLS configuration.
109/// If not used dummy ones need to be provided, e.g. `ServerConfig::<(), ()>::default()`.
110#[derive(Debug, Default)]
111#[non_exhaustive]
112pub struct ServerConfig {
113    /// Configuration for the Relay server, disabled if `None`.
114    pub relay: Option<RelayConfig>,
115    /// Configuration for the QUIC server, disabled if `None`.
116    pub quic: Option<QuicConfig>,
117    /// Socket to serve metrics on.
118    #[cfg(feature = "metrics")]
119    pub metrics_addr: Option<SocketAddr>,
120}
121
122/// Configuration for the Relay HTTP and HTTPS server.
123///
124/// This includes the HTTP services hosted by the Relay server, the Relay `/relay` HTTP
125/// endpoint is only one of the services served.
126#[derive(Debug)]
127#[non_exhaustive]
128pub struct RelayConfig {
129    /// The socket address on which the Relay HTTP server should bind.
130    ///
131    /// Normally you'd choose port `80`.  The bind address for the HTTPS server is
132    /// configured in [`RelayConfig::tls`].
133    ///
134    /// If [`RelayConfig::tls`] is `None` then this serves all the HTTP services without
135    /// TLS.
136    pub http_bind_addr: SocketAddr,
137    /// TLS configuration for the HTTPS server.
138    ///
139    /// If *None* all the HTTP services that would be served here are served from
140    /// [`RelayConfig::http_bind_addr`].
141    pub tls: Option<TlsConfig>,
142    /// Rate limits.
143    pub limits: Limits,
144    /// Key cache capacity.
145    pub key_cache_capacity: Option<usize>,
146    /// Listen queue length (defaults to 1024, capped by `net.core.somaxconn` on Linux).
147    pub listen_backlog: Option<u32>,
148    /// Access control for incoming connections.
149    pub access: Arc<dyn DynAccessControl>,
150}
151
152impl RelayConfig {
153    /// Creates a new [`RelayConfig`] bound to `http_bind_addr` with default settings.
154    ///
155    /// TLS is disabled, default [`Limits`] are used, the key cache capacity is unset, and
156    /// access defaults to [`AllowAll`]. Adjust any of these by assigning to the
157    /// corresponding fields after construction.
158    pub fn new(http_bind_addr: impl Into<SocketAddr>) -> Self {
159        Self {
160            http_bind_addr: http_bind_addr.into(),
161            tls: None,
162            limits: Limits::default(),
163            key_cache_capacity: None,
164            listen_backlog: None,
165            access: Arc::new(AllowAll),
166        }
167    }
168}
169
170/// A process-unique identifier for a single relay client connection.
171///
172/// A new id is assigned to every incoming connection when its [`ClientRequest`]
173/// is created, before the access check runs. The same id is passed to
174/// [`AccessControl::on_connect`] and [`AccessControl::on_disconnect`], so an
175/// implementation can match the two callbacks even when one endpoint holds
176/// several concurrent connections.
177#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, derive_more::Display)]
178#[display("{_0}")]
179pub struct ConnectionId(u64);
180
181impl ConnectionId {
182    /// Returns a fresh, process-unique connection id.
183    fn next() -> Self {
184        static NEXT: AtomicU64 = AtomicU64::new(0);
185        Self(NEXT.fetch_add(1, Ordering::Relaxed))
186    }
187}
188
189/// Details about an incoming relay client connection.
190///
191/// Passed to [`AccessControl::on_connect`] to decide whether to admit the connection.
192#[derive(Debug, Clone)]
193pub struct ClientRequest {
194    connection_id: ConnectionId,
195    endpoint_id: EndpointId,
196    protocol_version: ProtocolVersion,
197    request: http::request::Parts,
198}
199
200impl ClientRequest {
201    /// Creates a new [`ClientRequest`] from an [`EndpointId`] and HTTP request parts.
202    ///
203    /// The [`EndpointId`] must be proven by the relay handshake. The request parts
204    /// come from the client's WebSocket request. A fresh [`ConnectionId`] is assigned.
205    pub fn new(
206        endpoint_id: EndpointId,
207        protocol_version: ProtocolVersion,
208        request: http::request::Parts,
209    ) -> Self {
210        Self {
211            connection_id: ConnectionId::next(),
212            endpoint_id,
213            protocol_version,
214            request,
215        }
216    }
217
218    /// Returns the [`ConnectionId`] assigned to this connection.
219    pub fn connection_id(&self) -> ConnectionId {
220        self.connection_id
221    }
222
223    /// Returns the [`ProtocolVersion`] negotiated for this connection.
224    pub fn protocol_version(&self) -> ProtocolVersion {
225        self.protocol_version
226    }
227
228    /// Returns the [`EndpointId`] of the client.
229    ///
230    /// The relay handshake authenticates this id before the access hook
231    /// is invoked. The client proves possession of the secret key for
232    /// this public key by either signing keying material exported from
233    /// the TLS session or a challenge issued by the server.
234    pub fn endpoint_id(&self) -> EndpointId {
235        self.endpoint_id
236    }
237
238    /// Returns the URI of the HTTP request with which the client connected.
239    pub fn uri(&self) -> &http::Uri {
240        &self.request.uri
241    }
242
243    /// Returns an iterator over the query parameters set in the URI of the HTTP request.
244    ///
245    /// Each item is a `(name, value)` pair. Both names and values are percent-decoded.
246    /// The query string is parsed in order, and the same name may appear more than once.
247    pub fn query_pairs(&self) -> impl Iterator<Item = (Cow<'_, str>, Cow<'_, str>)> {
248        url::form_urlencoded::parse(self.request.uri.query().unwrap_or("").as_bytes())
249    }
250
251    /// Returns the headers of the HTTP request with which the client connected.
252    pub fn headers(&self) -> &http::HeaderMap {
253        &self.request.headers
254    }
255
256    /// Returns the authorization token from the client's HTTP request, if any.
257    ///
258    /// Walks the `Authorization` headers in order and returns the value of
259    /// the first one whose scheme is `Bearer` (matched case-insensitively).
260    /// Headers with a different scheme are skipped.
261    ///
262    /// If none of the `Authorization` headers carries a `Bearer` scheme,
263    /// returns the value of the `token` URL query parameter, or `None` if
264    /// the URL has no `token` parameter.
265    ///
266    /// If an `Authorization` header value is not valid UTF-8 the function returns
267    /// `None` immediately, without checking later headers or the URL query.
268    pub fn auth_token(&self) -> Option<String> {
269        for value in self.request.headers.get_all(AUTHORIZATION) {
270            let value = value.to_str().ok()?;
271            if let Some((scheme, token)) = value.split_once(' ')
272                && scheme.eq_ignore_ascii_case("Bearer")
273            {
274                return Some(token.to_string());
275            }
276        }
277        self.query_pairs()
278            .find(|(name, _)| name == AUTH_TOKEN_URL_QUERY_PARAM)
279            .map(|(_, value)| value.into_owned())
280    }
281}
282
283/// Controls which endpoints may use the relay and observes their lifecycle.
284///
285/// Implement this trait to gate access to a relay server.
286///
287/// Both callbacks carry the connection's [`ConnectionId`], so an implementation
288/// can index connections precisely even when one endpoint holds several.
289pub trait AccessControl: std::fmt::Debug + Send + Sync + 'static {
290    /// Decides whether a connecting client is admitted.
291    ///
292    /// Called once per incoming connection, before the connection is
293    /// registered. Returns [`Access::Allow`] to admit it or [`Access::Deny`]
294    /// to reject it.
295    ///
296    /// Can be implemented as `async fn on_connect(&self, request: &ClientRequest) -> Access`.
297    fn on_connect(&self, request: &ClientRequest) -> impl Future<Output = Access> + Send;
298
299    /// Notifies that a connection has ended.
300    ///
301    /// Called once for every connection that [`Self::on_connect`] admitted,
302    /// identified by the same [`ConnectionId`].
303    ///
304    /// Note that this is a sync method being called in an async context. Make sure that your
305    /// implementation does not block the runtime.
306    fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId) {
307        let _ = (endpoint_id, connection_id);
308    }
309}
310
311/// A dyn-compatible version of [`AccessControl`] that returns boxed futures.
312///
313/// Any type that implements [`AccessControl`] automatically implements
314/// `DynAccessControl`. Wrap it in an `Arc` to store it as an
315/// `Arc<dyn DynAccessControl>`, for example in [`RelayConfig::access`].
316pub trait DynAccessControl: std::fmt::Debug + Send + Sync + 'static {
317    /// See [`AccessControl::on_connect`].
318    fn on_connect<'a>(
319        &'a self,
320        request: &'a ClientRequest,
321    ) -> Pin<Box<dyn Future<Output = Access> + Send + 'a>>;
322
323    /// See [`AccessControl::on_disconnect`].
324    fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId);
325}
326
327impl<T: AccessControl> DynAccessControl for T {
328    fn on_connect<'a>(
329        &'a self,
330        request: &'a ClientRequest,
331    ) -> Pin<Box<dyn Future<Output = Access> + Send + 'a>> {
332        Box::pin(<Self as AccessControl>::on_connect(self, request))
333    }
334
335    fn on_disconnect(&self, endpoint_id: EndpointId, connection_id: ConnectionId) {
336        <Self as AccessControl>::on_disconnect(self, endpoint_id, connection_id)
337    }
338}
339
340/// An [`AccessControl`] that admits every endpoint.
341///
342/// This is the default used by [`RelayConfig::new`].
343#[derive(Debug, Clone, Copy)]
344pub struct AllowAll;
345
346impl AccessControl for AllowAll {
347    async fn on_connect(&self, _request: &ClientRequest) -> Access {
348        Access::Allow
349    }
350}
351
352/// Access restriction for an endpoint.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub enum Access {
355    /// Access is allowed.
356    Allow,
357    /// Access is denied.
358    Deny {
359        /// Optional reason for denial to send back to the client.
360        reason: Option<String>,
361    },
362}
363
364/// Reports a connection's disconnect to [`AccessControl`] when dropped.
365///
366/// A guard is created the moment [`AccessControl::on_connect`] admits a
367/// connection, and is then held for the connection's entire lifetime. Dropping
368/// it - whether the connection closed cleanly, hit an error, or setup returned
369/// early - calls [`AccessControl::on_disconnect`] exactly once.
370///
371/// Threading the guard through connection setup and into the connection actor
372/// makes it impossible to admit a connection without eventually reporting its
373/// disconnect, even as the surrounding code changes.
374///
375/// Embedders that register connections through [`Clients::register`] construct
376/// the guard themselves; see that method for the expected lifecycle.
377///
378/// [`Clients::register`]: crate::server::clients::Clients::register
379#[derive(Debug)]
380pub struct OnDisconnectGuard {
381    access: Option<Arc<dyn DynAccessControl>>,
382    endpoint_id: EndpointId,
383    connection_id: ConnectionId,
384}
385
386impl OnDisconnectGuard {
387    /// Creates a guard for the connection described by `request`.
388    ///
389    /// Dropping the guard calls [`AccessControl::on_disconnect`] on `access`
390    /// with the request's [`EndpointId`] and [`ConnectionId`]. Create it only
391    /// once [`AccessControl::on_connect`] has admitted the connection.
392    pub fn for_access_control(access: Arc<dyn DynAccessControl>, request: &ClientRequest) -> Self {
393        Self {
394            access: Some(access),
395            endpoint_id: request.endpoint_id(),
396            connection_id: request.connection_id(),
397        }
398    }
399
400    /// Creates a no-op guard for `endpoint_id`.
401    ///
402    /// The guard carries `endpoint_id` and a fresh [`ConnectionId`] but has no
403    /// access control attached, so dropping it does nothing.
404    pub fn empty(endpoint_id: EndpointId) -> Self {
405        Self {
406            access: None,
407            endpoint_id,
408            connection_id: ConnectionId::next(),
409        }
410    }
411
412    /// Returns the [`EndpointId`] of the guarded connection.
413    pub fn endpoint_id(&self) -> EndpointId {
414        self.endpoint_id
415    }
416
417    /// Returns the [`ConnectionId`] of the guarded connection.
418    pub fn connection_id(&self) -> ConnectionId {
419        self.connection_id
420    }
421}
422
423impl Drop for OnDisconnectGuard {
424    fn drop(&mut self) {
425        if let Some(access) = self.access.as_ref() {
426            access.on_disconnect(self.endpoint_id, self.connection_id);
427        }
428    }
429}
430
431/// Configuration for the QUIC server.
432#[derive(Debug)]
433#[non_exhaustive]
434pub struct QuicConfig {
435    /// The socket address on which the QUIC server should bind.
436    ///
437    /// Normally you'd chose port `7842`, see [`crate::defaults::DEFAULT_RELAY_QUIC_PORT`].
438    pub bind_addr: SocketAddr,
439    /// The TLS server configuration for the QUIC server.
440    ///
441    /// If this [`rustls::ServerConfig`] does not support TLS 1.3, the QUIC server will fail
442    /// to spawn.
443    ///
444    /// Will use the TLS config from [`RelayConfig::tls`] if unset. If neither is set the QUIC
445    /// server will fail to spawn.
446    pub server_config: Option<rustls::ServerConfig>,
447}
448
449impl QuicConfig {
450    /// Creates a new [`QuicConfig`] bound to `bind_addr`.
451    ///
452    /// The TLS server config is left unset and inherited from [`RelayConfig::tls`].
453    pub fn new(bind_addr: impl Into<SocketAddr>) -> Self {
454        Self {
455            bind_addr: bind_addr.into(),
456            server_config: None,
457        }
458    }
459}
460
461/// TLS configuration for Relay server.
462///
463/// Normally the Relay server accepts connections on both HTTPS and HTTP.
464#[derive(Debug)]
465#[non_exhaustive]
466pub struct TlsConfig {
467    /// The socket address on which to serve the HTTPS server.
468    ///
469    /// Since the captive portal probe has to run over plain text HTTP and TLS is used for
470    /// the main relay server this has to be on a different port.  When TLS is not enabled
471    /// this is served on the [`RelayConfig::http_bind_addr`] socket address.
472    ///
473    /// Normally you'd choose port `443`.
474    pub https_bind_addr: SocketAddr,
475    /// Mode for getting a cert.
476    pub cert: CertConfig,
477}
478
479impl TlsConfig {
480    /// Creates a new [`TlsConfig`] with the given bind address and certificate configuration.
481    pub fn new(https_bind_addr: impl Into<SocketAddr>, cert: CertConfig) -> Self {
482        Self {
483            https_bind_addr: https_bind_addr.into(),
484            cert,
485        }
486    }
487}
488
489/// Rate limits.
490// TODO: accept_conn_limit and accept_conn_burst are not currently implemented.
491#[derive(Debug, Default)]
492#[non_exhaustive]
493pub struct Limits {
494    /// Rate limits for incoming traffic from a client connection.
495    pub client_rx: Option<ClientRateLimit>,
496    /// Rate limit for accepting new connections. Unlimited if not set.
497    ///
498    /// Not currently implemented, setting this has no effect.
499    pub accept_conn_limit: Option<f64>,
500    /// Burst limit for accepting new connections. Unlimited if not set.
501    ///
502    /// Not currently implemented, setting this has no effect.
503    pub accept_conn_burst: Option<usize>,
504}
505
506/// Per-client rate limit configuration.
507#[derive(Debug, Copy, Clone, PartialEq, Eq)]
508#[non_exhaustive]
509pub struct ClientRateLimit {
510    /// Max number of bytes per second to read from the client connection.
511    pub bytes_per_second: NonZeroU32,
512    /// Max number of bytes to read in a single burst.
513    pub max_burst_bytes: Option<NonZeroU32>,
514}
515
516impl ClientRateLimit {
517    /// Creates a new [`ClientRateLimit`] with the given byte rate.
518    ///
519    /// `max_burst_bytes` is left unset; assign it after construction to allow bursting.
520    pub fn new(bytes_per_second: NonZeroU32) -> Self {
521        Self {
522            bytes_per_second,
523            max_burst_bytes: None,
524        }
525    }
526}
527
528/// TLS certificate configuration.
529#[derive(Debug)]
530#[non_exhaustive]
531pub enum CertConfig {
532    /// Use Let's Encrypt.
533    LetsEncrypt {
534        /// Configuration for the ACME client.
535        acme_config: AcmeConfig,
536        /// Builder for the [`rustls::ServerConfig`].
537        ///
538        /// The ACME resolver will be injected when starting the server.
539        server_config_builder: rustls::ConfigBuilder<rustls::ServerConfig, WantsServerCert>,
540    },
541    /// Use a TLS key and certificate chain that can be reloaded.
542    Manual {
543        /// The [`rustls::ServerConfig`] to use.
544        ///
545        /// This needs to have the certificates or a certificate loader, it will be used by the server as-is.
546        server_config: rustls::ServerConfig,
547    },
548}
549
550/// Configuration for the ACME client.
551#[derive(Debug, Clone)]
552pub struct AcmeConfig {
553    pub(crate) directory_url: String,
554    pub(crate) domains: Vec<String>,
555    pub(crate) contact: Vec<String>,
556    pub(crate) cache_path: Option<PathBuf>,
557    pub(crate) tls_config: CaTlsConfig,
558}
559
560impl AcmeConfig {
561    /// Creates a new [`AcmeConfig`] with a ACME directory URL.
562    pub fn new(directory_url: String) -> Self {
563        Self {
564            directory_url,
565            domains: Vec::new(),
566            contact: Vec::new(),
567            cache_path: None,
568            tls_config: CaTlsConfig::default(),
569        }
570    }
571
572    /// Creates a new [`AcmeConfig`] with the Let's Encrypt directory URL.
573    pub fn letsencrypt(production: bool) -> Self {
574        let url = if production {
575            LETS_ENCRYPT_PRODUCTION_DIRECTORY
576        } else {
577            LETS_ENCRYPT_STAGING_DIRECTORY
578        };
579        Self::new(url.to_string())
580    }
581
582    /// Provides the list of domains for which certificates should be obtained.
583    pub fn domains(mut self, domains: Vec<String>) -> Self {
584        self.domains = domains;
585        self
586    }
587
588    /// Provides a list of contacts for the account.
589    ///
590    /// Note that email addresses must include a `mailto:` prefix.
591    pub fn contact(mut self, contact: Vec<String>) -> Self {
592        self.contact = contact;
593        self
594    }
595
596    /// Sets the directory where to cache certificates.
597    ///
598    /// If not called certificates will not be cached.
599    pub fn cache_path(mut self, path: PathBuf) -> Self {
600        self.cache_path = Some(path);
601        self
602    }
603
604    /// Sets the [`CaTlsConfig`] used to verify the ACME server's TLS certificate.
605    ///
606    /// Defaults to [`CaTlsConfig::embedded`]. Set a config with extra roots when targeting
607    /// an ACME server whose certificate is not signed by a publicly trusted CA, such as a
608    /// local test server.
609    pub fn tls_config(mut self, tls_config: CaTlsConfig) -> Self {
610        self.tls_config = tls_config;
611        self
612    }
613}
614
615/// A running Relay + QAD server.
616///
617/// This is a full Relay server, including QAD, Relay and various associated HTTP services.
618///
619/// Dropping this will stop the server.
620#[derive(Debug)]
621pub struct Server {
622    /// The address of the HTTP server, if configured.
623    http_addr: Option<SocketAddr>,
624    /// The address of the HTTPS server, if the relay server is using TLS.
625    ///
626    /// If the Relay server is not using TLS then it is served from the
627    /// [`Server::http_addr`].
628    https_addr: Option<SocketAddr>,
629    /// The address of the QUIC server, if configured.
630    quic_addr: Option<SocketAddr>,
631    /// Handle to the relay server.
632    relay_handle: Option<http_server::ServerHandle>,
633    /// Handle to the relay service for runtime control.
634    relay_service: Option<http_server::RelayService>,
635    /// Handle to the quic server.
636    quic_handle: Option<QuicServerHandle>,
637    /// The main task running the server.
638    supervisor: AbortOnDropHandle<Result<(), SupervisorError>>,
639    metrics: RelayMetrics,
640    metrics_server: Option<iroh_metrics::service::MetricsServer>,
641}
642
643/// Server spawn errors
644#[allow(missing_docs)]
645#[stack_error(derive, add_meta, std_sources)]
646#[non_exhaustive]
647pub enum SpawnError {
648    #[error("Unable to get local address")]
649    LocalAddr { source: std::io::Error },
650    #[error("Failed to bind QAD listener")]
651    QuicSpawn { source: QuicSpawnError },
652    #[error("Failed to parse TLS header")]
653    TlsHeaderParse { source: InvalidHeaderValue },
654    #[error("Failed to bind TcpListener")]
655    BindTlsListener { source: std::io::Error },
656    #[error("Failed to build ACME client TLS config")]
657    AcmeClientTlsConfig {
658        #[error(std_err)]
659        source: std::io::Error,
660    },
661    #[error("No local address")]
662    NoLocalAddr { source: std::io::Error },
663    #[error("Failed to bind server socket to {addr}")]
664    BindTcpListener {
665        source: std::io::Error,
666        addr: SocketAddr,
667    },
668    #[error("Error starting metrics server")]
669    Metrics {
670        #[error(std_err)]
671        source: std::io::Error,
672    },
673}
674
675/// Server task errors
676#[allow(missing_docs)]
677#[stack_error(derive, add_meta)]
678#[non_exhaustive]
679pub enum SupervisorError {
680    #[error("Acme event stream finished")]
681    AcmeEventStreamFinished {},
682    #[error(transparent)]
683    JoinError {
684        #[error(from, std_err)]
685        source: JoinError,
686    },
687    #[error("No relay services are enabled")]
688    NoRelayServicesEnabled {},
689    #[error("Task cancelled")]
690    TaskCancelled {},
691}
692
693impl Server {
694    /// Starts the server.
695    pub async fn spawn(config: ServerConfig) -> Result<Self, SpawnError> {
696        let mut tasks = JoinSet::new();
697
698        let metrics = RelayMetrics::default();
699
700        #[cfg(not(feature = "metrics"))]
701        let metrics_server = None;
702
703        #[cfg(feature = "metrics")]
704        let metrics_server = if let Some(addr) = config.metrics_addr {
705            debug!("Starting metrics server");
706            let mut registry = iroh_metrics::Registry::default();
707            registry.register_all(&metrics);
708            let server = iroh_metrics::service::MetricsServer::spawn(addr, Arc::new(registry))
709                .await
710                .map_err(|err| e!(SpawnError::Metrics, err))?;
711            Some(server)
712        } else {
713            None
714        };
715
716        let (relay_server, http_addr, tls_config) = match config.relay {
717            Some(relay_config) => {
718                debug!("Starting Relay server");
719                let mut headers = HeaderMap::new();
720                for (name, value) in TLS_HEADERS.iter() {
721                    headers.insert(
722                        *name,
723                        value
724                            .parse()
725                            .map_err(|err| e!(SpawnError::TlsHeaderParse, err))?,
726                    );
727                }
728                let relay_bind_addr = match relay_config.tls {
729                    Some(ref tls) => tls.https_bind_addr,
730                    None => relay_config.http_bind_addr,
731                };
732                let key_cache_capacity = relay_config
733                    .key_cache_capacity
734                    .unwrap_or(DEFAULT_KEY_CACHE_CAPACITY);
735                let mut builder = http_server::ServerBuilder::new(relay_bind_addr)
736                    .metrics(metrics.server.clone())
737                    .headers(headers)
738                    .key_cache_capacity(key_cache_capacity)
739                    .listen_backlog(
740                        relay_config
741                            .listen_backlog
742                            .unwrap_or(DEFAULT_LISTEN_BACKLOG),
743                    )
744                    .access(relay_config.access)
745                    .request_handler(Method::GET, "/", Box::new(root_handler))
746                    .request_handler(Method::GET, "/index.html", Box::new(root_handler))
747                    .request_handler(Method::GET, probe_route(), Box::new(probe_handler))
748                    .request_handler(Method::GET, "/robots.txt", Box::new(robots_handler))
749                    .request_handler(Method::GET, "/healthz", Box::new(healthz_handler));
750                if let Some(cfg) = relay_config.limits.client_rx {
751                    builder = builder.client_rx_ratelimit(cfg);
752                }
753                let (http_addr, tls_config) = match relay_config.tls {
754                    Some(tls_config) => {
755                        let server_tls_config = match tls_config.cert {
756                            CertConfig::LetsEncrypt {
757                                acme_config,
758                                server_config_builder,
759                            } => {
760                                let cache = acme_config.cache_path.map(DirCache::new);
761                                let crypto_provider =
762                                    server_config_builder.crypto_provider().clone();
763                                let client_tls_config = acme_config
764                                    .tls_config
765                                    .client_config(crypto_provider)
766                                    .map_err(|err| e!(SpawnError::AcmeClientTlsConfig, err))?;
767                                let config =
768                                    tokio_rustls_acme::AcmeConfig::new_with_client_tls_config(
769                                        acme_config.domains,
770                                        Arc::new(client_tls_config),
771                                    )
772                                    .contact(acme_config.contact)
773                                    .directory(acme_config.directory_url)
774                                    .cache_option(cache);
775                                let mut state = config.state();
776                                let resolver = state.resolver().clone();
777                                let server_config =
778                                    server_config_builder.with_cert_resolver(resolver);
779                                let acceptor =
780                                    http_server::TlsAcceptor::LetsEncrypt(state.acceptor());
781                                tasks.spawn(
782                                    async move {
783                                        while let Some(event) = state.next().await {
784                                            match event {
785                                                Ok(ok) => debug!("acme event: {ok:?}"),
786                                                Err(err) => error!("error: {err:?}"),
787                                            }
788                                        }
789                                        Err(e!(SupervisorError::AcmeEventStreamFinished))
790                                    }
791                                    .instrument(info_span!("acme")),
792                                );
793                                http_server::TlsConfig {
794                                    config: Arc::new(server_config),
795                                    acceptor,
796                                }
797                            }
798                            CertConfig::Manual { server_config } => {
799                                let server_config = Arc::new(server_config);
800                                let acceptor =
801                                    tokio_rustls::TlsAcceptor::from(server_config.clone());
802                                let acceptor = http_server::TlsAcceptor::Manual(acceptor);
803                                http_server::TlsConfig {
804                                    config: server_config,
805                                    acceptor,
806                                }
807                            }
808                        };
809                        builder = builder.tls_config(Some(server_tls_config.clone()));
810
811                        // Some services always need to be served over HTTP without TLS.  Run
812                        // these standalone.
813                        let http_listener = TcpListener::bind(&relay_config.http_bind_addr)
814                            .await
815                            .map_err(|err| e!(SpawnError::BindTlsListener, err))?;
816                        let http_addr = http_listener
817                            .local_addr()
818                            .map_err(|err| e!(SpawnError::NoLocalAddr, err))?;
819                        tasks.spawn(
820                            async move {
821                                run_captive_portal_service(http_listener).await;
822                                Ok(())
823                            }
824                            .instrument(info_span!("http-service", addr = %http_addr)),
825                        );
826                        (Some(http_addr), Some(server_tls_config))
827                    }
828                    None => {
829                        // If running Relay without TLS add the plain HTTP server directly
830                        // to the Relay server.
831                        builder = builder.request_handler(
832                            Method::GET,
833                            "/generate_204",
834                            Box::new(serve_no_content_handler),
835                        );
836                        (None, None)
837                    }
838                };
839                let relay_server = builder.spawn()?;
840                (Some(relay_server), http_addr, tls_config)
841            }
842            None => (None, None, None),
843        };
844        // If http_addr is Some then relay_server is serving HTTPS.  If http_addr is None
845        // relay_server is serving HTTP, including the /generate_204 service.
846        let relay_addr = relay_server.as_ref().map(|srv| srv.addr());
847        let relay_handle = relay_server.as_ref().map(|srv| srv.handle());
848        let relay_service = relay_server.as_ref().map(|srv| srv.service().clone());
849
850        let quic_server = match config.quic {
851            Some(quic_config) => {
852                debug!("Starting QUIC server {}", quic_config.bind_addr);
853                let server_config = quic_config
854                    .server_config
855                    .or(tls_config.map(|config| (*config.config).clone()))
856                    .ok_or_else(|| {
857                        e!(SpawnError::QuicSpawn, e!(QuicSpawnError::TlsNotConfigured))
858                    })?;
859                Some(
860                    QuicServer::spawn(quic_config.bind_addr, server_config, metrics.server.clone())
861                        .map_err(|err| e!(SpawnError::QuicSpawn, err))?,
862                )
863            }
864            None => None,
865        };
866        let quic_addr = quic_server.as_ref().map(|srv| srv.bind_addr());
867        let quic_handle = quic_server.as_ref().map(|srv| srv.handle());
868
869        let task = tokio::spawn(relay_supervisor(tasks, relay_server, quic_server));
870
871        Ok(Self {
872            http_addr: http_addr.or(relay_addr),
873            https_addr: http_addr.and(relay_addr),
874            quic_addr,
875            relay_handle,
876            relay_service,
877            quic_handle,
878            supervisor: AbortOnDropHandle::new(task),
879            metrics,
880            metrics_server,
881        })
882    }
883
884    /// Requests graceful shutdown.
885    ///
886    /// Returns once all server tasks have stopped.
887    pub async fn shutdown(self) -> Result<(), SupervisorError> {
888        // Only the Relay server and QUIC server need shutting down, the supervisor will abort the tasks in
889        // the JoinSet when the server terminates.
890        if let Some(handle) = self.relay_handle {
891            handle.shutdown();
892        }
893        if let Some(handle) = self.quic_handle {
894            handle.shutdown();
895        }
896        if let Some(server) = self.metrics_server {
897            server.shutdown().await;
898        }
899        self.supervisor.await?
900    }
901
902    /// Waits for the server's supervisor task to finish.
903    ///
904    /// Returns the exit result of the supervisor task. Unlike [`Self::shutdown`], this does
905    /// *not* request shutdown, it only waits for the server to terminate on its own (for
906    /// example, after an internal error or because the supervisor was aborted from
907    /// elsewhere). The outer [`JoinError`] is only produced if the supervisor task itself
908    /// panics or is aborted.
909    pub async fn join(&mut self) -> Result<Result<(), SupervisorError>, JoinError> {
910        (&mut self.supervisor).await
911    }
912
913    /// The socket address the HTTPS server is listening on.
914    pub fn https_addr(&self) -> Option<SocketAddr> {
915        self.https_addr
916    }
917
918    /// The socket address the HTTP server is listening on.
919    pub fn http_addr(&self) -> Option<SocketAddr> {
920        self.http_addr
921    }
922
923    /// The socket address the QUIC server is listening on.
924    pub fn quic_addr(&self) -> Option<SocketAddr> {
925        self.quic_addr
926    }
927
928    /// Get the server's https [`RelayUrl`].
929    ///
930    /// This uses [`Self::https_addr`] so it's mostly useful for local development.
931    #[cfg(feature = "test-utils")]
932    pub fn https_url(&self) -> Option<RelayUrl> {
933        self.https_addr.map(|addr| {
934            url::Url::parse(&format!("https://{addr}"))
935                .expect("valid url")
936                .into()
937        })
938    }
939
940    /// Get the server's http [`RelayUrl`].
941    ///
942    /// This uses [`Self::http_addr`] so it's mostly useful for local development.
943    #[cfg(feature = "test-utils")]
944    pub fn http_url(&self) -> Option<RelayUrl> {
945        self.http_addr.map(|addr| {
946            url::Url::parse(&format!("http://{addr}"))
947                .expect("valid url")
948                .into()
949        })
950    }
951
952    /// Returns the metrics collected in the relay server.
953    pub fn metrics(&self) -> &RelayMetrics {
954        &self.metrics
955    }
956
957    /// Returns a handle to the embedded [`RelayService`] for runtime control.
958    pub fn relay_service(&self) -> Option<&RelayService> {
959        self.relay_service.as_ref()
960    }
961}
962
963/// Supervisor for the relay server tasks.
964///
965/// As soon as one of the tasks exits, all other tasks are stopped and the server stops.
966/// The supervisor finishes once all tasks are finished.
967#[instrument(skip_all)]
968async fn relay_supervisor(
969    mut tasks: JoinSet<Result<(), SupervisorError>>,
970    mut relay_http_server: Option<http_server::Server>,
971    mut quic_server: Option<QuicServer>,
972) -> Result<(), SupervisorError> {
973    let quic_enabled = quic_server.is_some();
974    let mut quic_fut = match quic_server {
975        Some(ref mut server) => n0_future::Either::Left(server.task_handle()),
976        None => n0_future::Either::Right(n0_future::future::pending()),
977    };
978    let relay_enabled = relay_http_server.is_some();
979    let mut relay_fut = match relay_http_server {
980        Some(ref mut server) => n0_future::Either::Left(server.task_handle()),
981        None => n0_future::Either::Right(n0_future::future::pending()),
982    };
983    let res = tokio::select! {
984        biased;
985        Some(ret) = tasks.join_next() => ret,
986        ret = &mut quic_fut, if quic_enabled => ret.map(Ok),
987        ret = &mut relay_fut, if relay_enabled => ret.map(Ok),
988        else => Ok(Err(e!(SupervisorError::NoRelayServicesEnabled))),
989    };
990    let ret = match res {
991        Ok(Ok(())) => {
992            debug!("Task exited");
993            Ok(())
994        }
995        Ok(Err(err)) => {
996            error!(%err, "Task failed");
997            Err(err)
998        }
999        Err(err) => {
1000            if let Ok(panic) = err.try_into_panic() {
1001                error!("Task panicked");
1002                std::panic::resume_unwind(panic);
1003            }
1004            debug!("Task cancelled");
1005            Err(e!(SupervisorError::TaskCancelled))
1006        }
1007    };
1008
1009    // Ensure the HTTP server terminated, there is no harm in calling this after it is
1010    // already shut down.
1011    if let Some(server) = relay_http_server {
1012        server.shutdown();
1013    }
1014
1015    // Ensure the QUIC server is closed
1016    if let Some(server) = quic_server {
1017        server.shutdown().await;
1018    }
1019
1020    // Stop all remaining tasks
1021    tasks.shutdown().await;
1022
1023    ret
1024}
1025
1026fn root_handler(
1027    _r: Request<Incoming>,
1028    response: ResponseBuilder,
1029) -> HyperResult<Response<BytesBody>> {
1030    let body: BytesBody = Box::new(Full::from(INDEX));
1031    response
1032        .status(StatusCode::OK)
1033        .header("Content-Type", "text/html; charset=utf-8")
1034        .body(body)
1035        .map_err(|err| Box::new(err) as HyperError)
1036}
1037
1038/// HTTP latency queries
1039fn probe_handler(
1040    _r: Request<Incoming>,
1041    response: ResponseBuilder,
1042) -> HyperResult<Response<BytesBody>> {
1043    response
1044        .status(StatusCode::OK)
1045        .header("Access-Control-Allow-Origin", "*")
1046        .body(body_empty())
1047        .map_err(|err| Box::new(err) as HyperError)
1048}
1049
1050fn robots_handler(
1051    _r: Request<Incoming>,
1052    response: ResponseBuilder,
1053) -> HyperResult<Response<BytesBody>> {
1054    let body: BytesBody = Box::new(Full::from(ROBOTS_TXT));
1055    response
1056        .status(StatusCode::OK)
1057        .body(body)
1058        .map_err(|err| Box::new(err) as HyperError)
1059}
1060
1061/// For captive portal detection.
1062fn serve_no_content_handler<B: hyper::body::Body>(
1063    r: Request<B>,
1064    mut response: ResponseBuilder,
1065) -> HyperResult<Response<BytesBody>> {
1066    let check = |c: &HeaderValue| {
1067        !c.is_empty() && c.len() < 64 && c.as_bytes().iter().all(|c| is_challenge_char(*c as char))
1068    };
1069
1070    if let Some(challenge) = r.headers().get(NO_CONTENT_CHALLENGE_HEADER)
1071        && check(challenge)
1072    {
1073        response = response.header(
1074            NO_CONTENT_RESPONSE_HEADER,
1075            format!("response {}", challenge.to_str()?),
1076        );
1077    }
1078
1079    response
1080        .status(StatusCode::NO_CONTENT)
1081        .body(body_empty())
1082        .map_err(|err| Box::new(err) as HyperError)
1083}
1084
1085fn is_challenge_char(c: char) -> bool {
1086    // Semi-randomly chosen as a limited set of valid characters
1087    c.is_ascii_lowercase()
1088        || c.is_ascii_uppercase()
1089        || c.is_ascii_digit()
1090        || c == '.'
1091        || c == '-'
1092        || c == '_'
1093}
1094
1095/// Health check response
1096#[derive(Serialize)]
1097struct Health {
1098    status: &'static str,
1099    version: &'static str,
1100    git_hash: &'static str,
1101}
1102
1103fn healthz_handler(
1104    _r: Request<Incoming>,
1105    response: ResponseBuilder,
1106) -> HyperResult<Response<BytesBody>> {
1107    let health = Health {
1108        status: "ok",
1109        version: env!("CARGO_PKG_VERSION"),
1110        git_hash: "unknown",
1111    };
1112    let body = serde_json::to_string(&health).unwrap_or_else(|_| r#"{"status":"error"}"#.into());
1113    let body: BytesBody = Box::new(Full::from(body));
1114    response
1115        .status(StatusCode::OK)
1116        .header("Content-Type", "application/json")
1117        .body(body)
1118        .map_err(|err| Box::new(err) as HyperError)
1119}
1120
1121/// This is a future that never returns, drop it to cancel/abort.
1122async fn run_captive_portal_service(http_listener: TcpListener) {
1123    info!("serving");
1124
1125    // If this future is cancelled, this is dropped and all tasks are aborted.
1126    let mut tasks = JoinSet::new();
1127
1128    loop {
1129        tokio::select! {
1130            biased;
1131
1132            Some(res) = tasks.join_next() => {
1133                if let Err(err) = res
1134                    && err.is_panic()
1135                {
1136                    panic!("task panicked: {err:#?}");
1137                }
1138            }
1139
1140            res = http_listener.accept() => {
1141                match res {
1142                    Ok((stream, peer_addr)) => {
1143                        debug!(%peer_addr, "Connection opened",);
1144                        let handler = CaptivePortalService;
1145
1146                        let stream = crate::server::streams::MaybeTlsStream::Plain(stream);
1147                        let stream = hyper_util::rt::TokioIo::new(stream);
1148                        let connection = hyper::server::conn::http1::Builder::new()
1149                            .keep_alive(false)
1150                            .serve_connection(stream, handler);
1151                        tasks.spawn(async move {
1152                            match tokio::time::timeout(Duration::from_secs(30), connection).await {
1153                                Ok(Ok(())) => {}
1154                                Ok(Err(err)) => error!("Failed to serve connection: {err:?}"),
1155                                Err(_) => debug!(%peer_addr, "Captive portal connection timed out"),
1156                            }
1157                        });
1158                    }
1159                    Err(err) => {
1160                        error!(
1161                            "[CaptivePortalService] failed to accept connection: {:#?}",
1162                            err
1163                        );
1164                    }
1165                }
1166            }
1167        }
1168    }
1169}
1170
1171#[derive(Clone)]
1172struct CaptivePortalService;
1173
1174impl hyper::service::Service<Request<Incoming>> for CaptivePortalService {
1175    type Response = Response<BytesBody>;
1176    type Error = HyperError;
1177    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1178
1179    fn call(&self, req: Request<Incoming>) -> Self::Future {
1180        match (req.method(), req.uri().path()) {
1181            // Captive Portal checker
1182            (&Method::GET, "/generate_204") => {
1183                Box::pin(async move { serve_no_content_handler(req, Response::builder()) })
1184            }
1185            _ => {
1186                // Return 404 not found response.
1187                let body: BytesBody = Box::new(Full::from(NOTFOUND));
1188                let r = Response::builder()
1189                    .status(StatusCode::NOT_FOUND)
1190                    .body(body)
1191                    .map_err(|err| Box::new(err) as HyperError);
1192                Box::pin(async move { r })
1193            }
1194        }
1195    }
1196}
1197
1198/// The route latency probes are served on: [`RELAY_PROBE_RELATIVE_PATH`] at the root.
1199///
1200/// Built once and kept in a static only because [`Handlers`] keys its routes by
1201/// `&'static str`. Changing [`Handlers`] to take a `String` would remove the need
1202/// for this.
1203fn probe_route() -> &'static str {
1204    static ROUTE: std::sync::LazyLock<String> =
1205        std::sync::LazyLock::new(|| format!("/{RELAY_PROBE_RELATIVE_PATH}"));
1206    ROUTE.as_str()
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211    use std::{net::Ipv4Addr, sync::Arc, time::Duration};
1212
1213    use http::StatusCode;
1214    use iroh_base::{EndpointId, RelayUrl, SecretKey};
1215    use iroh_dns::dns::DnsResolver;
1216    use n0_error::{Result, StackResultExt, StdResultExt};
1217    use n0_future::{SinkExt, StreamExt};
1218    use n0_tracing_test::traced_test;
1219    use rand::{RngExt, SeedableRng};
1220    use tracing::{info, instrument};
1221    use url::Url;
1222
1223    use super::{
1224        Access, AccessControl, ClientRequest, NO_CONTENT_CHALLENGE_HEADER,
1225        NO_CONTENT_RESPONSE_HEADER, RelayConfig, Server, ServerConfig, SpawnError,
1226    };
1227    use crate::{
1228        client::{ClientBuilder, ConnectError},
1229        protos::{
1230            handshake,
1231            relay::{ClientToRelayMsg, Datagrams, MAX_PACKET_SIZE, RelayToClientMsg},
1232        },
1233        test_utils::static_resolver,
1234        tls::{self, CaTlsConfig, default_provider},
1235    };
1236
1237    /// An [`AccessControl`] backed by a closure, for tests.
1238    #[derive(derive_more::Debug)]
1239    struct TestAccess(#[debug("access fn")] Box<dyn Fn(&ClientRequest) -> Access + Send + Sync>);
1240
1241    impl AccessControl for TestAccess {
1242        async fn on_connect(&self, request: &ClientRequest) -> Access {
1243            (self.0)(request)
1244        }
1245    }
1246
1247    async fn spawn_local_relay() -> std::result::Result<Server, SpawnError> {
1248        let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0));
1249        relay.key_cache_capacity = Some(1024);
1250        Server::spawn(ServerConfig {
1251            relay: Some(relay),
1252            quic: None,
1253            metrics_addr: None,
1254        })
1255        .await
1256    }
1257
1258    #[instrument]
1259    async fn try_send_recv(
1260        client_a: &mut crate::client::Client,
1261        client_b: &mut crate::client::Client,
1262        b_key: EndpointId,
1263        msg: Datagrams,
1264    ) -> Result<RelayToClientMsg> {
1265        // try resend 10 times
1266        for _ in 0..10 {
1267            client_a
1268                .send(ClientToRelayMsg::Datagrams {
1269                    dst_endpoint_id: b_key,
1270                    datagrams: msg.clone(),
1271                })
1272                .await?;
1273            let Ok(res) = tokio::time::timeout(Duration::from_millis(500), client_b.next()).await
1274            else {
1275                continue;
1276            };
1277            let res = res.expect("stream finished")?;
1278            return Ok(res);
1279        }
1280        panic!("failed to send and recv message");
1281    }
1282
1283    fn dns_resolver() -> DnsResolver {
1284        DnsResolver::new()
1285    }
1286
1287    fn ring_config() -> rustls::ClientConfig {
1288        rustls::ClientConfig::builder_with_provider(Arc::new(
1289            rustls::crypto::ring::default_provider(),
1290        ))
1291        .with_safe_default_protocol_versions()
1292        .unwrap()
1293        .with_root_certificates(rustls::RootCertStore::empty())
1294        .with_no_client_auth()
1295    }
1296
1297    #[tokio::test]
1298    #[traced_test]
1299    async fn test_no_services() {
1300        let mut server = Server::spawn(ServerConfig::default()).await.unwrap();
1301        let res = tokio::time::timeout(Duration::from_secs(5), server.join())
1302            .await
1303            .expect("timeout, server not finished")
1304            .expect("server task JoinError");
1305        assert!(res.is_err());
1306    }
1307
1308    #[tokio::test]
1309    #[traced_test]
1310    async fn test_conflicting_bind() {
1311        let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 1234));
1312        relay.key_cache_capacity = Some(1024);
1313        let res = Server::spawn(ServerConfig {
1314            relay: Some(relay),
1315            quic: None,
1316            metrics_addr: Some((Ipv4Addr::LOCALHOST, 1234).into()),
1317        })
1318        .await;
1319        assert!(res.is_err()); // AddrInUse
1320    }
1321
1322    #[tokio::test]
1323    #[traced_test]
1324    async fn test_root_handler() {
1325        let server = spawn_local_relay().await.unwrap();
1326        let url = format!("http://{}", server.http_addr().unwrap());
1327
1328        let client = reqwest::Client::builder()
1329            .use_preconfigured_tls(ring_config())
1330            .build()
1331            .unwrap();
1332        let response = client.get(&url).send().await.unwrap();
1333        assert_eq!(response.status(), 200);
1334        let body = response.text().await.unwrap();
1335        assert!(body.contains("iroh.computer"));
1336    }
1337
1338    #[tokio::test]
1339    #[traced_test]
1340    async fn test_captive_portal_service() {
1341        let server = spawn_local_relay().await.unwrap();
1342        let url = format!("http://{}/generate_204", server.http_addr().unwrap());
1343        let challenge = "123az__.";
1344
1345        let client = reqwest::Client::builder()
1346            .use_preconfigured_tls(ring_config())
1347            .build()
1348            .unwrap();
1349        let response = client
1350            .get(&url)
1351            .header(NO_CONTENT_CHALLENGE_HEADER, challenge)
1352            .send()
1353            .await
1354            .unwrap();
1355        assert_eq!(response.status(), StatusCode::NO_CONTENT);
1356        let header = response.headers().get(NO_CONTENT_RESPONSE_HEADER).unwrap();
1357        assert_eq!(header.to_str().unwrap(), format!("response {challenge}"));
1358        let body = response.text().await.unwrap();
1359        assert!(body.is_empty());
1360    }
1361
1362    #[tokio::test]
1363    #[traced_test]
1364    async fn test_relay_clients() -> Result<()> {
1365        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1366        let server = spawn_local_relay().await?;
1367
1368        let relay_url = format!("http://{}", server.http_addr().unwrap());
1369        let relay_url: RelayUrl = relay_url.parse()?;
1370
1371        let client_config = CaTlsConfig::default()
1372            .client_config(default_provider())
1373            .unwrap();
1374
1375        // set up client a
1376        let a_secret_key = SecretKey::from_bytes(&rng.random());
1377        let a_key = a_secret_key.public();
1378        let resolver = dns_resolver();
1379        info!("client a build & connect");
1380        let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver.clone())
1381            .tls_client_config(client_config.clone())
1382            .connect()
1383            .await?;
1384
1385        // set up client b
1386        let b_secret_key = SecretKey::from_bytes(&rng.random());
1387        let b_key = b_secret_key.public();
1388        info!("client b build & connect");
1389        let mut client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver.clone())
1390            .tls_client_config(client_config)
1391            .connect()
1392            .await?;
1393
1394        // Empty datagrams must pass through without disconnecting either client.
1395        // The nonempty exchanges below also verify that both connections remain usable.
1396        let msg = Datagrams {
1397            ecn: None,
1398            segment_size: None,
1399            contents: bytes::Bytes::new(),
1400        };
1401        let res = try_send_recv(&mut client_a, &mut client_b, b_key, msg.clone()).await?;
1402        assert_eq!(
1403            res,
1404            RelayToClientMsg::Datagrams {
1405                remote_endpoint_id: a_key,
1406                datagrams: msg.clone(),
1407            }
1408        );
1409        let res = try_send_recv(&mut client_b, &mut client_a, a_key, msg.clone()).await?;
1410        assert_eq!(
1411            res,
1412            RelayToClientMsg::Datagrams {
1413                remote_endpoint_id: b_key,
1414                datagrams: msg,
1415            }
1416        );
1417
1418        info!("sending a -> b");
1419
1420        // send message from a to b
1421        let msg = Datagrams::from("hello, b");
1422        let res = try_send_recv(&mut client_a, &mut client_b, b_key, msg.clone()).await?;
1423        let RelayToClientMsg::Datagrams {
1424            remote_endpoint_id,
1425            datagrams,
1426        } = res
1427        else {
1428            panic!("client_b received unexpected message {res:?}");
1429        };
1430
1431        assert_eq!(a_key, remote_endpoint_id);
1432        assert_eq!(msg, datagrams);
1433
1434        info!("sending b -> a");
1435        // send message from b to a
1436        let msg = Datagrams::from("howdy, a");
1437        let res = try_send_recv(&mut client_b, &mut client_a, a_key, msg.clone()).await?;
1438
1439        let RelayToClientMsg::Datagrams {
1440            remote_endpoint_id,
1441            datagrams,
1442        } = res
1443        else {
1444            panic!("client_a received unexpected message {res:?}");
1445        };
1446
1447        assert_eq!(b_key, remote_endpoint_id);
1448        assert_eq!(msg, datagrams);
1449
1450        Ok(())
1451    }
1452
1453    /// The largest payload that fits into a frame is still delivered.
1454    #[tokio::test]
1455    #[traced_test]
1456    async fn test_relay_largest_payload() -> Result<()> {
1457        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
1458        let server = spawn_local_relay().await?;
1459
1460        let relay_url = format!("http://{}", server.http_addr().unwrap());
1461        let relay_url: RelayUrl = relay_url.parse()?;
1462
1463        let client_config = CaTlsConfig::default()
1464            .client_config(default_provider())
1465            .unwrap();
1466
1467        let a_secret_key = SecretKey::from_bytes(&rng.random());
1468        let a_key = a_secret_key.public();
1469        let resolver = dns_resolver();
1470        let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver.clone())
1471            .tls_client_config(client_config.clone())
1472            .connect()
1473            .await?;
1474
1475        let b_secret_key = SecretKey::from_bytes(&rng.random());
1476        let b_key = b_secret_key.public();
1477        let mut client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver.clone())
1478            .tls_client_config(client_config)
1479            .connect()
1480            .await?;
1481
1482        // Frame type (1), endpoint id (32) and ECN (1) take up 34 bytes of the frame.
1483        let msg = Datagrams::from(vec![7u8; MAX_PACKET_SIZE - 34]);
1484        let res = try_send_recv(&mut client_a, &mut client_b, b_key, msg.clone()).await?;
1485        assert_eq!(
1486            res,
1487            RelayToClientMsg::Datagrams {
1488                remote_endpoint_id: a_key,
1489                datagrams: msg,
1490            }
1491        );
1492
1493        Ok(())
1494    }
1495
1496    #[tokio::test]
1497    #[traced_test]
1498    async fn test_relay_access_control() -> Result<()> {
1499        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1500        let current_span = tracing::info_span!("this is a test");
1501        let _guard = current_span.enter();
1502
1503        let client_config = CaTlsConfig::default()
1504            .client_config(default_provider())
1505            .unwrap();
1506
1507        let a_secret_key = SecretKey::from_bytes(&rng.random());
1508        let a_key = a_secret_key.public();
1509
1510        let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0));
1511        relay.key_cache_capacity = Some(1024);
1512        relay.access = Arc::new(TestAccess(Box::new(move |request| {
1513            let endpoint_id = request.endpoint_id();
1514            info!("checking {}", endpoint_id);
1515            // reject endpoint a
1516            if endpoint_id == a_key {
1517                Access::Deny { reason: None }
1518            } else {
1519                Access::Allow
1520            }
1521        })));
1522        let server = Server::spawn(ServerConfig {
1523            relay: Some(relay),
1524            quic: None,
1525            metrics_addr: None,
1526        })
1527        .await?;
1528
1529        let relay_url = format!("http://{}", server.http_addr().unwrap());
1530        let relay_url: RelayUrl = relay_url.parse()?;
1531
1532        // set up client a
1533        let resolver = dns_resolver();
1534        let result = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver)
1535            .tls_client_config(client_config.clone())
1536            .connect()
1537            .await;
1538
1539        assert!(
1540            matches!(result, Err(ConnectError::Handshake { source: handshake::Error::ServerDeniedAuth { reason, .. }, .. }) if reason == "not authorized")
1541        );
1542
1543        // test that another client has access
1544
1545        // set up client b
1546        let b_secret_key = SecretKey::from_bytes(&rng.random());
1547        let b_key = b_secret_key.public();
1548
1549        let resolver = dns_resolver();
1550        let mut client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver)
1551            .tls_client_config(client_config.clone())
1552            .connect()
1553            .await?;
1554
1555        // set up client c
1556        let c_secret_key = SecretKey::from_bytes(&rng.random());
1557        let c_key = c_secret_key.public();
1558
1559        let resolver = dns_resolver();
1560        let mut client_c = ClientBuilder::new(relay_url.clone(), c_secret_key, resolver)
1561            .tls_client_config(client_config)
1562            .connect()
1563            .await?;
1564
1565        // send message from b to c
1566        let msg = Datagrams::from("hello, c");
1567        let res = try_send_recv(&mut client_b, &mut client_c, c_key, msg.clone()).await?;
1568
1569        if let RelayToClientMsg::Datagrams {
1570            remote_endpoint_id,
1571            datagrams,
1572        } = res
1573        {
1574            assert_eq!(b_key, remote_endpoint_id);
1575            assert_eq!(msg, datagrams);
1576        } else {
1577            panic!("client_c received unexpected message {res:?}");
1578        }
1579
1580        Ok(())
1581    }
1582
1583    /// Verifies that [`ClientBuilder::auth_token`] forwards a token to the
1584    /// relay so the [`AccessControl::on_connect`] hook can read it via
1585    /// [`ClientRequest::auth_token`].
1586    #[tokio::test]
1587    #[traced_test]
1588    async fn test_relay_client_auth_token_forwarded() -> Result<()> {
1589        const TOKEN: &str = "secret-token";
1590
1591        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1592        let client_config = CaTlsConfig::default()
1593            .client_config(default_provider())
1594            .unwrap();
1595
1596        let mut relay = RelayConfig::new((Ipv4Addr::LOCALHOST, 0));
1597        relay.key_cache_capacity = Some(1024);
1598        relay.access = Arc::new(TestAccess(Box::new(move |request| {
1599            if request.auth_token().as_deref() == Some(TOKEN) {
1600                Access::Allow
1601            } else {
1602                Access::Deny { reason: None }
1603            }
1604        })));
1605        let server = Server::spawn(ServerConfig {
1606            relay: Some(relay),
1607            quic: None,
1608            metrics_addr: None,
1609        })
1610        .await?;
1611
1612        let relay_url = format!("http://{}", server.http_addr().unwrap());
1613        let relay_url: RelayUrl = relay_url.parse()?;
1614
1615        // No query param: denied.
1616        let secret_key = SecretKey::from_bytes(&rng.random());
1617        let result = ClientBuilder::new(relay_url.clone(), secret_key, dns_resolver())
1618            .tls_client_config(client_config.clone())
1619            .connect()
1620            .await;
1621        assert!(matches!(
1622            result,
1623            Err(ConnectError::Handshake { source: handshake::Error::ServerDeniedAuth { reason, .. }, .. })
1624                if reason == "not authorized"
1625        ));
1626
1627        // Wrong token: denied.
1628        let secret_key = SecretKey::from_bytes(&rng.random());
1629        let result = ClientBuilder::new(relay_url.clone(), secret_key, dns_resolver())
1630            .tls_client_config(client_config.clone())
1631            .auth_token("wrong-token")
1632            .connect()
1633            .await;
1634        assert!(matches!(
1635            result,
1636            Err(ConnectError::Handshake { source: handshake::Error::ServerDeniedAuth { reason, .. }, .. })
1637                if reason == "not authorized"
1638        ));
1639
1640        // Correct token: connection succeeds.
1641        let secret_key = SecretKey::from_bytes(&rng.random());
1642        let _client = ClientBuilder::new(relay_url, secret_key, dns_resolver())
1643            .tls_client_config(client_config)
1644            .auth_token(TOKEN)
1645            .connect()
1646            .await?;
1647
1648        Ok(())
1649    }
1650
1651    #[tokio::test]
1652    #[traced_test]
1653    async fn test_relay_clients_full() -> Result<()> {
1654        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1655        let server = spawn_local_relay().await.unwrap();
1656        let relay_url = format!("http://{}", server.http_addr().unwrap());
1657        let relay_url: RelayUrl = relay_url.parse().unwrap();
1658
1659        let client_config = CaTlsConfig::default()
1660            .client_config(default_provider())
1661            .unwrap();
1662
1663        // set up client a
1664        let a_secret_key = SecretKey::from_bytes(&rng.random());
1665        let resolver = dns_resolver();
1666        let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver.clone())
1667            .tls_client_config(client_config.clone())
1668            .connect()
1669            .await?;
1670
1671        // set up client b
1672        let b_secret_key = SecretKey::from_bytes(&rng.random());
1673        let b_key = b_secret_key.public();
1674        let _client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver.clone())
1675            .tls_client_config(client_config)
1676            .connect()
1677            .await?;
1678
1679        // send messages from a to b, without b receiving anything.
1680        // we should still keep succeeding to send, even if the packet won't be forwarded
1681        // by the relay server because the server's send queue for b fills up.
1682        let msg = Datagrams::from("hello, b");
1683        for _i in 0..1000 {
1684            client_a
1685                .send(ClientToRelayMsg::Datagrams {
1686                    dst_endpoint_id: b_key,
1687                    datagrams: msg.clone(),
1688                })
1689                .await?;
1690        }
1691        Ok(())
1692    }
1693
1694    /// Regression test: A relay client that prefers IPv6 falls back to IPv4
1695    /// when the advertised IPv6 address is unreachable.
1696    #[tokio::test]
1697    #[traced_test]
1698    async fn test_relay_client_falls_back_to_ipv4() -> Result {
1699        // A relay reachable only over IPv4.
1700        let config = ServerConfig {
1701            relay: Some(RelayConfig::new((Ipv4Addr::LOCALHOST, 0))),
1702            ..Default::default()
1703        };
1704        let server = Server::spawn(config).await?;
1705        let addr = server.http_addr().expect("http relay address");
1706
1707        // Resolves to both the real IPv4 address and an unreachable IPv6 address.
1708        let resolver = static_resolver(
1709            vec![Ipv4Addr::LOCALHOST],
1710            vec!["2001:db8::dead".parse().expect("valid IPv6")],
1711        );
1712        let url: Url = format!("http://relay.test:{}", addr.port())
1713            .parse()
1714            .expect("valid relay url");
1715
1716        let client = ClientBuilder::new(url, SecretKey::generate(), resolver)
1717            .tls_client_config(tls::make_dangerous_client_config())
1718            // Force IPv6 preference
1719            .address_family_selector(|| true);
1720
1721        tokio::time::timeout(Duration::from_secs(10), client.connect())
1722            .await
1723            .with_std_context(|_| "relay connect timed out")?
1724            .context("relay connect")?;
1725
1726        server.shutdown().await.context("relay server shutdown")?;
1727        Ok(())
1728    }
1729}