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