certmagic 0.1.0

Automatic TLS certificate acquisition, renewal, and maintenance for Rust servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Framework-neutral HTTPS serving wrapper.
//!
//! The wrapper intentionally exposes a small owned HTTP/1.1 request/response
//! model instead of coupling certmagic to hyper, axum, or tower. TLS
//! certificate resolution still uses [`crate::tls_integration::CertmagicAcceptor`]
//! and HTTP-01 requests are answered before the redirect path.

use std::collections::HashSet;
use std::future::Future;
use std::sync::Arc;

use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

use crate::error::{Error, Result};
use crate::solvers::http::handle_http_challenge_request_async;

/// An owned HTTP request passed to an [`https`] service.
#[derive(Debug, Clone)]
pub struct HttpsRequest {
    /// Request method, e.g. `GET`.
    pub method: String,
    /// Request target including path and query.
    pub target: String,
    /// Headers in wire order.
    pub headers: Vec<(String, String)>,
    /// Request body, capped by the parser at 1 MiB.
    pub body: Vec<u8>,
}

impl HttpsRequest {
    /// Look up a header case-insensitively.
    #[must_use]
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(key, _)| key.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }
}

/// An HTTP response returned by an [`https`] service.
#[derive(Debug, Clone)]
pub struct HttpsResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response headers.
    pub headers: Vec<(String, String)>,
    /// Response body.
    pub body: Vec<u8>,
}

/// Policy and URL builder for HTTP-to-HTTPS redirects.
#[derive(Debug, Clone)]
pub struct HttpsRedirectHandler {
    /// Destination HTTPS port. Port 443 is omitted from generated URLs.
    pub https_port: u16,
    canonical_host: Option<String>,
    allowed_hosts: HashSet<String>,
}

impl Default for HttpsRedirectHandler {
    fn default() -> Self {
        Self {
            https_port: 443,
            canonical_host: None,
            allowed_hosts: HashSet::new(),
        }
    }
}

impl HttpsRedirectHandler {
    /// Create a redirect policy for `https_port`.
    #[must_use]
    pub fn new(https_port: u16) -> Self {
        Self {
            https_port,
            ..Self::default()
        }
    }

    /// Force every redirect to use `host`.
    pub fn with_canonical_host(mut self, host: &str) -> Result<Self> {
        self.canonical_host = Some(normalize_redirect_host(host)?);
        Ok(self)
    }

    /// Allow a request host when no canonical host is configured.
    pub fn allow_host(mut self, host: &str) -> Result<Self> {
        self.allowed_hosts.insert(normalize_redirect_host(host)?);
        Ok(self)
    }

    /// Build a redirect URL without enforcing the host policy.
    #[must_use]
    pub fn redirect_url(&self, host: &str, target: &str) -> String {
        let host = self
            .canonical_host
            .clone()
            .or_else(|| normalize_redirect_host(host).ok())
            .unwrap_or_else(|| "localhost".into());
        format_redirect_url(&host, self.https_port, target)
    }

    /// Build a redirect URL while enforcing canonical/allowed-host policy.
    pub fn try_redirect_url(&self, host: &str, target: &str) -> Result<String> {
        let host = if let Some(canonical) = &self.canonical_host {
            canonical.clone()
        } else {
            let normalized = normalize_redirect_host(host)?;
            if !self.allowed_hosts.contains(&normalized) {
                return Err(Error::Config(crate::error::ConfigError::Invalid(format!(
                    "request Host {normalized:?} is not allowed for redirect"
                ))));
            }
            normalized
        };
        Ok(format_redirect_url(&host, self.https_port, target))
    }

    /// Start a standalone HTTP redirect listener.
    ///
    /// A canonical host or at least one allowed host is required so the
    /// listener cannot reflect arbitrary `Host` headers into redirects.
    pub async fn start(&self, bind_addr: &str) -> Result<tokio::task::JoinHandle<()>> {
        if self.canonical_host.is_none() && self.allowed_hosts.is_empty() {
            return Err(Error::Config(crate::error::ConfigError::Invalid(
                "redirect requires a canonical host or an allowed host".into(),
            )));
        }
        let listener = TcpListener::bind(bind_addr).await.map_err(Error::from)?;
        let redirect = self.clone();
        Ok(tokio::spawn(async move {
            loop {
                let Ok((stream, _)) = listener.accept().await else {
                    return;
                };
                let redirect = redirect.clone();
                tokio::spawn(async move {
                    if let Err(error) = serve_redirect(stream, &redirect).await {
                        tracing::debug!(%error, "redirect connection closed with error");
                    }
                });
            }
        }))
    }
}

/// Start a standalone HTTP-to-HTTPS redirect listener using the default
/// policy.
///
/// The default policy intentionally has no allowed host, so this function
/// returns a configuration error until a caller chooses a canonical host (or
/// uses [`HttpsRedirectHandler::start`] after adding an allowlist).  Keeping
/// exposing this helper keeps the one-shot form available without
/// weakening the host-header safety contract.
pub async fn start_https_redirect(bind_addr: &str) -> Result<tokio::task::JoinHandle<()>> {
    HttpsRedirectHandler::default().start(bind_addr).await
}

/// Start an HTTP-to-HTTPS redirect listener with a custom HTTPS port.
pub async fn start_https_redirect_with_port(
    bind_addr: &str,
    https_port: u16,
) -> Result<tokio::task::JoinHandle<()>> {
    HttpsRedirectHandler::new(https_port).start(bind_addr).await
}

/// Start an HTTP-to-HTTPS redirect listener for a fixed canonical host.
pub async fn start_https_redirect_to_host(
    bind_addr: &str,
    canonical_host: &str,
) -> Result<tokio::task::JoinHandle<()>> {
    HttpsRedirectHandler::new(443)
        .with_canonical_host(canonical_host)?
        .start(bind_addr)
        .await
}

fn normalize_redirect_host(host: &str) -> Result<String> {
    let host = host.trim();
    if host.is_empty()
        || host
            .chars()
            .any(|ch| ch.is_ascii_control() || ch.is_whitespace())
        || host.contains(['/', '\\', '@', '?', '#'])
    {
        return Err(Error::Config(crate::error::ConfigError::Invalid(
            "invalid redirect host".into(),
        )));
    }

    // Normalize IP literals first. SocketAddr handles bracketed IPv6 with a
    // port, while IpAddr handles bare IPv4/IPv6 and bracketless IPv6.
    if let Ok(addr) = host.parse::<std::net::SocketAddr>() {
        return Ok(format_redirect_authority_host(addr.ip()));
    }
    if let Ok(ip) = host.parse::<std::net::IpAddr>() {
        return Ok(format_redirect_authority_host(ip));
    }
    if let Some(inner) = host
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
        && let Ok(ip) = inner.parse::<std::net::IpAddr>()
    {
        return Ok(format_redirect_authority_host(ip));
    }

    // A bracketed value which was not parsed as an IP literal is malformed;
    // never reflect a partial bracketed host into a Location header.
    if host.starts_with('[') || host.ends_with(']') {
        return Err(Error::Config(crate::error::ConfigError::Invalid(
            "invalid redirect host".into(),
        )));
    }
    let hostname = if host.matches(':').count() == 1 {
        let (name, port) = host.rsplit_once(':').ok_or_else(|| {
            Error::Config(crate::error::ConfigError::Invalid(
                "invalid redirect host".into(),
            ))
        })?;
        if name.is_empty() || port.is_empty() || port.parse::<u16>().is_err() {
            return Err(Error::Config(crate::error::ConfigError::Invalid(
                "invalid redirect host".into(),
            )));
        }
        name
    } else if host.contains(':') {
        return Err(Error::Config(crate::error::ConfigError::Invalid(
            "invalid redirect host".into(),
        )));
    } else {
        host
    };
    if hostname.is_empty() {
        return Err(Error::Config(crate::error::ConfigError::Invalid(
            "invalid redirect host".into(),
        )));
    }
    Ok(hostname.to_ascii_lowercase())
}

fn format_redirect_authority_host(ip: std::net::IpAddr) -> String {
    match ip {
        std::net::IpAddr::V4(ip) => ip.to_string(),
        std::net::IpAddr::V6(ip) => format!("[{ip}]"),
    }
}

fn format_redirect_url(host: &str, https_port: u16, target: &str) -> String {
    let target = if target.starts_with('/')
        && !target.contains(['\r', '\n', '\\'])
        && !target.starts_with("//")
    {
        target
    } else {
        "/"
    };
    if https_port == 443 {
        format!("https://{host}{target}")
    } else {
        format!("https://{host}:{https_port}{target}")
    }
}

impl HttpsResponse {
    /// Construct a response with a content type and body.
    #[must_use]
    pub fn new(status: u16, content_type: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
        Self {
            status,
            headers: vec![("content-type".into(), content_type.into())],
            body: body.into(),
        }
    }
}

/// Serve HTTPS on the configured ports and block until either accept loop
/// fails. HTTP-01 validation is answered on the HTTP port; all other HTTP
/// requests receive a 301 redirect to HTTPS.
pub async fn https<F, Fut>(domain_names: &[String], service: F) -> Result<()>
where
    F: Fn(HttpsRequest) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = HttpsResponse> + Send + 'static,
{
    let https_port = crate::HTTPS_PORT.load(std::sync::atomic::Ordering::Relaxed);
    let http_port = crate::HTTP_PORT.load(std::sync::atomic::Ordering::Relaxed);
    https_on(
        std::net::SocketAddr::from(([0, 0, 0, 0], https_port)),
        std::net::SocketAddr::from(([0, 0, 0, 0], http_port)),
        domain_names,
        service,
    )
    .await
}

/// Bind explicit HTTPS and HTTP addresses and run the framework-neutral
/// serving loops.
pub async fn https_on<F, Fut>(
    https_addr: std::net::SocketAddr,
    http_addr: std::net::SocketAddr,
    domain_names: &[String],
    service: F,
) -> Result<()>
where
    F: Fn(HttpsRequest) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = HttpsResponse> + Send + 'static,
{
    let (https_listener, acceptor) = crate::listen_on(https_addr, domain_names).await?;
    let http_listener = TcpListener::bind(http_addr).await.map_err(Error::from)?;
    // The HTTP side must not reflect an arbitrary Host header into a
    // Location response.  Reuse the certificate names as the default host
    // policy; callers that need another policy can use HttpsRedirectHandler
    // directly with their own listener.
    let mut redirect = HttpsRedirectHandler::new(https_addr.port());
    for domain in domain_names {
        if let Ok(policy) = redirect.clone().allow_host(domain) {
            redirect = policy;
        }
    }
    let service = Arc::new(service);
    let tls_task = tokio::spawn(serve_tls(
        https_listener,
        Arc::new(acceptor),
        Arc::clone(&service),
    ));
    let http_task = tokio::spawn(serve_http(http_listener, redirect));
    let result = tokio::select! {
        result = tls_task => result.map_err(|e| Error::Internal(format!("HTTPS task: {e}")))?,
        result = http_task => result.map_err(|e| Error::Internal(format!("HTTP task: {e}")))?,
    };
    result?;
    Ok(())
}

async fn serve_tls<F, Fut>(
    listener: TcpListener,
    acceptor: Arc<crate::tls_integration::CertmagicAcceptor>,
    service: Arc<F>,
) -> Result<()>
where
    F: Fn(HttpsRequest) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = HttpsResponse> + Send + 'static,
{
    loop {
        let (stream, _) = listener.accept().await.map_err(Error::from)?;
        let acceptor = Arc::clone(&acceptor);
        let service = Arc::clone(&service);
        tokio::spawn(async move {
            match acceptor.accept(stream).await {
                Ok(handshake) => match handshake.await {
                    Ok(tls) => {
                        if let Err(error) = serve_connection(tls, service).await {
                            tracing::debug!(%error, "HTTPS connection closed with error");
                        }
                    }
                    Err(error) => tracing::debug!(%error, "TLS handshake failed"),
                },
                Err(error) => tracing::debug!(%error, "TLS handshake failed"),
            }
        });
    }
}

async fn serve_http(listener: TcpListener, redirect: HttpsRedirectHandler) -> Result<()> {
    loop {
        let (stream, _) = listener.accept().await.map_err(Error::from)?;
        let redirect = redirect.clone();
        tokio::spawn(async move {
            if let Err(error) = serve_redirect(stream, &redirect).await {
                tracing::debug!(%error, "HTTP connection closed with error");
            }
        });
    }
}

async fn serve_redirect(mut stream: TcpStream, redirect: &HttpsRedirectHandler) -> Result<()> {
    let request = read_request(&mut stream).await?;
    let host = request.header("host").unwrap_or_default();
    if let Some(answer) =
        handle_http_challenge_request_async(host, &request.method, &request.target).await
    {
        write_response(
            &mut stream,
            HttpsResponse::new(200, "text/plain", answer.into_bytes()),
        )
        .await?;
        return Ok(());
    }
    let location = match redirect.try_redirect_url(host, &request.target) {
        Ok(location) => location,
        Err(_) => {
            let response = HttpsResponse::new(400, "text/plain", b"invalid host\n".to_vec());
            write_response(&mut stream, response).await?;
            return Ok(());
        }
    };
    let mut response = HttpsResponse::new(301, "text/plain", b"redirecting\n".to_vec());
    response.headers.push(("location".into(), location));
    write_response(&mut stream, response).await
}

async fn serve_connection<IO, F, Fut>(mut stream: IO, service: Arc<F>) -> Result<()>
where
    IO: AsyncRead + AsyncWrite + Unpin,
    F: Fn(HttpsRequest) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = HttpsResponse> + Send + 'static,
{
    let request = read_request(&mut stream).await?;
    let response = service(request).await;
    write_response(&mut stream, response).await
}

async fn read_request<IO>(stream: &mut IO) -> Result<HttpsRequest>
where
    IO: AsyncRead + Unpin,
{
    const MAX_HEADERS: usize = 64 * 1024;
    const MAX_BODY: usize = 1024 * 1024;
    let mut bytes = Vec::with_capacity(2048);
    let mut chunk = [0_u8; 2048];
    let header_end = loop {
        let read = stream.read(&mut chunk).await.map_err(Error::from)?;
        if read == 0 {
            return Err(Error::Internal("HTTP peer closed before headers".into()));
        }
        bytes.extend_from_slice(&chunk[..read]);
        if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
            break end + 4;
        }
        if bytes.len() > MAX_HEADERS {
            return Err(Error::Internal("HTTP headers exceed 64 KiB".into()));
        }
    };
    let header_text = String::from_utf8_lossy(&bytes[..header_end]);
    let mut lines = header_text.split("\r\n");
    let request_line = lines
        .next()
        .ok_or_else(|| Error::Internal("HTTP request line missing".into()))?;
    let mut parts = request_line.split_whitespace();
    let method = parts.next().unwrap_or_default().to_owned();
    let target = parts.next().unwrap_or_default().to_owned();
    if method.is_empty() || target.is_empty() {
        return Err(Error::Internal("HTTP request line malformed".into()));
    }
    let headers: Vec<(String, String)> = lines
        .filter_map(|line| line.split_once(':'))
        .map(|(name, value)| (name.trim().to_owned(), value.trim().to_owned()))
        .collect();
    let content_length = headers
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
        .and_then(|(_, value)| value.parse::<usize>().ok())
        .unwrap_or(0);
    if content_length > MAX_BODY {
        return Err(Error::Internal("HTTP body exceeds 1 MiB".into()));
    }
    while bytes.len() - header_end < content_length {
        let read = stream.read(&mut chunk).await.map_err(Error::from)?;
        if read == 0 {
            return Err(Error::Internal("HTTP peer closed in body".into()));
        }
        bytes.extend_from_slice(&chunk[..read]);
    }
    Ok(HttpsRequest {
        method,
        target,
        headers,
        body: bytes[header_end..header_end + content_length].to_vec(),
    })
}

async fn write_response<IO>(stream: &mut IO, mut response: HttpsResponse) -> Result<()>
where
    IO: AsyncWrite + Unpin,
{
    response
        .headers
        .retain(|(name, _)| !name.eq_ignore_ascii_case("content-length"));
    let reason = match response.status {
        200 => "OK",
        301 => "Moved Permanently",
        400 => "Bad Request",
        404 => "Not Found",
        500 => "Internal Server Error",
        _ => "Response",
    };
    let mut output = format!("HTTP/1.1 {} {reason}\r\n", response.status);
    for (name, value) in response.headers {
        output.push_str(&name);
        output.push_str(": ");
        output.push_str(&value);
        output.push_str("\r\n");
    }
    output.push_str(&format!(
        "content-length: {}\r\nconnection: close\r\n\r\n",
        response.body.len()
    ));
    stream
        .write_all(output.as_bytes())
        .await
        .map_err(Error::from)?;
    stream
        .write_all(&response.body)
        .await
        .map_err(Error::from)?;
    stream.flush().await.map_err(Error::from)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redirect_policy_enforces_allowed_hosts() {
        let handler = HttpsRedirectHandler::new(8443)
            .allow_host("Example.com:80")
            .unwrap();
        assert_eq!(
            handler.try_redirect_url("EXAMPLE.COM", "/a?b=1").unwrap(),
            "https://example.com:8443/a?b=1"
        );
        assert!(handler.try_redirect_url("other.example.com", "/").is_err());
    }

    #[test]
    fn redirect_policy_uses_canonical_host_and_sanitizes_target() {
        let handler = HttpsRedirectHandler::default()
            .with_canonical_host("Example.com")
            .unwrap();
        assert_eq!(
            handler.redirect_url("attacker.example", "//evil.example/path"),
            "https://example.com/"
        );
        assert_eq!(
            handler.redirect_url("attacker.example", "/\\evil.example/path"),
            "https://example.com/"
        );
    }

    #[test]
    fn redirect_policy_normalizes_ipv6_and_rejects_malformed_hosts() {
        let handler = HttpsRedirectHandler::new(8443)
            .allow_host("[2001:DB8::1]:80")
            .unwrap();
        assert_eq!(
            handler
                .try_redirect_url("[2001:db8::1]:8080", "/check?x=1")
                .unwrap(),
            "https://[2001:db8::1]:8443/check?x=1"
        );
        assert!(handler.try_redirect_url("[2001:db8::2]:8080", "/").is_err());
        assert!(
            HttpsRedirectHandler::default()
                .with_canonical_host("example.com:not-a-port")
                .is_err()
        );
        assert!(
            HttpsRedirectHandler::default()
                .with_canonical_host("[2001:db8::1")
                .is_err()
        );
        assert!(
            HttpsRedirectHandler::new(8443)
                .allow_host("example.com:not-a-port")
                .is_err()
        );
    }

    #[test]
    fn redirect_requires_a_host_policy_when_used_for_a_listener() {
        let handler = HttpsRedirectHandler::new(8443);
        assert!(handler.try_redirect_url("attacker.example", "/").is_err());
    }
}