iroh_dns_server/
http.rs

1//! HTTP server part of iroh-dns-server
2
3use std::{
4    net::{IpAddr, Ipv6Addr, SocketAddr},
5    path::PathBuf,
6    time::{Duration, Instant},
7};
8
9use axum::{
10    Json, Router,
11    extract::{ConnectInfo, Request, State},
12    handler::Handler,
13    http::Method,
14    middleware::{self, Next},
15    response::IntoResponse,
16    routing::get,
17};
18use hyper_util::{
19    rt::{TokioExecutor, TokioTimer},
20    server::conn::auto,
21};
22use n0_error::{Result, StdResultExt, anyerr, bail_any};
23use serde::{Deserialize, Serialize};
24use socket2::{SockRef, TcpKeepalive};
25use tokio::{net::TcpSocket, task::JoinSet};
26use tower_http::{
27    cors::{self, CorsLayer},
28    trace::TraceLayer,
29};
30use tracing::{Level, info, span, warn};
31
32mod doh;
33mod error;
34mod pkarr;
35mod rate_limiting;
36mod tls;
37
38pub use self::{rate_limiting::RateLimitConfig, tls::CertMode};
39use crate::state::AppState;
40
41/// How long a connection may be idle before keepalive probing starts.
42const TCP_KEEPALIVE_TIME: Duration = Duration::from_mins(1);
43
44/// Interval between keepalive probes once probing starts.
45const TCP_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
46
47/// Enable TCP keepalive on `listener`, which accepted connections inherit.
48///
49/// Without it, connections whose peer vanished without closing are never
50/// reaped: they accumulate for the lifetime of the process until it is
51/// OOM-killed.
52fn set_keepalive(listener: &std::net::TcpListener) -> std::io::Result<()> {
53    let keepalive = TcpKeepalive::new()
54        .with_time(TCP_KEEPALIVE_TIME)
55        .with_interval(TCP_KEEPALIVE_INTERVAL);
56    SockRef::from(listener).set_tcp_keepalive(&keepalive)
57}
58
59/// Listen backlog when none is configured.
60/// Tokio and std default to 128, which
61/// overflows under bursts of slow handshakes.
62const DEFAULT_LISTEN_BACKLOG: u32 = 1024;
63
64/// Bind a TCP listener on `addr` with a listen queue of `backlog`.
65fn bind_listener(addr: SocketAddr, backlog: u32) -> std::io::Result<std::net::TcpListener> {
66    let socket = match addr {
67        SocketAddr::V4(_) => TcpSocket::new_v4()?,
68        SocketAddr::V6(_) => TcpSocket::new_v6()?,
69    };
70
71    #[cfg(not(windows))]
72    socket.set_reuseaddr(true)?;
73    socket.bind(addr)?;
74    socket.listen(backlog)?.into_std()
75}
76
77/// How long a connection may take to send the headers of its next request.
78///
79/// This also closes keep-alive connections that stay idle after a request.
80const HTTP1_HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
81
82/// Enable hyper's HTTP/1 header read timeout.
83///
84/// hyper ignores its default timeout unless a timer is set and
85/// idle connections then stay open forever.
86fn set_header_read_timeout(builder: &mut auto::Builder<TokioExecutor>) {
87    builder
88        .http1()
89        .timer(TokioTimer::new())
90        .header_read_timeout(HTTP1_HEADER_READ_TIMEOUT);
91}
92
93/// Configuration for the HTTP listener.
94#[derive(Debug, Serialize, Deserialize, Clone)]
95#[non_exhaustive]
96pub struct HttpConfig {
97    /// Port to bind the HTTP listener to.
98    pub port: u16,
99    /// Address to bind the HTTP listener to (defaults to `::`, i.e. IPv6 wildcard which also covers IPv4).
100    pub bind_addr: Option<IpAddr>,
101    /// Listen queue length (defaults to 1024, capped by `net.core.somaxconn` on Linux).
102    pub listen_backlog: Option<u32>,
103}
104
105/// Configuration for the HTTPS listener.
106///
107/// Certificates are obtained according to [`Self::cert_mode`].
108#[derive(Debug, Serialize, Deserialize, Clone)]
109#[non_exhaustive]
110pub struct HttpsConfig {
111    /// Port to bind the HTTPS listener to.
112    pub port: u16,
113    /// Address to bind the HTTPS listener to (defaults to `::`, i.e. IPv6 wildcard which also covers IPv4).
114    pub bind_addr: Option<IpAddr>,
115    /// Listen queue length (defaults to 1024, capped by `net.core.somaxconn` on Linux).
116    pub listen_backlog: Option<u32>,
117    /// Domains for which TLS certificates are issued or loaded.
118    pub domains: Vec<String>,
119    /// Strategy used to obtain TLS certificates.
120    pub cert_mode: CertMode,
121    /// Contact email address passed to Let's Encrypt.
122    ///
123    /// Required when [`Self::cert_mode`] is [`CertMode::LetsEncrypt`]; ignored
124    /// otherwise.
125    pub letsencrypt_contact: Option<String>,
126    /// Whether to use the Let's Encrypt production endpoint instead of staging.
127    ///
128    /// Only applies when [`Self::cert_mode`] is [`CertMode::LetsEncrypt`]. When
129    /// unset, the ACME staging endpoint is used.
130    pub letsencrypt_prod: Option<bool>,
131}
132
133/// The HTTP(S) server part of iroh-dns-server
134#[derive(Debug)]
135pub(crate) struct HttpServer {
136    tasks: JoinSet<std::io::Result<()>>,
137    http_addr: Option<SocketAddr>,
138    https_addr: Option<SocketAddr>,
139}
140
141impl HttpServer {
142    /// Spawn the server
143    pub(crate) async fn spawn(
144        http_config: Option<HttpConfig>,
145        https_config: Option<HttpsConfig>,
146        rate_limit_config: RateLimitConfig,
147        state: AppState,
148        cert_cache_dir: PathBuf,
149    ) -> Result<HttpServer> {
150        if http_config.is_none() && https_config.is_none() {
151            bail_any!("Either http or https config is required");
152        }
153
154        let app = create_app(state, &rate_limit_config);
155
156        let mut tasks = JoinSet::new();
157
158        // launch http
159        let http_addr = if let Some(config) = http_config {
160            let bind_addr = SocketAddr::new(
161                config.bind_addr.unwrap_or(Ipv6Addr::UNSPECIFIED.into()),
162                config.port,
163            );
164            let app = app.clone();
165            let backlog = config.listen_backlog.unwrap_or(DEFAULT_LISTEN_BACKLOG);
166            let listener = bind_listener(bind_addr, backlog).anyerr()?;
167            let bound_addr = listener.local_addr().anyerr()?;
168            set_keepalive(&listener).anyerr()?;
169            let mut server = axum_server::from_tcp(listener)?;
170            set_header_read_timeout(server.http_builder());
171            let fut = server.serve(app.into_make_service_with_connect_info::<SocketAddr>());
172            info!("HTTP server listening on {bind_addr}");
173            tasks.spawn(fut);
174            Some(bound_addr)
175        } else {
176            None
177        };
178
179        // launch https
180        let https_addr = if let Some(config) = https_config {
181            let bind_addr = SocketAddr::new(
182                config.bind_addr.unwrap_or(Ipv6Addr::UNSPECIFIED.into()),
183                config.port,
184            );
185            let acceptor = {
186                tokio::fs::create_dir_all(&cert_cache_dir)
187                    .await
188                    .with_std_context(|_| {
189                        format!(
190                            "failed to create cert cache dir at {}",
191                            cert_cache_dir.display()
192                        )
193                    })?;
194                config
195                    .cert_mode
196                    .build(
197                        config.domains,
198                        cert_cache_dir,
199                        config.letsencrypt_contact,
200                        config.letsencrypt_prod.unwrap_or(false),
201                    )
202                    .await?
203            };
204            let backlog = config.listen_backlog.unwrap_or(DEFAULT_LISTEN_BACKLOG);
205            let listener = bind_listener(bind_addr, backlog).anyerr()?;
206            let bound_addr = listener.local_addr().anyerr()?;
207            set_keepalive(&listener).anyerr()?;
208            let mut server = axum_server::from_tcp(listener)?.acceptor(acceptor);
209            set_header_read_timeout(server.http_builder());
210            let fut = server.serve(app.into_make_service_with_connect_info::<SocketAddr>());
211            info!("HTTPS server listening on {bind_addr}");
212            tasks.spawn(fut);
213            Some(bound_addr)
214        } else {
215            None
216        };
217
218        Ok(HttpServer {
219            tasks,
220            http_addr,
221            https_addr,
222        })
223    }
224
225    /// Get the bound address of the HTTP socket.
226    pub(crate) fn http_addr(&self) -> Option<SocketAddr> {
227        self.http_addr
228    }
229
230    /// Get the bound address of the HTTPS socket.
231    pub(crate) fn https_addr(&self) -> Option<SocketAddr> {
232        self.https_addr
233    }
234
235    /// Shutdown the server and wait for all tasks to complete.
236    pub(crate) async fn shutdown(mut self) -> Result<()> {
237        // TODO: Graceful cancellation.
238        self.tasks.abort_all();
239        self.run_until_done().await?;
240        Ok(())
241    }
242
243    /// Wait for all tasks to complete.
244    ///
245    /// Runs forever unless tasks fail.
246    pub(crate) async fn run_until_done(mut self) -> Result<()> {
247        let mut final_res: Result<()> = Ok(());
248        while let Some(res) = self.tasks.join_next().await {
249            match res {
250                Ok(Ok(())) => {}
251                Err(err) if err.is_cancelled() => {}
252                Ok(Err(err)) => {
253                    warn!(?err, "task failed");
254                    final_res = Err(anyerr!(err, "task"));
255                }
256                Err(err) => {
257                    warn!(?err, "task panicked");
258                    final_res = Err(anyerr!(err, "join"));
259                }
260            }
261        }
262        final_res
263    }
264}
265
266/// Health check response
267#[derive(Serialize)]
268struct Health {
269    status: &'static str,
270    version: &'static str,
271    git_hash: &'static str,
272}
273
274async fn healthz() -> Json<Health> {
275    Json(Health {
276        status: "ok",
277        version: env!("CARGO_PKG_VERSION"),
278        git_hash: "unknown",
279    })
280}
281
282pub(crate) fn create_app(state: AppState, rate_limit_config: &RateLimitConfig) -> Router {
283    // configure cors middleware
284    let cors = CorsLayer::new()
285        // allow `GET` and `POST` when accessing the resource
286        .allow_methods([Method::GET, Method::POST, Method::PUT])
287        // allow requests from any origin
288        .allow_origin(cors::Any);
289
290    // configure tracing middleware
291    let trace = TraceLayer::new_for_http().make_span_with(|request: &http::Request<_>| {
292        let conn_info = request
293            .extensions()
294            .get::<ConnectInfo<SocketAddr>>()
295            .expect("connectinfo extension to be present");
296        let span = span!(
297        Level::DEBUG,
298            "http_request",
299            method = ?request.method(),
300            uri = ?request.uri(),
301            src = %conn_info.0,
302            );
303        span
304    });
305
306    // configure rate limiting middleware
307    let rate_limit = rate_limiting::create(rate_limit_config);
308
309    // configure routes
310    //
311    // only the pkarr::put route gets a rate limit
312    let router = Router::new()
313        .route("/dns-query", get(doh::get).post(doh::post))
314        .route(
315            "/pkarr/{key}",
316            if let Some(rate_limit) = rate_limit {
317                get(pkarr::get).put(pkarr::put.layer(rate_limit))
318            } else {
319                get(pkarr::get).put(pkarr::put)
320            },
321        )
322        // Deprecated: use /healthz instead
323        .route("/healthcheck", get(|| async { "OK" }))
324        .route("/healthz", get(healthz))
325        .route("/", get(|| async { "Hi!" }))
326        .with_state(state.clone());
327
328    // configure app
329    router
330        .layer(cors)
331        .layer(trace)
332        .route_layer(middleware::from_fn_with_state(state, metrics_middleware))
333}
334
335/// Record request metrics.
336// TODO:
337// * Request duration would be much better tracked as a histogram.
338// * It would be great to attach labels to the metrics, so that the recorded metrics
339// can filter by method etc.
340//
341// See also
342// https://github.com/tokio-rs/axum/blob/main/examples/prometheus-metrics/src/main.rs#L114
343async fn metrics_middleware(
344    State(state): State<AppState>,
345    req: Request,
346    next: Next,
347) -> impl IntoResponse {
348    let start = Instant::now();
349    let response = next.run(req).await;
350    let latency = start.elapsed().as_millis();
351    let status = response.status();
352    state
353        .metrics
354        .http_requests_duration_ms
355        .inc_by(latency as u64);
356    state.metrics.http_requests.inc();
357    if status.is_success() {
358        state.metrics.http_requests_success.inc();
359    } else {
360        state.metrics.http_requests_error.inc();
361    }
362    response
363}
364
365#[cfg(test)]
366mod tests {
367    use std::{
368        net::{IpAddr, Ipv4Addr},
369        time::Duration,
370    };
371
372    use iroh::{
373        RelayUrl, SecretKey,
374        address_lookup::{EndpointInfo, PkarrRelayClient},
375        dns::{DNS_TIMEOUT, DnsResolver, NameserverConfig},
376        tls::{CaTlsConfig, default_provider},
377    };
378    use n0_error::StdResultExt;
379    use n0_tracing_test::traced_test;
380    use rand::{RngExt, SeedableRng};
381    use tokio::{
382        io::{AsyncReadExt, AsyncWriteExt},
383        net::TcpStream,
384    };
385
386    use crate::{http::HttpsConfig, server::Server};
387
388    /// Linux completes at most `backlog + 1` handshakes that are not yet accepted,
389    /// then drops further SYNs, so a sequential connect beyond that times out.
390    #[cfg(target_os = "linux")]
391    #[tokio::test]
392    #[traced_test]
393    async fn test_listen_backlog() -> n0_error::Result {
394        const BACKLOG: u32 = 4;
395        const MAX_CLIENTS: u32 = 64;
396
397        let listener = super::bind_listener((Ipv4Addr::LOCALHOST, 0).into(), BACKLOG).anyerr()?;
398        let addr = listener.local_addr().anyerr()?;
399
400        let mut streams = Vec::new();
401        while streams.len() < MAX_CLIENTS as usize {
402            let connect = tokio::net::TcpStream::connect(addr);
403            match tokio::time::timeout(std::time::Duration::from_millis(250), connect).await {
404                Ok(stream) => streams.push(stream.anyerr()?),
405                Err(_elapsed) => break,
406            }
407        }
408        assert!(
409            (BACKLOG..=BACKLOG + 1).contains(&(streams.len() as u32)),
410            "accept queue held {} connections for backlog {BACKLOG}",
411            streams.len()
412        );
413        Ok(())
414    }
415
416    /// Real time the server gets to close a connection once its clock has been advanced.
417    const CLOSE_DEADLINE: Duration = Duration::from_secs(2);
418
419    async fn assert_closed_after(stream: &mut TcpStream, timeout: Duration) -> n0_error::Result {
420        assert_open(stream).await;
421
422        advance(timeout - Duration::from_secs(1)).await;
423        assert_open(stream).await;
424
425        advance(Duration::from_secs(2)).await;
426        let mut buf = [0; 1];
427        let read = tokio::time::timeout(CLOSE_DEADLINE, stream.read(&mut buf))
428            .await
429            .std_context("server did not close the connection")?;
430        match read {
431            Ok(0) => Ok(()),
432            Err(err) if err.kind() == std::io::ErrorKind::ConnectionReset => Ok(()),
433            other => panic!("expected the server to close the connection: {other:?}"),
434        }
435    }
436
437    async fn assert_open(stream: &mut TcpStream) {
438        let mut buf = [0; 1];
439        assert!(
440            tokio::time::timeout(Duration::from_millis(50), stream.read(&mut buf))
441                .await
442                .is_err(),
443            "connection closed before its timeout"
444        );
445    }
446
447    async fn advance(duration: Duration) {
448        tokio::time::pause();
449        tokio::time::advance(duration).await;
450        tokio::time::resume();
451    }
452
453    #[tokio::test]
454    #[traced_test]
455    async fn test_idle_connection_closed() -> n0_error::Result {
456        let dir = tempfile::tempdir()?;
457        let server = Server::spawn_for_tests(dir.path()).await?;
458        let addr = server.http_addr().expect("http is bound");
459
460        let mut stream = TcpStream::connect(addr).await.anyerr()?;
461        stream
462            .write_all(b"GET /healthcheck HTTP/1.1\r\nhost: localhost\r\n\r\n")
463            .await
464            .anyerr()?;
465        let mut response = Vec::new();
466        while !response.ends_with(b"\r\n\r\nOK") {
467            let mut chunk = [0; 1024];
468            let n = tokio::time::timeout(CLOSE_DEADLINE, stream.read(&mut chunk))
469                .await
470                .std_context("no response from server")?
471                .anyerr()?;
472            assert!(n > 0, "connection closed before the response");
473            response.extend_from_slice(&chunk[..n]);
474        }
475        assert!(response.starts_with(b"HTTP/1.1 200 OK"));
476        assert_closed_after(&mut stream, super::HTTP1_HEADER_READ_TIMEOUT).await?;
477
478        server.shutdown().await?;
479        Ok(())
480    }
481
482    #[tokio::test]
483    #[traced_test]
484    async fn test_doh() -> n0_error::Result {
485        let mut rng = rand_chacha::ChaCha12Rng::seed_from_u64(0);
486        let dir = tempfile::tempdir()?;
487        let https_config = HttpsConfig {
488            port: 0,
489            bind_addr: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
490            listen_backlog: None,
491            domains: vec!["localhost".to_string()],
492            cert_mode: crate::http::CertMode::SelfSigned,
493            letsencrypt_contact: None,
494            letsencrypt_prod: None,
495        };
496        let server =
497            Server::spawn_for_tests_with_options(dir.path(), None, None, Some(https_config))
498                .await?;
499
500        const RELAY_URL: &str = "https://relay.example./";
501        let (name_z32, signed_packet) = {
502            let secret_key = SecretKey::from_bytes(&rng.random());
503            let endpoint_id = secret_key.public();
504            let relay_url: RelayUrl = RELAY_URL.parse().expect("valid url");
505            let endpoint_info = EndpointInfo::new(endpoint_id).with_relay_url(relay_url.clone());
506            (
507                secret_key.public().to_z32(),
508                endpoint_info.to_pkarr_signed_packet(&secret_key, 30)?,
509            )
510        };
511
512        let http_url = server.http_url().expect("http is bound");
513        let tls_config = CaTlsConfig::default()
514            .client_config(default_provider())
515            .expect("infallible");
516        let pkarr = PkarrRelayClient::new(
517            format!("{http_url}pkarr").parse().anyerr()?,
518            tls_config,
519            DnsResolver::default(),
520        );
521        pkarr.publish(&signed_packet).await?;
522
523        // Create a reqwest client that does not verify certificates.
524        let client = reqwest::Client::builder()
525            .http2_prior_knowledge()
526            .use_preconfigured_tls(self::tls::insecure_tls_config())
527            .build()
528            .anyerr()?;
529
530        // Fetch as JSON via HTTP.
531        let url = format!(
532            "{http_url}dns-query?name={}&type=txt",
533            format_args!("_iroh.{name_z32}."),
534        );
535        let res = client
536            .get(url)
537            .header("accept", "application/dns-json")
538            .send()
539            .await
540            .anyerr()?
541            .json::<super::doh::response::DnsResponse>()
542            .await
543            .anyerr()?;
544        assert_eq!(res.answer.len(), 1);
545        assert_eq!(res.answer[0].name, format!("_iroh.{name_z32}."));
546        assert_eq!(res.answer[0].data, format!("relay={RELAY_URL}"));
547
548        // Fetch as JSON via HTTPS.
549        let https_url = server.https_url().expect("https is bound");
550        let url = format!(
551            "{https_url}dns-query?name={}&type=txt",
552            format_args!("_iroh.{name_z32}."),
553        );
554        let res = client
555            .get(url)
556            .header("accept", "application/dns-json")
557            .send()
558            .await
559            .anyerr()?
560            .json::<super::doh::response::DnsResponse>()
561            .await
562            .anyerr()?;
563        assert_eq!(res.answer.len(), 1);
564        assert_eq!(res.answer[0].name, format!("_iroh.{name_z32}."));
565        assert_eq!(res.answer[0].data, format!("relay={RELAY_URL}"));
566
567        // Fetch over DNS-over-HTTPS.
568        let resolver = {
569            let https_addr = server.https_addr().expect("https is bound");
570            DnsResolver::builder()
571                .add_nameserver_config(
572                    NameserverConfig::https(https_addr.ip())
573                        .with_port(https_addr.port())
574                        .with_tls_server_name("localhost"),
575                )
576                .tls_client_config(self::tls::insecure_tls_config())
577                .disable_fallback()
578                .build()
579        };
580
581        let records: Vec<_> = resolver
582            .lookup_txt(format!("_iroh.{name_z32}."), DNS_TIMEOUT)
583            .await?
584            .collect();
585        assert_eq!(records.len(), 1);
586        assert_eq!(records[0].to_string(), format!("relay={RELAY_URL}"));
587
588        server.shutdown().await?;
589        Ok(())
590    }
591
592    mod tls {
593        use std::sync::Arc;
594
595        use rustls::{
596            DigitallySignedStruct, RootCertStore,
597            client::{
598                ClientConfig,
599                danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
600            },
601            crypto::{
602                CryptoProvider, ring::default_provider, verify_tls12_signature,
603                verify_tls13_signature,
604            },
605            pki_types::{CertificateDer, ServerName, UnixTime},
606        };
607
608        #[derive(Debug)]
609        struct NoCertificateVerification(CryptoProvider);
610
611        impl Default for NoCertificateVerification {
612            fn default() -> Self {
613                Self(default_provider())
614            }
615        }
616
617        impl ServerCertVerifier for NoCertificateVerification {
618            fn verify_server_cert(
619                &self,
620                _end_entity: &CertificateDer<'_>,
621                _intermediates: &[CertificateDer<'_>],
622                _server_name: &ServerName<'_>,
623                _ocsp: &[u8],
624                _now: UnixTime,
625            ) -> Result<ServerCertVerified, rustls::Error> {
626                Ok(ServerCertVerified::assertion())
627            }
628
629            fn verify_tls12_signature(
630                &self,
631                message: &[u8],
632                cert: &CertificateDer<'_>,
633                dss: &DigitallySignedStruct,
634            ) -> Result<HandshakeSignatureValid, rustls::Error> {
635                verify_tls12_signature(
636                    message,
637                    cert,
638                    dss,
639                    &self.0.signature_verification_algorithms,
640                )
641            }
642
643            fn verify_tls13_signature(
644                &self,
645                message: &[u8],
646                cert: &CertificateDer<'_>,
647                dss: &DigitallySignedStruct,
648            ) -> Result<HandshakeSignatureValid, rustls::Error> {
649                verify_tls13_signature(
650                    message,
651                    cert,
652                    dss,
653                    &self.0.signature_verification_algorithms,
654                )
655            }
656
657            fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
658                self.0.signature_verification_algorithms.supported_schemes()
659            }
660        }
661
662        pub(super) fn insecure_tls_config() -> ClientConfig {
663            let mut cfg = ClientConfig::builder_with_provider(Arc::new(
664                rustls::crypto::ring::default_provider(),
665            ))
666            .with_safe_default_protocol_versions()
667            .unwrap()
668            .with_root_certificates(RootCertStore::empty())
669            .with_no_client_auth();
670            cfg.dangerous()
671                .set_certificate_verifier(Arc::new(NoCertificateVerification::default()));
672            cfg
673        }
674    }
675}