iroh_relay/server/
http_server.rs

1//! Low-level HTTP server components for embedding the relay service.
2//!
3//! This module provides [`RelayService`] which can be used to embed relay functionality
4//! into an existing HTTP server. It handles individual connections and provides
5//! the core relay protocol implementation.
6//!
7//! For a complete relay server implementation, see the parent [`server`](super) module.
8
9use std::{collections::HashMap, convert::Infallible, net::SocketAddr, sync::Arc, time::Duration};
10
11use bytes::Bytes;
12use derive_more::Debug;
13use http::{
14    header::{CONNECTION, SEC_WEBSOCKET_KEY, SEC_WEBSOCKET_PROTOCOL, SEC_WEBSOCKET_VERSION},
15    response::Builder as ResponseBuilder,
16};
17use hyper::{
18    HeaderMap, Method, Request, Response, StatusCode,
19    body::Incoming,
20    header::{HeaderValue, SEC_WEBSOCKET_ACCEPT, UPGRADE},
21    service::Service,
22    upgrade::Upgraded,
23};
24use n0_error::{e, ensure, stack_error};
25use n0_future::MaybeFuture;
26use tokio::{
27    net::{TcpListener, TcpSocket, TcpStream},
28    sync::{Notify, watch},
29    time::Instant,
30};
31use tokio_rustls_acme::AcmeAcceptor;
32use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
33use tracing::{Instrument, debug, error, info, info_span, trace, warn};
34
35use super::{
36    AllowAll, ClientRequest, DynAccessControl, SpawnError, clients::Clients,
37    streams::InvalidBucketConfig,
38};
39use crate::{
40    KeyCache,
41    defaults::{
42        DEFAULT_KEY_CACHE_CAPACITY, DEFAULT_LISTEN_BACKLOG, timeouts::SERVER_WRITE_TIMEOUT,
43    },
44    http::{
45        CLIENT_AUTH_HEADER, ProtocolVersion, RELAY_RELATIVE_PATH, SUPPORTED_WEBSOCKET_VERSION,
46        WEBSOCKET_UPGRADE_PROTOCOL,
47    },
48    protos::{handshake, relay::MAX_FRAME_SIZE, streams::WsBytesFramed},
49    server::{
50        ClientRateLimit,
51        client::Config,
52        metrics::Metrics,
53        streams::{MaybeTlsStream, RateLimited, RelayedStream},
54    },
55};
56
57/// Boxed HTTP response body produced by [`RelayServiceWithNotify`].
58pub type BytesBody = Box<
59    dyn 'static + Send + Unpin + hyper::body::Body<Data = hyper::body::Bytes, Error = Infallible>,
60>;
61/// Boxed error type returned from [`RelayServiceWithNotify`]'s [`hyper::service::Service`] impl.
62pub type HyperError = Box<dyn std::error::Error + Send + Sync>;
63/// Result alias for HTTP responses produced by [`RelayServiceWithNotify`].
64pub type HyperResult<T> = std::result::Result<T, HyperError>;
65pub(super) type HyperHandler = Box<
66    dyn Fn(Request<Incoming>, ResponseBuilder) -> HyperResult<Response<BytesBody>>
67        + Send
68        + Sync
69        + 'static,
70>;
71
72/// WebSocket GUID needed for accepting websocket connections, see RFC 6455 (<https://www.rfc-editor.org/rfc/rfc6455>) section 1.3
73const SEC_WEBSOCKET_ACCEPT_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
74
75/// Timeout for a connection to finish the TLS and WebSocket upgrade handshakes.
76///
77/// The connection is aborted if the connection does not complete the TLS handshake
78/// and establishes relay protocol WebSocket stream within this timeout.
79const ESTABLISH_TIMEOUT: Duration = Duration::from_secs(30);
80
81/// Derives the accept key for WebSocket handshake according to RFC 6455.
82/// Takes the client's Sec-WebSocket-Key value and returns the calculated accept key.
83fn derive_accept_key(client_key: &HeaderValue) -> String {
84    use sha1::Digest;
85
86    let mut sha1 = sha1::Sha1::new();
87    sha1.update(client_key.as_bytes());
88    sha1.update(SEC_WEBSOCKET_ACCEPT_GUID);
89    data_encoding::BASE64.encode(&sha1.finalize())
90}
91
92/// Creates a new [`BytesBody`] with given content.
93fn body_full(content: impl Into<hyper::body::Bytes>) -> BytesBody {
94    Box::new(http_body_util::Full::new(content.into()))
95}
96
97#[allow(clippy::result_large_err)]
98fn downcast_upgrade(upgraded: Upgraded) -> Result<(MaybeTlsStream, Bytes), ConnectionHandlerError> {
99    match upgraded.downcast::<hyper_util::rt::TokioIo<MaybeTlsStream>>() {
100        Ok(parts) => Ok((parts.io.into_inner(), parts.read_buf)),
101        Err(_) => Err(e!(ConnectionHandlerError::DowncastUpgrade)),
102    }
103}
104
105/// The Relay HTTP server.
106///
107/// A running HTTP server serving the relay endpoint and optionally a number of additional
108/// HTTP services added with [`ServerBuilder::request_handler`].  If configured using
109/// [`ServerBuilder::tls_config`] the server will handle TLS as well.
110///
111/// Created using [`ServerBuilder::spawn`].
112#[derive(Debug)]
113pub(super) struct Server {
114    addr: SocketAddr,
115    http_server_task: AbortOnDropHandle<()>,
116    cancel_server_loop: CancellationToken,
117    service: RelayService,
118}
119
120impl Server {
121    /// Returns a handle for this server.
122    ///
123    /// The server runs in the background as several async tasks.  This allows controlling
124    /// the server, in particular it allows gracefully shutting down the server.
125    pub(super) fn handle(&self) -> ServerHandle {
126        ServerHandle {
127            cancel_token: self.cancel_server_loop.clone(),
128        }
129    }
130
131    /// Closes the underlying relay server and the HTTP(S) server tasks.
132    pub(super) fn shutdown(&self) {
133        self.cancel_server_loop.cancel();
134    }
135
136    /// Returns the [`AbortOnDropHandle`] for the supervisor task managing the server.
137    ///
138    /// This is the root of all the tasks for the server.  Aborting it will abort all the
139    /// other tasks for the server.  Awaiting it will complete when all the server tasks are
140    /// completed.
141    pub(super) fn task_handle(&mut self) -> &mut AbortOnDropHandle<()> {
142        &mut self.http_server_task
143    }
144
145    /// Returns the local address of this server.
146    pub(super) fn addr(&self) -> SocketAddr {
147        self.addr
148    }
149
150    /// Returns the [`RelayService`] driving this server.
151    pub(super) fn service(&self) -> &RelayService {
152        &self.service
153    }
154}
155
156/// A handle for the [`Server`].
157///
158/// This does not allow access to the task but can communicate with it.
159#[derive(Debug, Clone)]
160pub(super) struct ServerHandle {
161    cancel_token: CancellationToken,
162}
163
164impl ServerHandle {
165    /// Gracefully shut down the server.
166    pub(super) fn shutdown(&self) {
167        self.cancel_token.cancel()
168    }
169}
170
171/// Configuration to use for the TLS connection
172///
173/// This struct wraps a rustls server configuration and TLS acceptor for use with
174/// [`RelayService::handle_connection`].
175///
176/// # Example
177///
178/// ```
179/// use std::sync::Arc;
180///
181/// use iroh_relay::server::http_server::TlsConfig;
182/// use rustls::ServerConfig;
183/// use webpki_types::{CertificateDer, PrivateKeyDer};
184///
185/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
186/// // Set ring as the process-level default crypto provider
187/// rustls::crypto::ring::default_provider()
188///     .install_default()
189///     .ok();
190/// // Generate a self-signed certificate for testing
191/// let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
192/// let cert_der = cert.cert.der().to_vec();
193/// let private_key_der = cert.signing_key.serialize_der();
194///
195/// // Create rustls types
196/// let cert_chain = vec![CertificateDer::from(cert_der)];
197/// let private_key = PrivateKeyDer::try_from(private_key_der)?;
198///
199/// // Create a rustls ServerConfig
200/// let server_config = Arc::new(
201///     ServerConfig::builder()
202///         .with_no_client_auth()
203///         .with_single_cert(cert_chain, private_key)?,
204/// );
205///
206/// // Create TlsConfig for use with RelayService
207/// let tls_config = TlsConfig::new(server_config);
208/// # Ok(())
209/// # }
210/// ```
211#[derive(Debug, Clone)]
212pub struct TlsConfig {
213    /// The server config
214    pub(super) config: Arc<rustls::ServerConfig>,
215    /// The kind
216    pub(super) acceptor: TlsAcceptor,
217}
218
219impl TlsConfig {
220    /// Creates a new `TlsConfig` from a rustls `ServerConfig`.
221    ///
222    /// This creates a manual TLS acceptor using the provided server configuration.
223    /// The acceptor will handle TLS handshakes for incoming connections.
224    ///
225    /// # Example
226    ///
227    /// ```
228    /// use std::sync::Arc;
229    ///
230    /// use iroh_relay::server::http_server::TlsConfig;
231    /// use rustls::ServerConfig;
232    /// use webpki_types::{CertificateDer, PrivateKeyDer};
233    ///
234    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
235    /// // Set ring as the process-level default crypto provider
236    /// rustls::crypto::ring::default_provider()
237    ///     .install_default()
238    ///     .ok();
239    /// // Generate a self-signed certificate for testing
240    /// let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
241    /// let cert_der = cert.cert.der().to_vec();
242    /// let private_key_der = cert.signing_key.serialize_der();
243    ///
244    /// // Create rustls types
245    /// let cert_chain = vec![CertificateDer::from(cert_der)];
246    /// let private_key = PrivateKeyDer::try_from(private_key_der)?;
247    ///
248    /// let server_config = Arc::new(
249    ///     ServerConfig::builder()
250    ///         .with_no_client_auth()
251    ///         .with_single_cert(cert_chain, private_key)?,
252    /// );
253    ///
254    /// let tls_config = TlsConfig::new(server_config);
255    /// # Ok(())
256    /// # }
257    /// ```
258    pub fn new(config: Arc<rustls::ServerConfig>) -> Self {
259        let acceptor = tokio_rustls::TlsAcceptor::from(config.clone());
260        Self {
261            config,
262            acceptor: TlsAcceptor::Manual(acceptor),
263        }
264    }
265}
266
267/// Errors when attempting to upgrade and
268#[allow(missing_docs)]
269#[stack_error(derive, add_meta)]
270#[non_exhaustive]
271pub enum ServeConnectionError {
272    #[error("TLS[acme] handshake")]
273    TlsHandshake {
274        #[error(std_err)]
275        source: std::io::Error,
276    },
277    #[error("TLS[acme] serve connection")]
278    ServeConnection {
279        #[error(std_err)]
280        source: hyper::Error,
281    },
282    #[error("TLS[manual] accept")]
283    ManualAccept {
284        #[error(std_err)]
285        source: std::io::Error,
286    },
287    #[error("TLS[acme] accept")]
288    LetsEncryptAccept {
289        #[error(std_err)]
290        source: std::io::Error,
291    },
292    #[error("HTTPS connection")]
293    Https {
294        #[error(std_err)]
295        source: hyper::Error,
296    },
297    #[error("HTTP connection")]
298    Http {
299        #[error(std_err)]
300        source: hyper::Error,
301    },
302    #[error("Connection did not reach established state within timeout")]
303    EstablishTimeout,
304}
305
306/// Server accept errors.
307#[allow(missing_docs)]
308#[stack_error(derive, add_meta, from_sources)]
309#[non_exhaustive]
310pub enum AcceptError {
311    #[error(transparent)]
312    Handshake { source: handshake::Error },
313    #[error("rate limiting misconfigured")]
314    RateLimitingMisconfigured { source: InvalidBucketConfig },
315}
316
317/// Server connection errors, includes errors that can happen on `accept`.
318#[allow(missing_docs)]
319#[stack_error(derive, add_meta, from_sources)]
320#[non_exhaustive]
321pub enum ConnectionHandlerError {
322    #[error(transparent)]
323    Accept { source: AcceptError },
324    #[error("Could not downcast the upgraded connection to MaybeTlsStream")]
325    DowncastUpgrade {},
326    #[error("Cannot deal with buffered data yet: {buf:?}")]
327    BufferNotEmpty { buf: Bytes },
328}
329
330/// Builder for the Relay HTTP Server.
331///
332/// Defaults to handling relay requests on the "/relay" (and "/derp" for backwards compatibility) endpoint.
333/// Other HTTP endpoints can be added using [`ServerBuilder::request_handler`].
334#[derive(derive_more::Debug)]
335pub(super) struct ServerBuilder {
336    /// The ip + port combination for this server.
337    addr: SocketAddr,
338    /// Optional tls configuration/TlsAcceptor combination.
339    ///
340    /// When `None`, the server will serve HTTP, otherwise it will serve HTTPS.
341    tls_config: Option<TlsConfig>,
342    /// A map of request handlers to routes.
343    ///
344    /// Used when certain routes in your server should be made available at the same port as
345    /// the relay server, and so must be handled along side requests to the relay endpoint.
346    handlers: Handlers,
347    /// Headers to use for HTTP responses.
348    headers: HeaderMap,
349    /// Rate-limiting configuration for an individual client connection.
350    ///
351    /// Rate-limiting is enforced on received traffic from individual clients.  This
352    /// configuration applies to a single client connection.
353    client_rx_ratelimit: Option<ClientRateLimit>,
354    /// The capacity of the key cache.
355    key_cache_capacity: usize,
356    /// Listen queue length.
357    listen_backlog: u32,
358    /// Access control for endpoints.
359    access: Arc<dyn DynAccessControl>,
360    metrics: Option<Arc<Metrics>>,
361    establish_timeout: Duration,
362}
363
364/// Bind a TCP listener on `addr` with a listen queue of `backlog`.
365fn bind_listener(addr: SocketAddr, backlog: u32) -> std::io::Result<TcpListener> {
366    let socket = match addr {
367        SocketAddr::V4(_) => TcpSocket::new_v4()?,
368        SocketAddr::V6(_) => TcpSocket::new_v6()?,
369    };
370    #[cfg(not(windows))]
371    socket.set_reuseaddr(true)?;
372    socket.bind(addr)?;
373    socket.listen(backlog)
374}
375
376impl ServerBuilder {
377    /// Creates a new [ServerBuilder].
378    pub(super) fn new(addr: SocketAddr) -> Self {
379        Self {
380            addr,
381            tls_config: None,
382            handlers: Default::default(),
383            headers: HeaderMap::new(),
384            client_rx_ratelimit: None,
385            key_cache_capacity: DEFAULT_KEY_CACHE_CAPACITY,
386            listen_backlog: DEFAULT_LISTEN_BACKLOG,
387            access: Arc::new(AllowAll),
388            metrics: None,
389            establish_timeout: ESTABLISH_TIMEOUT,
390        }
391    }
392
393    /// Sets the metrics collector.
394    pub(super) fn metrics(mut self, metrics: Arc<Metrics>) -> Self {
395        self.metrics = Some(metrics);
396        self
397    }
398
399    /// Set the access control.
400    pub(super) fn access(mut self, access: Arc<dyn DynAccessControl>) -> Self {
401        self.access = access;
402        self
403    }
404
405    /// Serves all requests content using TLS.
406    pub(super) fn tls_config(mut self, config: Option<TlsConfig>) -> Self {
407        self.tls_config = config;
408        self
409    }
410
411    /// Sets the timeout after which connections are aborted if they don't become fully established.
412    ///
413    /// The timeout is started immediately after a TCP connection comes in, and cleared once
414    /// the connection has finished the TLS handshake and fully processed the WebSocket request
415    /// to initiate the relay protocol. If the timeout expires before being cleared, the
416    /// connection is aborted.
417    ///
418    /// Defaults to 30s.
419    #[cfg(test)]
420    pub(super) fn establish_timeout(mut self, timeout: Duration) -> Self {
421        self.establish_timeout = timeout;
422        self
423    }
424
425    /// Sets the per-client rate-limit configuration for incoming data.
426    ///
427    /// On each client connection the incoming data is rate-limited.  By default
428    /// no rate limit is enforced.
429    pub(super) fn client_rx_ratelimit(mut self, config: ClientRateLimit) -> Self {
430        self.client_rx_ratelimit = Some(config);
431        self
432    }
433
434    /// Adds a custom handler for a specific Method & URI.
435    pub(super) fn request_handler(
436        mut self,
437        method: Method,
438        uri_path: &'static str,
439        handler: HyperHandler,
440    ) -> Self {
441        self.handlers.insert((method, uri_path), handler);
442        self
443    }
444
445    /// Adds HTTP headers to responses.
446    pub(super) fn headers(mut self, headers: HeaderMap) -> Self {
447        for (k, v) in headers.iter() {
448            self.headers.insert(k.clone(), v.clone());
449        }
450        self
451    }
452
453    /// Set the capacity of the cache for public keys.
454    pub(super) fn key_cache_capacity(mut self, capacity: usize) -> Self {
455        self.key_cache_capacity = capacity;
456        self
457    }
458
459    /// Set the listen queue length.
460    pub(super) fn listen_backlog(mut self, backlog: u32) -> Self {
461        self.listen_backlog = backlog;
462        self
463    }
464
465    /// Builds and spawns an HTTP(S) Relay Server.
466    pub(super) fn spawn(self) -> Result<Server, SpawnError> {
467        let cancel_token = CancellationToken::new();
468
469        let service = RelayService::new(
470            self.handlers,
471            self.headers,
472            self.client_rx_ratelimit,
473            KeyCache::new(self.key_cache_capacity),
474            self.access,
475            self.metrics.unwrap_or_default(),
476        );
477
478        let addr = self.addr;
479        let tls_config = self.tls_config;
480
481        // Bind a TCP listener on `addr` and handles content using HTTPS.
482
483        let listener = bind_listener(addr, self.listen_backlog)
484            .map_err(|err| e!(super::SpawnError::BindTcpListener { addr }, err))?;
485
486        let addr = listener
487            .local_addr()
488            .map_err(|err| e!(super::SpawnError::NoLocalAddr, err))?;
489        let http_str = tls_config.as_ref().map_or("HTTP/WS", |_| "HTTPS/WSS");
490        info!("[{http_str}] relay: serving on {addr}");
491
492        let cancel = cancel_token.clone();
493        let loop_service = service.clone();
494        let task = tokio::task::spawn(
495            async move {
496                let service = loop_service;
497                // create a join set to track all our connection tasks
498                let mut set = tokio::task::JoinSet::new();
499                loop {
500                    tokio::select! {
501                        biased;
502                        _ = cancel.cancelled() => {
503                            break;
504                        }
505                        Some(res) = set.join_next() => {
506                            if let Err(err) = res
507                                && err.is_panic()
508                            {
509                                panic!("task panicked: {err:#?}");
510                            }
511                        }
512                        res = listener.accept() => match res {
513                            Ok((stream, peer_addr)) => {
514                                debug!("connection opened from {peer_addr}");
515                                let tls_config = tls_config.clone();
516                                let service = service.clone();
517                                // spawn a task to handle the connection
518                                set.spawn(async move {
519                                    service
520                                        .handle_connection(stream, tls_config, self.establish_timeout)
521                                        .await
522                                }.instrument(info_span!("conn", peer = %peer_addr)));
523                            }
524                            Err(err) => {
525                                error!("failed to accept connection: {err}");
526                            }
527                        }
528                    }
529                }
530                service.shutdown().await;
531                set.shutdown().await;
532                debug!("server has been shutdown.");
533            }
534            .instrument(info_span!("relay-http-serve")),
535        );
536
537        Ok(Server {
538            addr,
539            http_server_task: AbortOnDropHandle::new(task),
540            cancel_server_loop: cancel_token,
541            service,
542        })
543    }
544}
545
546/// The hyper Service that serves the actual relay endpoints.
547///
548/// This service can be used standalone or embedded into an existing HTTP server.
549#[derive(Clone, Debug)]
550pub struct RelayService(Arc<Inner>);
551
552#[derive(Debug)]
553struct Inner {
554    handlers: Handlers,
555    headers: HeaderMap,
556    clients: Clients,
557    write_timeout: Duration,
558    rate_limit: watch::Sender<Option<ClientRateLimit>>,
559    key_cache: KeyCache,
560    access: Arc<dyn DynAccessControl>,
561    metrics: Arc<Metrics>,
562}
563
564#[stack_error(derive, add_meta)]
565enum RelayUpgradeReqError {
566    #[error("missing header: {header}")]
567    MissingHeader { header: http::HeaderName },
568    #[error("invalid header value for {header}: {details}")]
569    InvalidHeader {
570        header: http::HeaderName,
571        details: String,
572    },
573    #[error(
574        "invalid header value for {SEC_WEBSOCKET_VERSION}: unsupported websocket version, only supporting {SUPPORTED_WEBSOCKET_VERSION}"
575    )]
576    UnsupportedWebsocketVersion,
577    #[error(
578        "invalid header value for {SEC_WEBSOCKET_PROTOCOL}: unsupported relay version: we support {we_support} but you only provide {you_support}"
579    )]
580    UnsupportedRelayVersion {
581        we_support: String,
582        you_support: String,
583    },
584}
585
586impl RelayServiceWithNotify {
587    fn build_response(&self) -> http::response::Builder {
588        let mut res = Response::builder();
589        for (key, value) in self.service.0.headers.iter() {
590            res = res.header(key, value);
591        }
592        res
593    }
594
595    /// Upgrades the HTTP connection to the relay protocol, runs relay client.
596    fn handle_relay_ws_upgrade(
597        &self,
598        mut req: Request<Incoming>,
599    ) -> Result<Response<BytesBody>, RelayUpgradeReqError> {
600        fn expect_header(
601            req: &Request<Incoming>,
602            header: http::HeaderName,
603        ) -> Result<&HeaderValue, RelayUpgradeReqError> {
604            req.headers()
605                .get(&header)
606                .ok_or_else(|| e!(RelayUpgradeReqError::MissingHeader { header }))
607        }
608
609        let upgrade_header = expect_header(&req, UPGRADE)?;
610        ensure!(
611            upgrade_header == HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL),
612            RelayUpgradeReqError::InvalidHeader {
613                header: UPGRADE,
614                details: format!("value must be {WEBSOCKET_UPGRADE_PROTOCOL}")
615            }
616        );
617
618        let key = expect_header(&req, SEC_WEBSOCKET_KEY)?.clone();
619        let version = expect_header(&req, SEC_WEBSOCKET_VERSION)?.clone();
620
621        ensure!(
622            version.as_bytes() == SUPPORTED_WEBSOCKET_VERSION.as_bytes(),
623            RelayUpgradeReqError::UnsupportedWebsocketVersion
624        );
625
626        let subprotocols = expect_header(&req, SEC_WEBSOCKET_PROTOCOL)?
627            .to_str()
628            .ok()
629            .ok_or_else(|| {
630                e!(RelayUpgradeReqError::InvalidHeader {
631                    header: SEC_WEBSOCKET_PROTOCOL,
632                    details: "header value is not ascii".to_string()
633                })
634            })?;
635        let protocol_version = subprotocols
636            .split(",")
637            .map(|s| s.trim())
638            .filter_map(ProtocolVersion::match_from_str)
639            .max()
640            .ok_or_else(|| {
641                e!(RelayUpgradeReqError::UnsupportedRelayVersion {
642                    we_support: ProtocolVersion::all_joined(),
643                    you_support: subprotocols.to_string()
644                })
645            })?;
646
647        // Setup a future that will eventually receive the upgraded
648        // connection and talk a new protocol, and spawn the future
649        // into the runtime.
650        //
651        // Note: This can't possibly be fulfilled until the 101 response
652        // is returned below, so it's better to spawn this future instead
653        // waiting for it to complete to then return a response.
654        tokio::task::spawn({
655            let this = self.clone();
656            let deadline = Instant::now() + this.establish_timeout;
657            let establish = async move {
658                match hyper::upgrade::on(&mut req).await {
659                    Ok(upgraded) => {
660                        let (parts, _) = req.into_parts();
661                        if let Err(err) = this
662                            .service
663                            .0
664                            .relay_connection_handler(upgraded, parts, protocol_version)
665                            .await
666                        {
667                            warn!("error accepting upgraded connection: {err:#}",);
668                        } else {
669                            // We have passed the connection to the relay protocol handler,
670                            // thus we trigger the on_establish notification so that timeouts
671                            // on the upper layer will be cleared.
672                            this.on_establish.notify_waiters();
673                            debug!("upgraded connection completed");
674                        };
675                    }
676                    Err(err) => warn!("upgrade error: {err:#}"),
677                }
678            };
679            async move {
680                // After the WebSocket upgrade, the HTTP timeout no longer covers this socket.
681                // Give the client a deadline to finish authentication and the access check.
682                if tokio::time::timeout_at(deadline, establish).await.is_err() {
683                    debug!("relay connection establishment timed out");
684                }
685            }
686            .instrument(info_span!("handler"))
687        });
688
689        // Now return a 101 Response saying we agree to the upgrade to the
690        // websocket upgrade protocol
691        Ok(self
692            .build_response()
693            .status(StatusCode::SWITCHING_PROTOCOLS)
694            .header(
695                UPGRADE,
696                HeaderValue::from_static(WEBSOCKET_UPGRADE_PROTOCOL),
697            )
698            .header(SEC_WEBSOCKET_ACCEPT, derive_accept_key(&key))
699            .header(SEC_WEBSOCKET_PROTOCOL, protocol_version.to_header_value())
700            .header(CONNECTION, "upgrade")
701            .body(body_full("switching to websocket protocol"))
702            .expect("valid body"))
703    }
704}
705
706/// Combines [`RelayService`] with a notification token.
707///
708/// This struct implements [`Service`]. Note that the service has to be called with hyper's `io`
709/// argument set to [`MaybeTlsStream`] wrapped by [`hyper_util::rt::TokioIo`], otherwise handling
710/// WebSocket requests at `/relay` will fail at runtime with [`ConnectionHandlerError::DowncastUpgrade`].
711///
712/// The notification token is triggered once the relay connection is fully established. It can be used
713/// to cancel a timeout aborting the TCP connection if no upgrade request is received in some time.
714///
715/// ## Example
716///
717/// ```no_run
718/// # use std::{sync::Arc, time::Duration};
719/// # use http::HeaderMap;
720/// # use hyper::server::conn::http1;
721/// # use hyper_util::rt::TokioIo;
722/// # use tokio::{net::TcpListener, sync::Notify};
723/// # use iroh_relay::{
724/// #     KeyCache,
725/// #     server::{
726/// #         AllowAll, Metrics,
727/// #         http_server::{Handlers, RelayService, RelayServiceWithNotify},
728/// #         streams::MaybeTlsStream
729/// #     },
730/// # };
731/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
732/// let service = RelayService::new(
733///     Handlers::default(),
734///     HeaderMap::new(),
735///     None,
736///     KeyCache::new(1024),
737///     Arc::new(AllowAll),
738///     Arc::new(Metrics::default()),
739/// );
740/// let service = RelayServiceWithNotify::with_timeout(
741///     service,
742///     Arc::new(Notify::new()),
743///     Duration::from_secs(30),
744/// );
745///
746/// let listener = TcpListener::bind("127.0.0.1:0").await?;
747/// let (stream, _peer) = listener.accept().await?;
748/// // Wrap the TCP stream in `MaybeTlsStream`, otherwise the relay WebSocket handler will error at runtime
749/// // for all WebSocket requests to `/relay`.
750/// let stream = MaybeTlsStream::Plain(stream);
751/// http1::Builder::new()
752///     .serve_connection(TokioIo::new(stream), service)
753///     .with_upgrades()
754///     .await?;
755/// # Ok(())
756/// # }
757/// ```
758#[derive(Debug, Clone)]
759pub struct RelayServiceWithNotify {
760    service: RelayService,
761    on_establish: Arc<Notify>,
762    establish_timeout: Duration,
763}
764
765impl RelayServiceWithNotify {
766    /// Creates a new service wrapper for a connection.
767    ///
768    /// The `on_establish` notification is triggered once the connection is passed to the
769    /// relay protocol, i.e. after a WebSocket request on /relay is received and established.
770    /// Upgraded connections must finish authentication and authorization within 30 seconds
771    /// of receiving the upgrade request.
772    pub fn new(service: RelayService, on_establish: Arc<Notify>) -> Self {
773        Self::with_timeout(service, on_establish, ESTABLISH_TIMEOUT)
774    }
775
776    /// Creates a service wrapper with a relay establishment timeout.
777    ///
778    /// Each upgrade request starts a new timeout covering the WebSocket upgrade, authentication,
779    /// and authorization. The `on_establish` notification is triggered once the connection is
780    /// passed to the relay protocol. Established connections are not subject to this timeout.
781    ///
782    /// The caller must separately bound TLS handshakes and HTTP requests before an upgrade request
783    /// reaches this service.
784    pub fn with_timeout(
785        service: RelayService,
786        on_establish: Arc<Notify>,
787        timeout: Duration,
788    ) -> Self {
789        Self {
790            service,
791            on_establish,
792            establish_timeout: timeout,
793        }
794    }
795}
796
797impl Service<Request<Incoming>> for RelayServiceWithNotify {
798    type Response = Response<BytesBody>;
799    type Error = HyperError;
800    type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
801
802    fn call(&self, req: Request<Incoming>) -> Self::Future {
803        // Create a client if the request hits the relay endpoint.
804        if req.method() == hyper::Method::GET
805            && req.uri().path().strip_prefix('/') == Some(RELAY_RELATIVE_PATH)
806        {
807            let response = match self.handle_relay_ws_upgrade(req) {
808                Ok(response) => Ok(response),
809                // It's convention to send back the version(s) we *do* support
810                Err(e @ RelayUpgradeReqError::UnsupportedWebsocketVersion { .. }) => self
811                    .build_response()
812                    .status(StatusCode::BAD_REQUEST)
813                    .header(SEC_WEBSOCKET_VERSION, SUPPORTED_WEBSOCKET_VERSION)
814                    .body(body_full(e.to_string())),
815                Err(e) => self
816                    .build_response()
817                    .status(StatusCode::BAD_REQUEST)
818                    .body(body_full(e.to_string())),
819            }
820            .map_err(Into::into);
821            return std::future::ready(response);
822        }
823        // Otherwise handle the relay connection as normal.
824
825        // Check all other possible endpoints.
826        let uri = req.uri().clone();
827        if let Some(handler) = self
828            .service
829            .0
830            .handlers
831            .get(&(req.method().clone(), uri.path()))
832        {
833            let response = handler(req, self.service.0.default_response());
834            return std::future::ready(response);
835        }
836
837        // Otherwise return 404
838        let response = self
839            .service
840            .0
841            .not_found_fn(req, self.service.0.default_response());
842        std::future::ready(response)
843    }
844}
845
846impl Inner {
847    fn default_response(&self) -> ResponseBuilder {
848        let mut response = Response::builder();
849        for (key, value) in self.headers.iter() {
850            response = response.header(key.clone(), value.clone());
851        }
852        response
853    }
854
855    fn not_found_fn(
856        &self,
857        _req: Request<Incoming>,
858        mut res: ResponseBuilder,
859    ) -> HyperResult<Response<BytesBody>> {
860        for (k, v) in self.headers.iter() {
861            res = res.header(k.clone(), v.clone());
862        }
863        let body = body_full("Not Found");
864        let r = res.status(StatusCode::NOT_FOUND).body(body)?;
865        HyperResult::Ok(r)
866    }
867
868    /// The server HTTP handler to do HTTP upgrades.
869    ///
870    /// This handler runs while doing the connection upgrade handshake.  Once the connection
871    /// is upgraded it sends the stream to the relay server which takes it over.  After
872    /// having sent off the connection this handler returns.
873    async fn relay_connection_handler(
874        &self,
875        upgraded: Upgraded,
876        request_parts: http::request::Parts,
877        protocol_version: ProtocolVersion,
878    ) -> Result<(), ConnectionHandlerError> {
879        debug!("relay_connection upgraded");
880        let (io, read_buf) = downcast_upgrade(upgraded)?;
881        if !read_buf.is_empty() {
882            return Err(e!(ConnectionHandlerError::BufferNotEmpty { buf: read_buf }));
883        }
884
885        self.accept(io, request_parts, protocol_version).await?;
886        Ok(())
887    }
888
889    /// Adds a new connection to the server and serves it.
890    ///
891    /// Will error if it takes too long (10 sec) to write or read to the connection, if there is
892    /// some read or write error to the connection,  if the server is meant to verify clients,
893    /// and is unable to verify this one, or if there is some issue communicating with the server.
894    ///
895    /// The provided [`AsyncRead`] and [`AsyncWrite`] must be already connected to the connection.
896    ///
897    /// [`AsyncRead`]: tokio::io::AsyncRead
898    /// [`AsyncWrite`]: tokio::io::AsyncWrite
899    async fn accept(
900        &self,
901        io: MaybeTlsStream,
902        request_parts: http::request::Parts,
903        protocol_version: ProtocolVersion,
904    ) -> Result<(), AcceptError> {
905        trace!("accept: start");
906
907        // Set the socket to NO_DELAY.
908        io.disable_nagle();
909
910        let io = RateLimited::from_watcher(io, self.rate_limit.subscribe(), self.metrics.clone())
911            .map_err(|err| e!(AcceptError::RateLimitingMisconfigured, err))?;
912        let limited_watcher = io.limited_watcher();
913
914        // Create a server builder with default config
915        let websocket = tokio_websockets::ServerBuilder::new()
916            .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)))
917            // Serve will create a WebSocketStream on an already upgraded connection
918            .serve(io);
919
920        let mut io = WsBytesFramed::new(websocket);
921
922        let client_auth_header = request_parts.headers.get(CLIENT_AUTH_HEADER).cloned();
923        let authentication = handshake::serverside(&mut io, client_auth_header).await?;
924
925        trace!(?authentication.mechanism, "accept: verified authentication");
926
927        let request =
928            ClientRequest::new(authentication.client_key, protocol_version, request_parts);
929
930        // Authorize the request against the configured `AccessControl`.
931        let guard = authentication
932            .authorize_with(&request, &self.access, &mut io)
933            .await?;
934
935        trace!("accept: verified authorization");
936
937        let io = RelayedStream {
938            inner: io,
939            key_cache: self.key_cache.clone(),
940        };
941
942        trace!("accept: build client conn");
943        let mut client_conn_builder = Config::new(guard, io, protocol_version);
944        client_conn_builder.write_timeout = self.write_timeout;
945        client_conn_builder.rate_limited = Some(limited_watcher);
946        trace!(endpoint_id = %request.endpoint_id().fmt_short(), "create client");
947
948        // build and register client, starting up read & write loops for the client
949        // connection
950        self.clients
951            .register(client_conn_builder, self.metrics.clone());
952        Ok(())
953    }
954}
955
956/// TLS Certificate Authority acceptor.
957#[derive(Clone, derive_more::Debug)]
958pub(super) enum TlsAcceptor {
959    /// Uses Let's Encrypt as the Certificate Authority. This is used in production.
960    LetsEncrypt(#[debug("tokio_rustls_acme::AcmeAcceptor")] AcmeAcceptor),
961    /// Manually added tls acceptor. Generally used for tests or for when we've passed in
962    /// a certificate via a file.
963    Manual(#[debug("tokio_rustls::TlsAcceptor")] tokio_rustls::TlsAcceptor),
964}
965
966impl RelayService {
967    /// Creates a new RelayService.
968    ///
969    /// This allows embedding the relay service into an existing HTTP server.
970    pub fn new(
971        handlers: Handlers,
972        headers: HeaderMap,
973        rate_limit: Option<ClientRateLimit>,
974        key_cache: KeyCache,
975        access: Arc<dyn DynAccessControl>,
976        metrics: Arc<Metrics>,
977    ) -> Self {
978        Self(Arc::new(Inner {
979            handlers,
980            headers,
981            clients: Clients::default(),
982            write_timeout: SERVER_WRITE_TIMEOUT,
983            rate_limit: watch::Sender::new(rate_limit),
984            key_cache,
985            access,
986            metrics,
987        }))
988    }
989
990    /// Updates the per-client receive rate limit.
991    ///
992    /// The new rate limit will be applied to all current and future client connections.
993    /// Passing `None` will remove rate limiting from all connections.
994    pub fn set_client_rate_limit(&self, rate_limit: Option<ClientRateLimit>) {
995        self.0.rate_limit.send_replace(rate_limit);
996    }
997
998    /// Shuts down the relay service, disconnecting all clients.
999    pub async fn shutdown(&self) {
1000        self.0.clients.shutdown().await;
1001    }
1002
1003    /// Returns a reference to the registry of currently connected clients.
1004    ///
1005    /// The returned [`Clients`] handle can be used at runtime to disconnect a
1006    /// connected endpoint via [`Clients::disconnect`].
1007    pub fn clients(&self) -> &Clients {
1008        &self.0.clients
1009    }
1010
1011    /// Handle the incoming connection.
1012    ///
1013    /// If a `tls_config` is given, will serve the connection using HTTPS, otherwise HTTP.
1014    ///
1015    /// TLS and HTTP establishment are bounded by `establish_timeout`. An upgrade request starts
1016    /// a separate timeout of the same duration for the WebSocket upgrade, authentication, and
1017    /// authorization. The connection is aborted if either timeout expires.
1018    ///
1019    /// # Example
1020    ///
1021    /// ```no_run
1022    /// # use std::{sync::Arc, time::Duration};
1023    /// # use tokio::net::TcpStream;
1024    /// # use http::HeaderMap;
1025    /// # use iroh_relay::server::http_server::{Handlers, RelayService, TlsConfig};
1026    /// # use iroh_relay::{KeyCache, server::{AllowAll, Metrics}};
1027    /// # use webpki_types::{CertificateDer, PrivateKeyDer};
1028    /// # async fn example(stream: TcpStream) -> Result<(), Box<dyn std::error::Error>> {
1029    /// // Create a relay service
1030    /// let handlers = Handlers::default();
1031    /// let headers = HeaderMap::new();
1032    /// let key_cache = KeyCache::new(1024);
1033    /// let metrics = Arc::new(Metrics::default());
1034    /// let relay_service = RelayService::new(
1035    ///     handlers,
1036    ///     headers,
1037    ///     None, // No rate limiting
1038    ///     key_cache,
1039    ///     Arc::new(AllowAll),
1040    ///     metrics,
1041    /// );
1042    ///
1043    /// // Generate a self-signed certificate for HTTPS
1044    /// let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
1045    /// let cert_der = cert.cert.der().to_vec();
1046    /// let private_key_der = cert.signing_key.serialize_der();
1047    /// let cert_chain = vec![CertificateDer::from(cert_der)];
1048    /// let private_key = PrivateKeyDer::try_from(private_key_der)?;
1049    ///
1050    /// // Serve with HTTPS
1051    /// let server_config = Arc::new(
1052    ///     rustls::ServerConfig::builder()
1053    ///         .with_no_client_auth()
1054    ///         .with_single_cert(cert_chain, private_key)?,
1055    /// );
1056    /// let tls_config = TlsConfig::new(server_config);
1057    /// relay_service
1058    ///     .clone()
1059    ///     .handle_connection(stream, Some(tls_config), Duration::from_secs(30))
1060    ///     .await;
1061    ///
1062    /// // Or serve with plain HTTP
1063    /// # let stream = TcpStream::connect("127.0.0.1:0").await?;
1064    /// relay_service
1065    ///     .handle_connection(stream, None, Duration::from_secs(30))
1066    ///     .await;
1067    /// # Ok(())
1068    /// # }
1069    /// ```
1070    pub async fn handle_connection(
1071        self,
1072        stream: TcpStream,
1073        tls_config: Option<TlsConfig>,
1074        establish_timeout: Duration,
1075    ) {
1076        let metrics = self.0.metrics.clone();
1077        metrics.http_connections.inc();
1078        // We create a notification token to be triggered once the connection is fully established
1079        // and passed to the relay server.
1080        let on_establish = Arc::new(Notify::new());
1081        let service =
1082            RelayServiceWithNotify::with_timeout(self, on_establish.clone(), establish_timeout);
1083
1084        // This is the main connection future, driving the connection to completion.
1085        let serve_fut = async move {
1086            match tls_config {
1087                Some(tls_config) => {
1088                    debug!("HTTPS: serve connection");
1089                    service.tls_serve_connection(stream, tls_config).await
1090                }
1091                None => {
1092                    debug!("HTTP: serve connection");
1093                    let stream = MaybeTlsStream::Plain(stream);
1094                    service.serve_connection(stream).await
1095                }
1096            }
1097        };
1098
1099        // Bound TLS and HTTP establishment. Hyper completes this future when it hands off an
1100        // upgraded socket; the upgrade task separately bounds authentication and authorization.
1101        let res = clearable_timeout(establish_timeout, on_establish, serve_fut)
1102            .await
1103            .map_err(|_elapsed| e!(ServeConnectionError::EstablishTimeout))
1104            .flatten();
1105
1106        metrics.http_connections_closed.inc();
1107
1108        if let Err(error) = res {
1109            match error {
1110                ServeConnectionError::ManualAccept { source, .. }
1111                | ServeConnectionError::LetsEncryptAccept { source, .. }
1112                    if source.kind() == std::io::ErrorKind::UnexpectedEof =>
1113                {
1114                    debug!(reason=?source, "peer disconnected");
1115                }
1116                // From hyper: <https://github.com/hyperium/hyper/commit/271bba16672ff54a44e043c5cc1ae6b9345bb172>
1117                // `hyper::Error::IncompleteMessage` is hyper's equivalent of UnexpectedEof
1118                ServeConnectionError::Https { source, .. }
1119                | ServeConnectionError::Http { source, .. }
1120                    if source.is_incomplete_message() =>
1121                {
1122                    debug!(reason=?source, "peer disconnected");
1123                }
1124                _ => {
1125                    metrics.http_connections_errored.inc();
1126                    error!(?error, "failed to handle connection");
1127                }
1128            }
1129        }
1130    }
1131}
1132
1133impl RelayServiceWithNotify {
1134    /// Serves a TLS connection.
1135    async fn tls_serve_connection(
1136        self,
1137        stream: TcpStream,
1138        tls_config: TlsConfig,
1139    ) -> Result<(), ServeConnectionError> {
1140        let TlsConfig { acceptor, config } = tls_config;
1141        let stream = match acceptor {
1142            TlsAcceptor::LetsEncrypt(a) => {
1143                match a
1144                    .accept(stream)
1145                    .await
1146                    .map_err(|err| e!(ServeConnectionError::LetsEncryptAccept, err))?
1147                {
1148                    None => {
1149                        info!("TLS[acme]: received TLS-ALPN-01 validation request");
1150                        return Ok(());
1151                    }
1152                    Some(start_handshake) => {
1153                        debug!("TLS[acme]: start handshake");
1154                        let tls_stream = start_handshake
1155                            .into_stream(config)
1156                            .await
1157                            .map_err(|err| e!(ServeConnectionError::TlsHandshake, err))?;
1158                        MaybeTlsStream::Tls(tls_stream)
1159                    }
1160                }
1161            }
1162            TlsAcceptor::Manual(a) => {
1163                debug!("TLS[manual]: accept");
1164                let tls_stream = a
1165                    .accept(stream)
1166                    .await
1167                    .map_err(|err| e!(ServeConnectionError::ManualAccept, err))?;
1168                MaybeTlsStream::Tls(tls_stream)
1169            }
1170        };
1171        self.serve_connection(stream).await
1172    }
1173
1174    /// Wrapper for the actual http connection (with upgrades)
1175    async fn serve_connection(self, io: MaybeTlsStream) -> Result<(), ServeConnectionError> {
1176        hyper::server::conn::http1::Builder::new()
1177            .serve_connection(hyper_util::rt::TokioIo::new(io), self)
1178            .with_upgrades()
1179            .await
1180            .map_err(|err| e!(ServeConnectionError::ServeConnection, err))
1181    }
1182}
1183
1184/// A collection of HTTP request handlers for custom endpoints.
1185#[derive(Default)]
1186pub struct Handlers(HashMap<(Method, &'static str), HyperHandler>);
1187
1188impl std::fmt::Debug for Handlers {
1189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1190        let s = self.0.keys().fold(String::new(), |curr, next| {
1191            let (method, uri) = next;
1192            format!("{curr}\n({method},{uri}): Box<Fn(ResponseBuilder) -> Result<Response<Body>> + Send + Sync + 'static>")
1193        });
1194        write!(f, "HashMap<{s}>")
1195    }
1196}
1197
1198impl std::ops::Deref for Handlers {
1199    type Target = HashMap<(Method, &'static str), HyperHandler>;
1200
1201    fn deref(&self) -> &Self::Target {
1202        &self.0
1203    }
1204}
1205
1206impl std::ops::DerefMut for Handlers {
1207    fn deref_mut(&mut self) -> &mut Self::Target {
1208        &mut self.0
1209    }
1210}
1211
1212/// Requires a future to complete before the specified duration elapses, unless the timeout is cleared.
1213///
1214/// If the future completes before the duration has elapsed, then the completed value is returned.
1215/// Otherwise, an error is returned and the future is canceled.
1216///
1217/// If `clear_timeout` is triggered, the timeout is cleared and the future is always run to completion.
1218async fn clearable_timeout<F: Future>(
1219    timeout: Duration,
1220    clear_timeout: Arc<Notify>,
1221    fut: F,
1222) -> Result<F::Output, Elapsed> {
1223    tokio::pin!(fut);
1224    let timeout = MaybeFuture::Some(tokio::time::sleep(timeout));
1225    tokio::pin!(timeout);
1226    loop {
1227        tokio::select! {
1228            biased;
1229            res = &mut fut => {
1230                return Ok(res);
1231            }
1232            _ = clear_timeout.notified() => {
1233                timeout.as_mut().set_none();
1234            },
1235            _ = &mut timeout => {
1236                return Err(Elapsed);
1237            }
1238        }
1239    }
1240}
1241
1242#[stack_error(derive)]
1243#[error("Timeout elapsed")]
1244struct Elapsed;
1245
1246#[cfg(test)]
1247mod tests {
1248    use std::sync::Arc;
1249
1250    use iroh_base::{PublicKey, SecretKey};
1251    use iroh_dns::dns::DnsResolver;
1252    use n0_error::{Result, StdResultExt, bail_any};
1253    use n0_future::{SinkExt, StreamExt};
1254    use n0_tracing_test::traced_test;
1255    use rand::{RngExt, SeedableRng};
1256    use reqwest::Url;
1257    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1258    use tracing::info;
1259
1260    use super::*;
1261    use crate::{
1262        client::{Client, ClientBuilder, ConnectError, conn::Conn},
1263        protos::relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg},
1264        tls::{CaTlsConfig, default_provider},
1265    };
1266
1267    pub(crate) fn make_tls_config() -> TlsConfig {
1268        let subject_alt_names = vec!["localhost".to_string()];
1269
1270        let cert = rcgen::generate_simple_self_signed(subject_alt_names).unwrap();
1271        let rustls_certificate = cert.cert.der().clone();
1272        let rustls_key =
1273            rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
1274        let config = rustls::ServerConfig::builder_with_provider(Arc::new(
1275            rustls::crypto::ring::default_provider(),
1276        ))
1277        .with_safe_default_protocol_versions()
1278        .expect("protocols supported by ring")
1279        .with_no_client_auth()
1280        .with_single_cert(vec![(rustls_certificate)], rustls_key.into())
1281        .expect("cert is right");
1282
1283        TlsConfig::new(Arc::new(config))
1284    }
1285
1286    /// Linux completes at most `backlog + 1` handshakes that are not yet accepted,
1287    /// then drops further SYNs, so a sequential connect beyond that times out.
1288    #[cfg(target_os = "linux")]
1289    #[tokio::test]
1290    #[traced_test]
1291    async fn test_listen_backlog() -> Result {
1292        const BACKLOG: u32 = 4;
1293        const MAX_CLIENTS: usize = 64;
1294
1295        let listener =
1296            bind_listener((std::net::Ipv4Addr::LOCALHOST, 0).into(), BACKLOG).anyerr()?;
1297        let addr = listener.local_addr().anyerr()?;
1298
1299        let mut streams = Vec::new();
1300        while streams.len() < MAX_CLIENTS {
1301            let connect = TcpStream::connect(addr);
1302            match tokio::time::timeout(Duration::from_millis(250), connect).await {
1303                Ok(stream) => streams.push(stream.anyerr()?),
1304                Err(_elapsed) => break,
1305            }
1306        }
1307        assert!(
1308            (BACKLOG..=BACKLOG + 1).contains(&(streams.len() as u32)),
1309            "accept queue held {} connections for backlog {BACKLOG}",
1310            streams.len()
1311        );
1312        Ok(())
1313    }
1314
1315    #[tokio::test]
1316    #[traced_test]
1317    async fn test_http_clients_and_server() -> Result {
1318        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1319
1320        let a_key = SecretKey::from_bytes(&rng.random());
1321        let b_key = SecretKey::from_bytes(&rng.random());
1322
1323        // start server
1324        let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()).spawn()?;
1325
1326        let addr = server.addr();
1327
1328        // get dial info
1329        let port = addr.port();
1330        let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
1331            ipv4_addr
1332        } else {
1333            bail_any!("cannot get ipv4 addr from socket addr {addr:?}");
1334        };
1335
1336        info!("addr: {addr}:{port}");
1337        let relay_addr: Url = format!("http://{addr}:{port}").parse().unwrap();
1338
1339        // create clients
1340        let (a_key, mut client_a) = create_test_client(a_key, relay_addr.clone()).await?;
1341        info!("created client {a_key:?}");
1342        let (b_key, mut client_b) = create_test_client(b_key, relay_addr).await?;
1343        info!("created client {b_key:?}");
1344
1345        info!("ping a");
1346        client_a.send(ClientToRelayMsg::Ping([1u8; 8])).await?;
1347        let pong = client_a.next().await.expect("eos")?;
1348        assert!(matches!(pong, RelayToClientMsg::Pong { .. }));
1349
1350        info!("ping b");
1351        client_b.send(ClientToRelayMsg::Ping([2u8; 8])).await?;
1352        let pong = client_b.next().await.expect("eos")?;
1353        assert!(matches!(pong, RelayToClientMsg::Pong { .. }));
1354
1355        info!("sending message from a to b");
1356        let msg = Datagrams::from(b"hi there, client b!");
1357        client_a
1358            .send(ClientToRelayMsg::Datagrams {
1359                dst_endpoint_id: b_key,
1360                datagrams: msg.clone(),
1361            })
1362            .await?;
1363        info!("waiting for message from a on b");
1364        let (got_key, got_msg) =
1365            process_msg(client_b.next().await).expect("expected message from client_a");
1366        assert_eq!(a_key, got_key);
1367        assert_eq!(msg, got_msg);
1368
1369        info!("sending message from b to a");
1370        let msg = Datagrams::from(b"right back at ya, client b!");
1371        client_b
1372            .send(ClientToRelayMsg::Datagrams {
1373                dst_endpoint_id: a_key,
1374                datagrams: msg.clone(),
1375            })
1376            .await?;
1377        info!("waiting for message b on a");
1378        let (got_key, got_msg) =
1379            process_msg(client_a.next().await).expect("expected message from client_b");
1380        assert_eq!(b_key, got_key);
1381        assert_eq!(msg, got_msg);
1382
1383        // Close before shutting down, otherwise we'll try to send close frames on broken pipes
1384        client_a.close().await?;
1385        client_b.close().await?;
1386        server.shutdown();
1387
1388        Ok(())
1389    }
1390
1391    async fn create_test_client(
1392        key: SecretKey,
1393        server_url: Url,
1394    ) -> Result<(PublicKey, Client), ConnectError> {
1395        let public_key = key.public();
1396        let client = ClientBuilder::new(server_url, key, DnsResolver::new()).tls_client_config(
1397            CaTlsConfig::insecure_skip_verify()
1398                .client_config(default_provider())
1399                .expect("infallible"),
1400        );
1401        let client = client.connect().await?;
1402
1403        Ok((public_key, client))
1404    }
1405
1406    fn process_msg(
1407        msg: Option<Result<RelayToClientMsg, crate::client::RecvError>>,
1408    ) -> Option<(PublicKey, Datagrams)> {
1409        match msg {
1410            Some(Err(e)) => {
1411                info!("client `recv` error {e}");
1412                None
1413            }
1414            Some(Ok(msg)) => {
1415                info!("got message on: {msg:?}");
1416                if let RelayToClientMsg::Datagrams {
1417                    remote_endpoint_id: source,
1418                    datagrams,
1419                } = msg
1420                {
1421                    Some((source, datagrams))
1422                } else {
1423                    None
1424                }
1425            }
1426            None => {
1427                info!("client end of stream");
1428                None
1429            }
1430        }
1431    }
1432
1433    #[tokio::test]
1434    #[traced_test]
1435    async fn test_subprotocol_negotiation_picks_latest() -> Result {
1436        let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap()).spawn()?;
1437        let addr = server.addr();
1438
1439        for offered in [
1440            "iroh-relay-v2,iroh-relay-v1",
1441            "iroh-relay-v1,iroh-relay-v2",
1442            "baz, iroh-relay-v1, iroh-relay-v2, boo",
1443            "foo, iroh-relay-v2, bar",
1444        ] {
1445            let ws_uri = format!("ws://{addr}/{RELAY_RELATIVE_PATH}");
1446            let (_stream, response) = tokio_websockets::ClientBuilder::new()
1447                .uri(&ws_uri)
1448                .expect("valid websocket URI")
1449                .add_header(
1450                    SEC_WEBSOCKET_PROTOCOL,
1451                    HeaderValue::from_str(offered).expect("valid subprotocol header value"),
1452                )
1453                .expect("header accepted by websocket client")
1454                .connect()
1455                .await
1456                .expect("websocket upgrade succeeds");
1457            let negotiated = response
1458                .headers()
1459                .get(SEC_WEBSOCKET_PROTOCOL)
1460                .expect("Sec-WebSocket-Protocol response header is present");
1461            assert_eq!(negotiated, "iroh-relay-v2", "offered={offered}");
1462        }
1463
1464        server.shutdown();
1465        Ok(())
1466    }
1467
1468    #[tokio::test]
1469    #[traced_test]
1470    async fn test_https_clients_and_server() -> Result {
1471        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1472
1473        let a_key = SecretKey::from_bytes(&rng.random());
1474        let b_key = SecretKey::from_bytes(&rng.random());
1475
1476        // create tls_config
1477        let tls_config = make_tls_config();
1478
1479        // start server
1480        let mut server = ServerBuilder::new("127.0.0.1:0".parse().unwrap())
1481            .tls_config(Some(tls_config))
1482            .spawn()?;
1483
1484        let addr = server.addr();
1485
1486        // get dial info
1487        let port = addr.port();
1488        let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
1489            ipv4_addr
1490        } else {
1491            bail_any!("cannot get ipv4 addr from socket addr {addr:?}");
1492        };
1493
1494        info!("Relay listening on: {addr}:{port}");
1495
1496        let url: Url = format!("https://localhost:{port}").parse().unwrap();
1497
1498        // create clients
1499        let (a_key, mut client_a) = create_test_client(a_key, url.clone()).await?;
1500        info!("created client {a_key:?}");
1501        let (b_key, mut client_b) = create_test_client(b_key, url).await?;
1502        info!("created client {b_key:?}");
1503
1504        info!("ping a");
1505        client_a.send(ClientToRelayMsg::Ping([1u8; 8])).await?;
1506        let pong = client_a.next().await.expect("eos")?;
1507        assert!(matches!(pong, RelayToClientMsg::Pong { .. }));
1508
1509        info!("ping b");
1510        client_b.send(ClientToRelayMsg::Ping([2u8; 8])).await?;
1511        let pong = client_b.next().await.expect("eos")?;
1512        assert!(matches!(pong, RelayToClientMsg::Pong { .. }));
1513
1514        info!("sending message from a to b");
1515        let msg = Datagrams::from(b"hi there, client b!");
1516        client_a
1517            .send(ClientToRelayMsg::Datagrams {
1518                dst_endpoint_id: b_key,
1519                datagrams: msg.clone(),
1520            })
1521            .await?;
1522        info!("waiting for message from a on b");
1523        let (got_key, got_msg) =
1524            process_msg(client_b.next().await).expect("expected message from client_a");
1525        assert_eq!(a_key, got_key);
1526        assert_eq!(msg, got_msg);
1527
1528        info!("sending message from b to a");
1529        let msg = Datagrams::from(b"right back at ya, client b!");
1530        client_b
1531            .send(ClientToRelayMsg::Datagrams {
1532                dst_endpoint_id: a_key,
1533                datagrams: msg.clone(),
1534            })
1535            .await?;
1536        info!("waiting for message b on a");
1537        let (got_key, got_msg) =
1538            process_msg(client_a.next().await).expect("expected message from client_b");
1539        assert_eq!(b_key, got_key);
1540        assert_eq!(msg, got_msg);
1541
1542        // Close before shutting down, otherwise we'll try to send close frames on broken pipes
1543        client_a.close().await?;
1544        client_b.close().await?;
1545        server.shutdown();
1546        server.task_handle().await.std_context("join")?;
1547
1548        Ok(())
1549    }
1550
1551    async fn make_test_client(client: tokio::io::DuplexStream, key: &SecretKey) -> Result<Conn> {
1552        let client = crate::client::streams::MaybeTlsStream::Test(client);
1553        let client = tokio_websockets::ClientBuilder::new().take_over(client);
1554        let client = Conn::new(client, KeyCache::test(), key, Default::default()).await?;
1555        Ok(client)
1556    }
1557
1558    #[tokio::test]
1559    #[traced_test]
1560    async fn test_server_basic() -> Result {
1561        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1562
1563        info!("Create the server.");
1564        let metrics = Arc::new(Metrics::default());
1565        let service = RelayService::new(
1566            Default::default(),
1567            Default::default(),
1568            None,
1569            KeyCache::test(),
1570            Arc::new(crate::server::AllowAll),
1571            metrics.clone(),
1572        );
1573
1574        info!("Create client A and connect it to the server.");
1575        let key_a = SecretKey::from_bytes(&rng.random());
1576        let public_key_a = key_a.public();
1577        let (client_a, rw_a) = tokio::io::duplex(10);
1578        let s = service.clone();
1579        let handler_task = tokio::spawn(async move {
1580            s.0.accept(
1581                MaybeTlsStream::Test(rw_a),
1582                Request::new(()).into_parts().0,
1583                Default::default(),
1584            )
1585            .await
1586        });
1587        let mut client_a = make_test_client(client_a, &key_a).await?;
1588        handler_task.await.std_context("join")??;
1589
1590        info!("Create client B and connect it to the server.");
1591        let key_b = SecretKey::from_bytes(&rng.random());
1592        let public_key_b = key_b.public();
1593        let (client_b, rw_b) = tokio::io::duplex(10);
1594        let s = service.clone();
1595        let handler_task = tokio::spawn(async move {
1596            s.0.accept(
1597                MaybeTlsStream::Test(rw_b),
1598                Request::new(()).into_parts().0,
1599                Default::default(),
1600            )
1601            .await
1602        });
1603        let mut client_b = make_test_client(client_b, &key_b).await?;
1604        handler_task.await.std_context("join")??;
1605
1606        info!("Send message from A to B.");
1607        let msg = Datagrams::from(b"hello client b!!");
1608        client_a
1609            .send(ClientToRelayMsg::Datagrams {
1610                dst_endpoint_id: public_key_b,
1611                datagrams: msg.clone(),
1612            })
1613            .await?;
1614        match client_b.next().await.unwrap()? {
1615            RelayToClientMsg::Datagrams {
1616                remote_endpoint_id,
1617                datagrams,
1618            } => {
1619                assert_eq!(public_key_a, remote_endpoint_id);
1620                assert_eq!(msg, datagrams);
1621            }
1622            msg => {
1623                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1624            }
1625        }
1626
1627        info!("Send message from B to A.");
1628        let msg = Datagrams::from(b"nice to meet you client a!!");
1629        client_b
1630            .send(ClientToRelayMsg::Datagrams {
1631                dst_endpoint_id: public_key_a,
1632                datagrams: msg.clone(),
1633            })
1634            .await?;
1635        match client_a.next().await.unwrap()? {
1636            RelayToClientMsg::Datagrams {
1637                remote_endpoint_id,
1638                datagrams,
1639            } => {
1640                assert_eq!(public_key_b, remote_endpoint_id);
1641                assert_eq!(msg, datagrams);
1642            }
1643            msg => {
1644                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1645            }
1646        }
1647
1648        info!("Close the server and clients");
1649        service.shutdown().await;
1650        tokio::time::sleep(Duration::from_secs(1)).await;
1651
1652        info!("Fail to send message from A to B.");
1653        let res = client_a
1654            .send(ClientToRelayMsg::Datagrams {
1655                dst_endpoint_id: public_key_b,
1656                datagrams: Datagrams::from(b"try to send"),
1657            })
1658            .await;
1659        assert!(res.is_err());
1660        assert!(client_b.next().await.is_none());
1661
1662        drop(client_a);
1663        drop(client_b);
1664
1665        service.shutdown().await;
1666
1667        assert_eq!(metrics.accepts.get(), metrics.disconnects.get());
1668
1669        Ok(())
1670    }
1671
1672    #[tokio::test]
1673    async fn test_server_replace_client() -> Result {
1674        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1675
1676        info!("Create the server.");
1677        let service = RelayService::new(
1678            Default::default(),
1679            Default::default(),
1680            None,
1681            KeyCache::test(),
1682            Arc::new(crate::server::AllowAll),
1683            Default::default(),
1684        );
1685
1686        info!("Create client A and connect it to the server.");
1687        let key_a = SecretKey::from_bytes(&rng.random());
1688        let public_key_a = key_a.public();
1689        let (client_a, rw_a) = tokio::io::duplex(10);
1690        let s = service.clone();
1691        let handler_task = tokio::spawn(async move {
1692            s.0.accept(
1693                MaybeTlsStream::Test(rw_a),
1694                Request::new(()).into_parts().0,
1695                Default::default(),
1696            )
1697            .await
1698        });
1699        let mut client_a = make_test_client(client_a, &key_a).await?;
1700        handler_task.await.std_context("join")??;
1701
1702        info!("Create client B and connect it to the server.");
1703        let key_b = SecretKey::from_bytes(&rng.random());
1704        let public_key_b = key_b.public();
1705        let (client_b, rw_b) = tokio::io::duplex(10);
1706        let s = service.clone();
1707        let handler_task = tokio::spawn(async move {
1708            s.0.accept(
1709                MaybeTlsStream::Test(rw_b),
1710                Request::new(()).into_parts().0,
1711                Default::default(),
1712            )
1713            .await
1714        });
1715        let mut client_b = make_test_client(client_b, &key_b).await?;
1716        handler_task.await.std_context("join")??;
1717
1718        info!("Send message from A to B.");
1719        let msg = Datagrams::from(b"hello client b!!");
1720        client_a
1721            .send(ClientToRelayMsg::Datagrams {
1722                dst_endpoint_id: public_key_b,
1723                datagrams: msg.clone(),
1724            })
1725            .await?;
1726        match client_b.next().await.expect("eos")? {
1727            RelayToClientMsg::Datagrams {
1728                remote_endpoint_id,
1729                datagrams,
1730            } => {
1731                assert_eq!(public_key_a, remote_endpoint_id);
1732                assert_eq!(msg, datagrams);
1733            }
1734            msg => {
1735                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1736            }
1737        }
1738
1739        info!("Send message from B to A.");
1740        let msg = Datagrams::from(b"nice to meet you client a!!");
1741        client_b
1742            .send(ClientToRelayMsg::Datagrams {
1743                dst_endpoint_id: public_key_a,
1744                datagrams: msg.clone(),
1745            })
1746            .await?;
1747        match client_a.next().await.expect("eos")? {
1748            RelayToClientMsg::Datagrams {
1749                remote_endpoint_id,
1750                datagrams,
1751            } => {
1752                assert_eq!(public_key_b, remote_endpoint_id);
1753                assert_eq!(msg, datagrams);
1754            }
1755            msg => {
1756                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1757            }
1758        }
1759
1760        info!("Create client B and connect it to the server");
1761        let (new_client_b, new_rw_b) = tokio::io::duplex(10);
1762        let s = service.clone();
1763        let handler_task = tokio::spawn(async move {
1764            s.0.accept(
1765                MaybeTlsStream::Test(new_rw_b),
1766                Request::new(()).into_parts().0,
1767                Default::default(),
1768            )
1769            .await
1770        });
1771        let mut new_client_b = make_test_client(new_client_b, &key_b).await?;
1772        handler_task.await.std_context("join")??;
1773
1774        // assert!(client_b.recv().await.is_err());
1775
1776        info!("Send message from A to B.");
1777        let msg = Datagrams::from(b"are you still there, b?!");
1778        client_a
1779            .send(ClientToRelayMsg::Datagrams {
1780                dst_endpoint_id: public_key_b,
1781                datagrams: msg.clone(),
1782            })
1783            .await?;
1784        match new_client_b.next().await.expect("eos")? {
1785            RelayToClientMsg::Datagrams {
1786                remote_endpoint_id,
1787                datagrams,
1788            } => {
1789                assert_eq!(public_key_a, remote_endpoint_id);
1790                assert_eq!(msg, datagrams);
1791            }
1792            msg => {
1793                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1794            }
1795        }
1796
1797        info!("Send message from B to A.");
1798        let msg = Datagrams::from(b"just had a spot of trouble but I'm back now,a!!");
1799        new_client_b
1800            .send(ClientToRelayMsg::Datagrams {
1801                dst_endpoint_id: public_key_a,
1802                datagrams: msg.clone(),
1803            })
1804            .await?;
1805        match client_a.next().await.expect("eos")? {
1806            RelayToClientMsg::Datagrams {
1807                remote_endpoint_id,
1808                datagrams,
1809            } => {
1810                assert_eq!(public_key_b, remote_endpoint_id);
1811                assert_eq!(msg, datagrams);
1812            }
1813            msg => {
1814                bail_any!("expected ReceivedDatagrams msg, got {msg:?}");
1815            }
1816        }
1817
1818        info!("Close the server and clients");
1819        service.shutdown().await;
1820
1821        info!("Sending message from A to B fails");
1822        let res = client_a
1823            .send(ClientToRelayMsg::Datagrams {
1824                dst_endpoint_id: public_key_b,
1825                datagrams: Datagrams::from(b"try to send"),
1826            })
1827            .await;
1828        assert!(res.is_err());
1829        assert!(new_client_b.next().await.is_none());
1830        Ok(())
1831    }
1832
1833    #[tokio::test]
1834    #[traced_test]
1835    async fn test_establish_timeout() -> Result {
1836        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42u64);
1837
1838        // Start server with a very short establish timeout.
1839        let server = ServerBuilder::new("127.0.0.1:0".parse().unwrap())
1840            .establish_timeout(Duration::from_millis(500))
1841            .spawn()?;
1842
1843        let addr = server.addr();
1844        let port = addr.port();
1845        let addr = if let std::net::IpAddr::V4(ipv4_addr) = addr.ip() {
1846            ipv4_addr
1847        } else {
1848            bail_any!("cannot get ipv4 addr from socket addr {addr:?}");
1849        };
1850        let relay_url: Url = format!("http://{addr}:{port}").parse().unwrap();
1851
1852        // 1. A lingering connection that never upgrades should be aborted by the timeout.
1853        info!("opening lingering TCP connection (no upgrade)");
1854        let mut lingering = TcpStream::connect(format!("{addr}:{port}")).await?;
1855        // Write a partial HTTP request but never complete the upgrade.
1856        lingering
1857            .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n")
1858            .await?;
1859        // Wait for the server to abort this connection.
1860        let mut buf = [0u8; 1];
1861        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1862        let read = tokio::time::timeout_at(deadline, lingering.read(&mut buf)).await;
1863        // The server should close the connection, resulting in a read of 0 bytes or an error.
1864        match read {
1865            Ok(Ok(0)) => info!("lingering connection closed by server (EOF)"),
1866            Ok(Err(e)) => info!("lingering connection closed by server (error: {e})"),
1867            other => bail_any!("expected lingering connection to be closed, got {other:?}"),
1868        }
1869
1870        // 2. A properly established client should NOT be aborted by the timeout.
1871        info!("connecting a proper relay client");
1872        let key = SecretKey::from_bytes(&rng.random());
1873        let (_, mut client) = create_test_client(key, relay_url).await?;
1874
1875        // Wait longer than the establish timeout to prove the connection survives.
1876        tokio::time::sleep(Duration::from_millis(1000)).await;
1877
1878        // Ping should still work.
1879        client.send(ClientToRelayMsg::Ping([7u8; 8])).await?;
1880        let pong = client.next().await.expect("expected pong")?;
1881        assert!(matches!(pong, RelayToClientMsg::Pong { .. }));
1882        info!("established connection survived past the timeout");
1883
1884        client.close().await?;
1885        server.shutdown();
1886        Ok(())
1887    }
1888}