iroh_dns_server/
http.rs

1//! HTTP server part of iroh-dns-server
2
3use std::{
4    net::{IpAddr, Ipv4Addr, SocketAddr},
5    time::Instant,
6};
7
8use axum::{
9    Router,
10    extract::{ConnectInfo, Request, State},
11    handler::Handler,
12    http::Method,
13    middleware::{self, Next},
14    response::IntoResponse,
15    routing::get,
16};
17use n0_error::{Result, StdResultExt, anyerr, bail_any};
18use serde::{Deserialize, Serialize};
19use tokio::{net::TcpListener, task::JoinSet};
20use tower_http::{
21    cors::{self, CorsLayer},
22    trace::TraceLayer,
23};
24use tracing::{Level, info, span, warn};
25
26mod doh;
27mod error;
28mod pkarr;
29mod rate_limiting;
30mod tls;
31
32pub use self::{rate_limiting::RateLimitConfig, tls::CertMode};
33use crate::{config::Config, state::AppState};
34
35/// Config for the HTTP server
36#[derive(Debug, Serialize, Deserialize, Clone)]
37pub struct HttpConfig {
38    /// Port to bind to
39    pub port: u16,
40    /// Optionally set a custom bind address (will use 0.0.0.0 if unset)
41    pub bind_addr: Option<IpAddr>,
42}
43
44/// Config for the HTTPS server
45#[derive(Debug, Serialize, Deserialize, Clone)]
46pub struct HttpsConfig {
47    /// Port to bind to
48    pub port: u16,
49    /// Optionally set a custom bind address (will use 0.0.0.0 if unset)
50    pub bind_addr: Option<IpAddr>,
51    /// The list of domains for which SSL certificates should be created.
52    pub domains: Vec<String>,
53    /// The mode of SSL certificate creation
54    pub cert_mode: CertMode,
55    /// Letsencrypt contact email address (required if using [`CertMode::LetsEncrypt`])
56    pub letsencrypt_contact: Option<String>,
57    /// Whether to use the letsenrypt production servers (only applies to [`CertMode::LetsEncrypt`])
58    pub letsencrypt_prod: Option<bool>,
59}
60
61/// The HTTP(S) server part of iroh-dns-server
62pub struct HttpServer {
63    tasks: JoinSet<std::io::Result<()>>,
64    http_addr: Option<SocketAddr>,
65    https_addr: Option<SocketAddr>,
66}
67
68impl HttpServer {
69    /// Spawn the server
70    pub async fn spawn(
71        http_config: Option<HttpConfig>,
72        https_config: Option<HttpsConfig>,
73        rate_limit_config: RateLimitConfig,
74        state: AppState,
75    ) -> Result<HttpServer> {
76        if http_config.is_none() && https_config.is_none() {
77            bail_any!("Either http or https config is required");
78        }
79
80        let app = create_app(state, &rate_limit_config);
81
82        let mut tasks = JoinSet::new();
83
84        // launch http
85        let http_addr = if let Some(config) = http_config {
86            let bind_addr = SocketAddr::new(
87                config.bind_addr.unwrap_or(Ipv4Addr::UNSPECIFIED.into()),
88                config.port,
89            );
90            let app = app.clone();
91            let listener = TcpListener::bind(bind_addr)
92                .await
93                .anyerr()?
94                .into_std()
95                .anyerr()?;
96            let bound_addr = listener.local_addr().anyerr()?;
97            let fut = axum_server::from_tcp(listener)
98                .serve(app.into_make_service_with_connect_info::<SocketAddr>());
99            info!("HTTP server listening on {bind_addr}");
100            tasks.spawn(fut);
101            Some(bound_addr)
102        } else {
103            None
104        };
105
106        // launch https
107        let https_addr = if let Some(config) = https_config {
108            let bind_addr = SocketAddr::new(
109                config.bind_addr.unwrap_or(Ipv4Addr::UNSPECIFIED.into()),
110                config.port,
111            );
112            let acceptor = {
113                let cache_path = Config::data_dir()?
114                    .join("cert_cache")
115                    .join(config.cert_mode.to_string());
116                tokio::fs::create_dir_all(&cache_path)
117                    .await
118                    .with_std_context(|_| {
119                        format!("failed to create cert cache dir at {cache_path:?}")
120                    })?;
121                config
122                    .cert_mode
123                    .build(
124                        config.domains,
125                        cache_path,
126                        config.letsencrypt_contact,
127                        config.letsencrypt_prod.unwrap_or(false),
128                    )
129                    .await?
130            };
131            let listener = TcpListener::bind(bind_addr)
132                .await
133                .anyerr()?
134                .into_std()
135                .anyerr()?;
136            let bound_addr = listener.local_addr().anyerr()?;
137            let fut = axum_server::from_tcp(listener)
138                .acceptor(acceptor)
139                .serve(app.into_make_service_with_connect_info::<SocketAddr>());
140            info!("HTTPS server listening on {bind_addr}");
141            tasks.spawn(fut);
142            Some(bound_addr)
143        } else {
144            None
145        };
146
147        Ok(HttpServer {
148            tasks,
149            http_addr,
150            https_addr,
151        })
152    }
153
154    /// Get the bound address of the HTTP socket.
155    pub fn http_addr(&self) -> Option<SocketAddr> {
156        self.http_addr
157    }
158
159    /// Get the bound address of the HTTPS socket.
160    pub fn https_addr(&self) -> Option<SocketAddr> {
161        self.https_addr
162    }
163
164    /// Shutdown the server and wait for all tasks to complete.
165    pub async fn shutdown(mut self) -> Result<()> {
166        // TODO: Graceful cancellation.
167        self.tasks.abort_all();
168        self.run_until_done().await?;
169        Ok(())
170    }
171
172    /// Wait for all tasks to complete.
173    ///
174    /// Runs forever unless tasks fail.
175    pub async fn run_until_done(mut self) -> Result<()> {
176        let mut final_res: Result<()> = Ok(());
177        while let Some(res) = self.tasks.join_next().await {
178            match res {
179                Ok(Ok(())) => {}
180                Err(err) if err.is_cancelled() => {}
181                Ok(Err(err)) => {
182                    warn!(?err, "task failed");
183                    final_res = Err(anyerr!(err, "task"));
184                }
185                Err(err) => {
186                    warn!(?err, "task panicked");
187                    final_res = Err(anyerr!(err, "join"));
188                }
189            }
190        }
191        final_res
192    }
193}
194
195pub(crate) fn create_app(state: AppState, rate_limit_config: &RateLimitConfig) -> Router {
196    // configure cors middleware
197    let cors = CorsLayer::new()
198        // allow `GET` and `POST` when accessing the resource
199        .allow_methods([Method::GET, Method::POST, Method::PUT])
200        // allow requests from any origin
201        .allow_origin(cors::Any);
202
203    // configure tracing middleware
204    let trace = TraceLayer::new_for_http().make_span_with(|request: &http::Request<_>| {
205        let conn_info = request
206            .extensions()
207            .get::<ConnectInfo<SocketAddr>>()
208            .expect("connectinfo extension to be present");
209        let span = span!(
210        Level::DEBUG,
211            "http_request",
212            method = ?request.method(),
213            uri = ?request.uri(),
214            src = %conn_info.0,
215            );
216        span
217    });
218
219    // configure rate limiting middleware
220    let rate_limit = rate_limiting::create(rate_limit_config);
221
222    // configure routes
223    //
224    // only the pkarr::put route gets a rate limit
225    let router = Router::new()
226        .route("/dns-query", get(doh::get).post(doh::post))
227        .route(
228            "/pkarr/{key}",
229            if let Some(rate_limit) = rate_limit {
230                get(pkarr::get).put(pkarr::put.layer(rate_limit))
231            } else {
232                get(pkarr::get).put(pkarr::put)
233            },
234        )
235        .route("/healthcheck", get(|| async { "OK" }))
236        .route("/", get(|| async { "Hi!" }))
237        .with_state(state.clone());
238
239    // configure app
240    router
241        .layer(cors)
242        .layer(trace)
243        .route_layer(middleware::from_fn_with_state(state, metrics_middleware))
244}
245
246/// Record request metrics.
247// TODO:
248// * Request duration would be much better tracked as a histogram.
249// * It would be great to attach labels to the metrics, so that the recorded metrics
250// can filter by method etc.
251//
252// See also
253// https://github.com/tokio-rs/axum/blob/main/examples/prometheus-metrics/src/main.rs#L114
254async fn metrics_middleware(
255    State(state): State<AppState>,
256    req: Request,
257    next: Next,
258) -> impl IntoResponse {
259    let start = Instant::now();
260    let response = next.run(req).await;
261    let latency = start.elapsed().as_millis();
262    let status = response.status();
263    state
264        .metrics
265        .http_requests_duration_ms
266        .inc_by(latency as u64);
267    state.metrics.http_requests.inc();
268    if status.is_success() {
269        state.metrics.http_requests_success.inc();
270    } else {
271        state.metrics.http_requests_error.inc();
272    }
273    response
274}