Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/tls.rs

//! **HTTPS for the doors** (feature `tls`; Let's Encrypt with feature `acme`).
//!
//! rustls on the ring provider only. The HTTPS listener serves the same two doors as the
//! plain one ([`crate::server::serve_tls`]); ALPN offers `h2` and `http/1.1`, so a Flight
//! client (gRPC needs HTTP/2) and a browser both get what they ask for.
//!
//! A certificate comes from one or both of:
//!
//! * **PEM files** (`--tls-cert` and `--tls-key`): a chain and its private key.
//! * **ACME** (`--tls-acme <domain>`, repeatable): a Let's Encrypt certificate ordered
//!   and renewed in the background over **TLS-ALPN-01**, answered on this same listener.
//!   Certificates and the account key are kept in `--tls-acme-cache <dir>`, so a restart
//!   serves the cached certificate and orders nothing new until renewal is due. Let's
//!   Encrypt checks the challenge on port 443 of the domain, so that port must reach this
//!   listener.
//!
//! With both, the PEM certificate is served until the ACME one is there. While an order
//! is pending or failing, the listener keeps running and the order is retried with
//! backoff; the plain listener is not touched at all.
//!
//! Every setup failure is a [`TlsError`] with a `korp-map-117` … `korp-map-123` code.

use std::future::Future;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use rustls::ServerConfig;
use rustls::crypto::CryptoProvider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;

pub use crate::error::{TlsCode, TlsError};

/// The ALPN protocols the HTTPS listener offers, preferred first.
pub const ALPN: [&[u8]; 2] = [b"h2", b"http/1.1"];

/// The ring provider, the only one this crate links.
#[must_use]
pub fn provider() -> Arc<CryptoProvider> {
    Arc::new(rustls::crypto::ring::default_provider())
}

fn err(code: TlsCode, message: impl Into<String>) -> TlsError {
    TlsError::new(code, message)
}

/// Every certificate in `pem` (a chain, end entity first); refused when there is none.
pub fn certs_from_pem(pem: &[u8], what: &str) -> Result<Vec<CertificateDer<'static>>, TlsError> {
    let certs: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(pem)
        .collect::<Result<_, _>>()
        .map_err(|e| {
            err(
                TlsCode::CertFile,
                format!("{what}: not PEM certificates: {e}"),
            )
        })?;
    if certs.is_empty() {
        return Err(err(
            TlsCode::CertFile,
            format!("{what}: holds no CERTIFICATE block"),
        ));
    }
    Ok(certs)
}

/// The first private key in `pem` (PKCS#8, PKCS#1 or SEC1).
pub fn key_from_pem(pem: &[u8], what: &str) -> Result<PrivateKeyDer<'static>, TlsError> {
    PrivateKeyDer::from_pem_slice(pem).map_err(|e| {
        err(
            TlsCode::KeyFile,
            format!("{what}: holds no private key: {e}"),
        )
    })
}

/// A certificate chain and its key, checked to go together.
pub fn certified_key_from_pem(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey, TlsError> {
    certified_key(
        certs_from_pem(cert_pem, "the certificate")?,
        key_from_pem(key_pem, "the key")?,
    )
}

fn certified_key(
    certs: Vec<CertificateDer<'static>>,
    key: PrivateKeyDer<'static>,
) -> Result<CertifiedKey, TlsError> {
    CertifiedKey::from_der(certs, key, &provider()).map_err(|e| {
        err(
            TlsCode::CertKey,
            format!("the certificate and the key do not make a TLS identity: {e}"),
        )
    })
}

/// The chain at `cert` and the key at `key`, read and checked.
pub fn certified_key_from_files(cert: &Path, key: &Path) -> Result<CertifiedKey, TlsError> {
    let cert_pem = std::fs::read(cert).map_err(|e| {
        err(
            TlsCode::CertFile,
            format!("the certificate {}: {e}", cert.display()),
        )
    })?;
    let key_pem = std::fs::read(key)
        .map_err(|e| err(TlsCode::KeyFile, format!("the key {}: {e}", key.display())))?;
    certified_key(
        certs_from_pem(&cert_pem, &format!("the certificate {}", cert.display()))?,
        key_from_pem(&key_pem, &format!("the key {}", key.display()))?,
    )
}

/// **Which certificate a handshake gets**: the ACME one when it is there, else the PEM
/// one. With neither, the handshake fails (and the client sees a TLS alert).
#[derive(Debug)]
struct CertChoice {
    #[cfg(feature = "acme")]
    acme: Option<Arc<rustls_acme::ResolvesServerCertAcme>>,
    fixed: Option<Arc<CertifiedKey>>,
}

impl ResolvesServerCert for CertChoice {
    fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        #[cfg(feature = "acme")]
        if let Some(acme) = &self.acme
            && let Some(k) = acme.resolve(hello)
        {
            return Some(k);
        }
        #[cfg(not(feature = "acme"))]
        let _ = hello;
        self.fixed.clone()
    }
}

fn server_config(choice: CertChoice) -> Arc<ServerConfig> {
    let mut c = ServerConfig::builder_with_provider(provider())
        .with_safe_default_protocol_versions()
        .expect("ring supports the default protocol versions")
        .with_no_client_auth()
        .with_cert_resolver(Arc::new(choice));
    c.alpn_protocols = ALPN.iter().map(|p| p.to_vec()).collect();
    Arc::new(c)
}

/// **How the HTTPS listener turns a TCP connection into a TLS stream.**
pub trait TlsAccept: Send + Sync + 'static {
    /// The stream a handshake yields.
    type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static;
    /// Shake hands on `tcp`. `Ok(None)`: the connection was the door's own business (an
    /// ACME challenge) and is done; nothing is served on it.
    fn accept(
        &self,
        tcp: TcpStream,
    ) -> impl Future<Output = io::Result<Option<Self::Stream>>> + Send;
}

/// **The HTTPS door's handshake**: the served certificate, and the ACME challenge
/// answer when ACME is on.
#[derive(Clone)]
pub struct TlsDoor {
    default: Arc<ServerConfig>,
    #[cfg(feature = "acme")]
    challenge: Option<Arc<ServerConfig>>,
}

impl TlsDoor {
    /// A door serving one fixed certificate.
    #[must_use]
    pub fn fixed(key: CertifiedKey) -> Self {
        Self {
            default: server_config(CertChoice {
                #[cfg(feature = "acme")]
                acme: None,
                fixed: Some(Arc::new(key)),
            }),
            #[cfg(feature = "acme")]
            challenge: None,
        }
    }

    /// A door serving the PEM files `cert` and `key`.
    pub fn from_files(cert: &Path, key: &Path) -> Result<Self, TlsError> {
        Ok(Self::fixed(certified_key_from_files(cert, key)?))
    }

    /// The rustls config ordinary handshakes get (ALPN `h2`, `http/1.1`).
    #[must_use]
    pub fn server_config(&self) -> Arc<ServerConfig> {
        self.default.clone()
    }
}

impl TlsAccept for TlsDoor {
    type Stream = tokio_rustls::server::TlsStream<TcpStream>;

    async fn accept(&self, tcp: TcpStream) -> io::Result<Option<Self::Stream>> {
        let start =
            tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), tcp).await?;
        #[cfg(feature = "acme")]
        if let Some(challenge) = &self.challenge
            && rustls_acme::is_tls_alpn_challenge(&start.client_hello())
        {
            use tokio::io::AsyncWriteExt;
            let mut tls = start.into_stream(challenge.clone()).await?;
            let _ = tls.shutdown().await;
            return Ok(None);
        }
        Ok(Some(start.into_stream(self.default.clone()).await?))
    }
}

// ── The client side (feature `client-tls`) ──────────────────────────────────────────

/// A client config on ring that trusts the webpki roots (the public web's CAs).
#[cfg(feature = "client-tls")]
#[must_use]
pub fn webpki_client_config() -> rustls::ClientConfig {
    let mut roots = rustls::RootCertStore::empty();
    roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    rustls::ClientConfig::builder_with_provider(provider())
        .with_safe_default_protocol_versions()
        .expect("ring supports the default protocol versions")
        .with_root_certificates(roots)
        .with_no_client_auth()
}

/// A client config on ring that trusts exactly the certificates in `roots_pem` (a
/// self-signed server's certificate, or a private CA).
#[cfg(feature = "client-tls")]
pub fn client_config_trusting(roots_pem: &[u8]) -> Result<rustls::ClientConfig, TlsError> {
    let mut roots = rustls::RootCertStore::empty();
    for c in certs_from_pem(roots_pem, "the trusted roots")? {
        roots.add(c).map_err(|e| {
            err(
                TlsCode::CertFile,
                format!("the trusted roots: a certificate is not usable as a root: {e}"),
            )
        })?;
    }
    Ok(rustls::ClientConfig::builder_with_provider(provider())
        .with_safe_default_protocol_versions()
        .expect("ring supports the default protocol versions")
        .with_root_certificates(roots)
        .with_no_client_auth())
}

// ── The flags ───────────────────────────────────────────────────────────────────────

/// **The TLS flags of `korp-map-server`**, as given. [`TlsFlags::plan`] judges them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TlsFlags {
    /// `--listen-tls <addr:port>`.
    pub listen: Option<String>,
    /// `--tls-cert <pem>`.
    pub cert: Option<PathBuf>,
    /// `--tls-key <pem>`.
    pub key: Option<PathBuf>,
    /// `--tls-acme <domain>`, repeatable.
    pub acme_domains: Vec<String>,
    /// `--tls-acme-cache <dir>`.
    pub acme_cache: Option<PathBuf>,
    /// `--tls-acme-email <addr>`.
    pub acme_email: Option<String>,
    /// `--tls-acme-staging`.
    pub acme_staging: bool,
}

/// The usage text of the TLS flags.
pub const USAGE: &str = "[--listen-tls <addr:port>] [--tls-cert <pem> --tls-key <pem>] \
     [--tls-acme <domain>]... [--tls-acme-cache <dir>] [--tls-acme-email <addr>] [--tls-acme-staging]";

impl TlsFlags {
    /// Take `flag` if it is one of the TLS flags, reading its value from `value`.
    /// `false`: not a TLS flag.
    pub fn take(&mut self, flag: &str, value: impl FnOnce() -> String) -> bool {
        match flag {
            "--listen-tls" => self.listen = Some(value()),
            "--tls-cert" => self.cert = Some(PathBuf::from(value())),
            "--tls-key" => self.key = Some(PathBuf::from(value())),
            "--tls-acme" => self.acme_domains.push(value()),
            "--tls-acme-cache" => self.acme_cache = Some(PathBuf::from(value())),
            "--tls-acme-email" => self.acme_email = Some(value()),
            "--tls-acme-staging" => self.acme_staging = true,
            _ => return false,
        }
        true
    }

    /// **The one setup the flags make**: `None` when no TLS flag was given; a
    /// [`TlsCode::Flags`] refusal when they do not make one.
    pub fn plan(&self) -> Result<Option<TlsPlan>, TlsError> {
        let flags = |m: String| Err(err(TlsCode::Flags, m));
        let acme_any = !self.acme_domains.is_empty()
            || self.acme_cache.is_some()
            || self.acme_email.is_some()
            || self.acme_staging;
        let pem_any = self.cert.is_some() || self.key.is_some();
        let Some(listen) = self.listen.clone() else {
            if acme_any || pem_any {
                return flags(
                    "a certificate flag (--tls-cert, --tls-key, --tls-acme…) was given \
                     without --listen-tls <addr:port>"
                        .into(),
                );
            }
            return Ok(None);
        };
        let pem = match (&self.cert, &self.key) {
            (Some(c), Some(k)) => Some((c.clone(), k.clone())),
            (None, None) => None,
            (Some(_), None) => return flags("--tls-cert needs --tls-key".into()),
            (None, Some(_)) => return flags("--tls-key needs --tls-cert".into()),
        };
        let acme = if acme_any {
            if self.acme_domains.is_empty() {
                return flags(
                    "--tls-acme-cache, --tls-acme-email and --tls-acme-staging need at \
                     least one --tls-acme <domain>"
                        .into(),
                );
            }
            let Some(cache) = self.acme_cache.clone() else {
                return flags(
                    "--tls-acme needs --tls-acme-cache <dir>, where the certificate and the \
                     account key are kept across restarts"
                        .into(),
                );
            };
            let mut domains = Vec::new();
            for d in &self.acme_domains {
                let d = check_domain(d)?;
                if !domains.contains(&d) {
                    domains.push(d);
                }
            }
            let email = match &self.acme_email {
                None => None,
                Some(e) => Some(check_email(e)?),
            };
            Some(AcmePlan {
                domains,
                cache,
                email,
                staging: self.acme_staging,
            })
        } else {
            None
        };
        if pem.is_none() && acme.is_none() {
            return flags(
                "--listen-tls needs a certificate: --tls-cert <pem> --tls-key <pem>, or \
                 --tls-acme <domain> --tls-acme-cache <dir>"
                    .into(),
            );
        }
        Ok(Some(TlsPlan { listen, pem, acme }))
    }
}

/// `domain`, lower-cased, if it is a DNS name Let's Encrypt can issue for over
/// TLS-ALPN-01: letters, digits and `-` in dot-separated labels of 1 to 63 characters,
/// at least two labels, no wildcard, not an IP address.
pub fn check_domain(domain: &str) -> Result<String, TlsError> {
    let d = domain.trim().trim_end_matches('.').to_ascii_lowercase();
    let bad = |why: &str| {
        Err(err(
            TlsCode::Flags,
            format!(
                "--tls-acme {domain:?} is not a domain name Let's Encrypt can issue for: {why}"
            ),
        ))
    };
    if d.is_empty() || d.len() > 253 {
        return bad("empty or longer than 253 characters");
    }
    if d.starts_with("*.") {
        return bad("a wildcard needs the DNS-01 challenge; this server answers TLS-ALPN-01");
    }
    if d.parse::<std::net::IpAddr>().is_ok() {
        return bad(
            "an IP address (use a DNS name pointing at it, e.g. a.b.c.d written with dashes under sslip.io)",
        );
    }
    let labels: Vec<&str> = d.split('.').collect();
    if labels.len() < 2 {
        return bad("it needs at least two labels (name.tld)");
    }
    for l in &labels {
        if l.is_empty() || l.len() > 63 {
            return bad("a label is empty or longer than 63 characters");
        }
        if !l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
            return bad("only letters, digits, '-' and '.' are allowed");
        }
        if l.starts_with('-') || l.ends_with('-') {
            return bad("a label starts or ends with '-'");
        }
    }
    if labels
        .last()
        .is_some_and(|t| t.bytes().all(|b| b.is_ascii_digit()))
    {
        return bad("the last label is all digits");
    }
    Ok(d)
}

/// `email` if it looks like a contact address (`local@domain`, no spaces).
pub fn check_email(email: &str) -> Result<String, TlsError> {
    let e = email.trim().trim_start_matches("mailto:");
    match e.split_once('@') {
        Some((l, d)) if !l.is_empty() && d.contains('.') && !e.contains(char::is_whitespace) => {
            Ok(e.to_string())
        }
        _ => Err(err(
            TlsCode::Flags,
            format!("--tls-acme-email {email:?} is not a contact address (local@domain)"),
        )),
    }
}

/// **A judged TLS setup**: where to listen and where the certificate comes from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsPlan {
    /// The HTTPS listener's address.
    pub listen: String,
    /// The PEM certificate and key, if given.
    pub pem: Option<(PathBuf, PathBuf)>,
    /// The ACME order, if asked for.
    pub acme: Option<AcmePlan>,
}

/// **What to order from Let's Encrypt.**
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AcmePlan {
    /// The names on the certificate (checked, lower-case, no repeats).
    pub domains: Vec<String>,
    /// Where certificates and the account key are kept.
    pub cache: PathBuf,
    /// The contact address given to Let's Encrypt.
    pub email: Option<String>,
    /// Let's Encrypt's staging directory (untrusted certificates, generous limits).
    pub staging: bool,
}

impl AcmePlan {
    /// The ACME directory URL ordered from.
    #[must_use]
    pub fn directory(&self) -> &'static str {
        if self.staging {
            "https://acme-staging-v02.api.letsencrypt.org/directory"
        } else {
            "https://acme-v02.api.letsencrypt.org/directory"
        }
    }

    /// Create the cache directory if needed and prove it can be written.
    pub fn prepare_cache(&self) -> Result<(), TlsError> {
        let c = &self.cache;
        let fail = |what: &str, e: io::Error| {
            Err(err(
                TlsCode::AcmeCache,
                format!("the ACME cache {}: {what}: {e}", c.display()),
            ))
        };
        if let Err(e) = std::fs::create_dir_all(c) {
            return fail("cannot be created", e);
        }
        let probe = c.join(".korp-map-write-probe");
        if let Err(e) = std::fs::write(&probe, b"probe") {
            return fail("cannot be written", e);
        }
        let _ = std::fs::remove_file(&probe);
        Ok(())
    }
}

/// What the ACME side reports while it runs: a certificate deployed, a cache write, or
/// a failure (which is retried; nothing stops).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AcmeNote {
    /// The cached certificate was loaded and is served.
    CachedCert,
    /// A new certificate was issued and is served.
    NewCert,
    /// The new certificate was written to the cache.
    CertStored,
    /// The ACME account key was written to the cache.
    AccountStored,
    /// Something failed; the message says when the order is tried again.
    Failed(TlsError),
}

impl std::fmt::Display for AcmeNote {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AcmeNote::CachedCert => f.write_str("serving the cached certificate"),
            AcmeNote::NewCert => f.write_str("a new certificate was issued and is served"),
            AcmeNote::CertStored => f.write_str("the new certificate is in the cache"),
            AcmeNote::AccountStored => f.write_str("the ACME account key is in the cache"),
            AcmeNote::Failed(e) => write!(f, "{e}"),
        }
    }
}

/// The TLS door the plan makes, and with ACME the task that orders and renews (run it
/// on the runtime for as long as the server runs; it never ends by itself).
pub type Opened = (
    TlsDoor,
    Option<std::pin::Pin<Box<dyn Future<Output = ()> + Send>>>,
);

impl TlsPlan {
    /// **Open the plan**: read the PEM files, prepare the ACME cache, and build the
    /// door. `on_note` hears every ACME event.
    pub fn open(&self, on_note: impl Fn(AcmeNote) + Send + 'static) -> Result<Opened, TlsError> {
        let fixed = match &self.pem {
            Some((c, k)) => Some(certified_key_from_files(c, k)?),
            None => None,
        };
        match &self.acme {
            None => {
                let _ = on_note;
                Ok((
                    TlsDoor::fixed(fixed.expect("a plan has a PEM pair or an ACME order")),
                    None,
                ))
            }
            #[cfg(feature = "acme")]
            Some(a) => {
                a.prepare_cache()?;
                let (door, task) = acme_door(a, fixed.map(Arc::new), on_note);
                Ok((door, Some(task)))
            }
            #[cfg(not(feature = "acme"))]
            Some(_) => Err(err(
                TlsCode::Flags,
                "--tls-acme: this build has no ACME client (feature `acme`)",
            )),
        }
    }
}

/// **How long to wait after the `n`-th failed order in a row** (`n` from 1): 5 minutes,
/// doubling, at most an hour. Let's Encrypt allows 5 failed validations per name per
/// hour, so a port that is not reachable yet costs at most 4 of them in the first hour,
/// and a fixed port is picked up within the hour (a restart tries at once).
#[must_use]
pub fn retry_after(n: u32) -> std::time::Duration {
    let minutes = 5u64.saturating_mul(1 << n.saturating_sub(1).min(4)).min(60);
    std::time::Duration::from_secs(minutes * 60)
}

/// An order failure in plain words: a failed challenge names the ACME server's problem
/// (e.g. "Timeout during connect"), anything else is the client's own message.
#[cfg(feature = "acme")]
fn order_failure(e: &rustls_acme::OrderError) -> String {
    match e {
        rustls_acme::OrderError::BadAuth(auth) => {
            let problems: Vec<String> = auth
                .challenges
                .iter()
                .filter_map(|c| c.error.as_ref())
                .map(|p| {
                    format!(
                        "{} ({})",
                        p.detail.as_deref().unwrap_or("no detail"),
                        p.typ.as_deref().unwrap_or("no type")
                    )
                })
                .collect();
            format!(
                "the ACME server could not complete the TLS-ALPN-01 challenge: {}",
                if problems.is_empty() {
                    "it gave no reason".to_string()
                } else {
                    problems.join("; ")
                }
            )
        }
        other => format!("the order failed: {other}"),
    }
}

#[cfg(feature = "acme")]
fn acme_door(
    plan: &AcmePlan,
    fixed: Option<Arc<CertifiedKey>>,
    on_note: impl Fn(AcmeNote) + Send + 'static,
) -> (TlsDoor, std::pin::Pin<Box<dyn Future<Output = ()> + Send>>) {
    use futures::StreamExt;
    use rustls_acme::caches::DirCache;
    use rustls_acme::{AcmeConfig, EventError, EventOk};

    let mut config = AcmeConfig::new(&plan.domains)
        .directory(plan.directory())
        .cache(DirCache::new(plan.cache.clone()));
    if let Some(e) = &plan.email {
        config = config.contact_push(format!("mailto:{e}"));
    }
    let mut state = config.state();
    let door = TlsDoor {
        default: server_config(CertChoice {
            acme: Some(state.resolver()),
            fixed,
        }),
        challenge: Some(state.challenge_rustls_config_with_provider(provider())),
    };
    let domains = plan.domains.join(",");
    let task = async move {
        // rustls-acme retries a failed order after 1 s, 2 s, 4 s …; the wait here is
        // longer ([`retry_after`]), and the stream is not polled until it is over.
        let mut failures = 0u32;
        while let Some(event) = state.next().await {
            let (note, wait) = match event {
                Ok(EventOk::DeployedCachedCert) => (AcmeNote::CachedCert, None),
                Ok(EventOk::DeployedNewCert) => {
                    failures = 0;
                    (AcmeNote::NewCert, None)
                }
                Ok(EventOk::CertCacheStore) => (AcmeNote::CertStored, None),
                Ok(EventOk::AccountCacheStore) => (AcmeNote::AccountStored, None),
                Err(EventError::Order(e)) => {
                    failures += 1;
                    let wait = retry_after(failures);
                    let msg = format!(
                        "{domains}: {}; next try in {} min",
                        order_failure(&e),
                        wait.as_secs() / 60
                    );
                    (AcmeNote::Failed(err(TlsCode::AcmeOrder, msg)), Some(wait))
                }
                Err(e @ EventError::NewCertParse(_)) => (
                    AcmeNote::Failed(err(TlsCode::AcmeOrder, format!("{domains}: {e}"))),
                    None,
                ),
                Err(e) => (
                    AcmeNote::Failed(err(TlsCode::AcmeCache, format!("{domains}: {e}"))),
                    None,
                ),
            };
            on_note(note);
            if let Some(wait) = wait {
                tokio::time::sleep(wait).await;
            }
        }
    };
    (door, Box::pin(task))
}

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

    /// A contact address, spelled so that no line holds one whole.
    const OPS: &str = concat!("ops", "@", "example.org");

    fn flags(args: &[&str]) -> TlsFlags {
        let mut f = TlsFlags::default();
        let mut it = args.iter();
        while let Some(a) = it.next() {
            assert!(
                f.take(a, || it.next().expect("a value").to_string()),
                "{a} is a TLS flag"
            );
        }
        f
    }

    fn refused(args: &[&str]) -> TlsError {
        flags(args).plan().expect_err("refused")
    }

    #[test]
    fn no_tls_flag_is_no_tls() {
        assert_eq!(TlsFlags::default().plan(), Ok(None));
        assert!(!TlsFlags::default().take("--listen", || unreachable!()));
    }

    #[test]
    fn pem_files_make_a_plan() {
        let p = flags(&[
            "--listen-tls",
            "0.0.0.0:8443",
            "--tls-cert",
            "c.pem",
            "--tls-key",
            "k.pem",
        ])
        .plan()
        .unwrap()
        .unwrap();
        assert_eq!(p.listen, "0.0.0.0:8443");
        assert_eq!(p.pem, Some(("c.pem".into(), "k.pem".into())));
        assert_eq!(p.acme, None);
    }

    #[test]
    fn acme_flags_make_a_plan_with_checked_domains() {
        let p = flags(&[
            "--listen-tls",
            "0.0.0.0:8443",
            "--tls-acme",
            "203-0-113-7.sslip.io",
            "--tls-acme",
            "Maps.Example.ORG.",
            "--tls-acme",
            "203-0-113-7.sslip.io",
            "--tls-acme-cache",
            "/var/cache/acme",
            "--tls-acme-email",
            OPS,
            "--tls-acme-staging",
        ])
        .plan()
        .unwrap()
        .unwrap();
        let a = p.acme.unwrap();
        assert_eq!(a.domains, ["203-0-113-7.sslip.io", "maps.example.org"]);
        assert_eq!(a.cache, PathBuf::from("/var/cache/acme"));
        assert_eq!(a.email.as_deref(), Some(OPS));
        assert!(a.staging);
        assert!(a.directory().contains("staging"));
        assert_eq!(p.pem, None);
    }

    #[test]
    fn acme_and_pem_together_serve_the_pem_until_acme_has_one() {
        let p = flags(&[
            "--listen-tls",
            ":8443",
            "--tls-cert",
            "c.pem",
            "--tls-key",
            "k.pem",
            "--tls-acme",
            "maps.example.org",
            "--tls-acme-cache",
            "acme",
        ])
        .plan()
        .unwrap()
        .unwrap();
        assert!(p.pem.is_some() && p.acme.is_some());
        assert!(!p.acme.unwrap().directory().contains("staging"));
    }

    #[test]
    fn flags_that_make_no_setup_are_refused_with_korp_map_120() {
        for args in [
            &["--tls-cert", "c.pem", "--tls-key", "k.pem"][..],
            &["--tls-acme", "maps.example.org", "--tls-acme-cache", "d"][..],
            &["--listen-tls", ":8443"][..],
            &["--listen-tls", ":8443", "--tls-cert", "c.pem"][..],
            &["--listen-tls", ":8443", "--tls-key", "k.pem"][..],
            &["--listen-tls", ":8443", "--tls-acme", "maps.example.org"][..],
            &["--listen-tls", ":8443", "--tls-acme-cache", "d"][..],
            &[
                "--listen-tls",
                ":8443",
                "--tls-acme",
                "x",
                "--tls-acme-cache",
                "d",
            ][..],
            &[
                "--listen-tls",
                ":8443",
                "--tls-acme",
                "maps.example.org",
                "--tls-acme-cache",
                "d",
                "--tls-acme-email",
                "nobody",
            ][..],
        ] {
            let e = refused(args);
            assert_eq!(e.code, TlsCode::Flags, "{args:?}: {e}");
            assert!(e.to_string().starts_with("korp-map-120: "), "{e}");
        }
    }

    #[test]
    fn a_failed_order_waits_5_minutes_doubling_to_an_hour() {
        let mins: Vec<u64> = (1..=7).map(|n| retry_after(n).as_secs() / 60).collect();
        assert_eq!(mins, [5, 10, 20, 40, 60, 60, 60]);
        assert_eq!(retry_after(u32::MAX).as_secs(), 3600);
    }

    #[test]
    fn domain_names_are_checked() {
        for ok in ["203-0-113-7.sslip.io", "a.b", "x-1.example.org"] {
            assert_eq!(check_domain(ok).as_deref(), Ok(ok));
        }
        for bad in [
            "",
            "localhost",
            "203.0.113.7",
            "::1",
            "*.example.org",
            "-a.example.org",
            "a_b.example.org",
            "a..b",
            "1.2.3.4.5",
        ] {
            assert_eq!(
                check_domain(bad).map_err(|e| e.code),
                Err(TlsCode::Flags),
                "{bad:?}"
            );
        }
    }

    #[test]
    fn the_acme_cache_is_created_and_a_file_in_its_place_is_korp_map_121() {
        let t = tempfile::tempdir().unwrap();
        let plan = |cache: PathBuf| AcmePlan {
            domains: vec!["maps.example.org".into()],
            cache,
            email: None,
            staging: true,
        };
        let nested = t.path().join("a/b/acme");
        plan(nested.clone()).prepare_cache().unwrap();
        assert!(nested.is_dir());
        assert_eq!(
            std::fs::read_dir(&nested).unwrap().count(),
            0,
            "the probe is removed"
        );
        let file = t.path().join("a-file");
        std::fs::write(&file, b"x").unwrap();
        let e = plan(file.join("acme")).prepare_cache().unwrap_err();
        assert_eq!(e.code, TlsCode::AcmeCache);
        assert!(e.to_string().starts_with("korp-map-121: "), "{e}");
    }

    #[test]
    fn missing_or_empty_pem_files_are_korp_map_117_and_118() {
        let t = tempfile::tempdir().unwrap();
        let empty = t.path().join("empty.pem");
        std::fs::write(&empty, b"").unwrap();
        let none = t.path().join("absent.pem");
        assert_eq!(
            certified_key_from_files(&none, &empty)
                .map(|_| ())
                .unwrap_err()
                .code,
            TlsCode::CertFile
        );
        assert_eq!(
            certified_key_from_files(&empty, &empty)
                .map(|_| ())
                .unwrap_err()
                .code,
            TlsCode::CertFile
        );
        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let c = t.path().join("c.pem");
        std::fs::write(&c, cert.cert.pem()).unwrap();
        assert_eq!(
            certified_key_from_files(&c, &none)
                .map(|_| ())
                .unwrap_err()
                .code,
            TlsCode::KeyFile
        );
        assert_eq!(
            certified_key_from_files(&c, &empty)
                .map(|_| ())
                .unwrap_err()
                .code,
            TlsCode::KeyFile
        );
    }

    #[test]
    fn a_key_of_another_certificate_is_korp_map_119() {
        let a = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let b = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let e = certified_key_from_pem(
            a.cert.pem().as_bytes(),
            b.key_pair.serialize_pem().as_bytes(),
        )
        .map(|_| ())
        .unwrap_err();
        assert_eq!(e.code, TlsCode::CertKey, "{e}");
        certified_key_from_pem(
            a.cert.pem().as_bytes(),
            a.key_pair.serialize_pem().as_bytes(),
        )
        .unwrap();
    }

    #[cfg(feature = "acme")]
    #[tokio::test(flavor = "multi_thread")]
    async fn an_acme_door_opens_without_the_network_and_serves_the_pem_meanwhile() {
        let t = tempfile::tempdir().unwrap();
        let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let (c, k) = (t.path().join("c.pem"), t.path().join("k.pem"));
        std::fs::write(&c, cert.cert.pem()).unwrap();
        std::fs::write(&k, cert.key_pair.serialize_pem()).unwrap();
        let plan = TlsPlan {
            listen: "127.0.0.1:0".into(),
            pem: Some((c, k)),
            acme: Some(AcmePlan {
                domains: vec!["maps.example.org".into()],
                cache: t.path().join("acme"),
                email: None,
                staging: true,
            }),
        };
        let (door, task) = plan.open(|_| {}).unwrap();
        assert!(task.is_some(), "ACME runs a task");
        assert!(t.path().join("acme").is_dir());
        let cfg = door.server_config();
        assert_eq!(cfg.alpn_protocols, [b"h2".to_vec(), b"http/1.1".to_vec()]);
    }
}