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