Skip to main content

waf_proxy/
tls.rs

1// SPDX-FileCopyrightText: 2026 0x00spor3
2// SPDX-License-Identifier: Apache-2.0
3
4//! Inbound TLS termination (Phase 12).
5//!
6//! **Basic, cert-from-file termination is OPEN core** (`BOUNDARY.md` §3.2): it makes a
7//! single node self-sufficient for `https://`. Cert management *at scale* — ACME/Let's
8//! Encrypt, rotation, centralized multi-node certs, **mTLS with managed PKI** — is
9//! ENTERPRISE (governance/scale) and plugs in behind the [`TlsCertSource`] seam, the §4
10//! boundary pattern: the OPEN tier ships [`FileCertSource`]; an enterprise crate provides
11//! an at-scale impl of the SAME trait.
12//!
13//! ALPN advertises `h2` + `http/1.1` (config-driven) so an h2-capable client (e.g.
14//! gRPC-over-TLS, a later phase) negotiates HTTP/2 while an h1-only client falls back
15//! cleanly — both then flow through the SAME protocol-neutral `handle()`.
16//!
17//! **No silent downgrade**: when TLS is enabled the listener serves ONLY TLS. A required
18//! cert that cannot be loaded is a fatal boot error (`acceptor_from_config` returns `Err`,
19//! the proxy refuses to bind) — never a fallback to cleartext on the same port.
20
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23
24use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer};
25use tokio_rustls::rustls::server::danger::ClientCertVerifier;
26use tokio_rustls::rustls::server::ResolvesServerCert;
27use tokio_rustls::rustls::ServerConfig;
28use tokio_rustls::TlsAcceptor;
29
30use waf_core::TlsConfig;
31
32/// Server certificate material: a leaf-first chain + its private key, as rustls DER types.
33pub struct TlsMaterial {
34    pub cert_chain: Vec<CertificateDer<'static>>,
35    pub private_key: PrivateKeyDer<'static>,
36}
37
38/// Source of the server's TLS certificate material — the §4 boundary seam. [`FileCertSource`]
39/// is the OPEN implementation; ACME/rotation/managed-PKI are enterprise implementations of
40/// this same trait (the core depends only on the trait, never on the at-scale impl).
41///
42/// `load()` is the single-cert path (the OPEN baseline). The two *defaulted* hooks below are
43/// additive extension points (compatible with the BOUNDARY §5 freeze, like
44/// `WafModule::structural()`): an enterprise source overrides them to take over server-cert
45/// resolution (hitless ACME rotation) or to require client certificates (mTLS / managed PKI),
46/// while every existing impl keeps `load()` + no client auth unchanged.
47pub trait TlsCertSource: Send + Sync {
48    /// Load a single server certificate chain + key. Used unless [`Self::resolver`]
49    /// returns `Some` (in which case the core never calls this).
50    fn load(&self) -> Result<TlsMaterial, TlsError>;
51
52    /// Optional dynamic server-cert resolver. When `Some`, the core builds the
53    /// `ServerConfig` with this resolver INSTEAD of `load()` (so the cert can rotate
54    /// at runtime without rebuilding the acceptor — enterprise hitless ACME), and
55    /// advertises the `acme-tls/1` ALPN so an on-listener TLS-ALPN-01 challenge can
56    /// negotiate on the same port. Default `None` → the OPEN single-cert path.
57    fn resolver(&self) -> Option<Arc<dyn ResolvesServerCert>> {
58        None
59    }
60
61    /// Optional client-certificate verifier. When `Some`, the listener requires and
62    /// verifies client certificates (mTLS / managed PKI). Default `None` → no client
63    /// auth, exactly as before.
64    fn client_verifier(&self) -> Option<Arc<dyn ClientCertVerifier>> {
65        None
66    }
67}
68
69/// Why building the TLS terminator failed. All variants are fatal at boot (a required TLS
70/// that cannot be built must stop the proxy, never degrade to cleartext).
71#[derive(Debug)]
72pub enum TlsError {
73    Io { path: PathBuf, source: std::io::Error },
74    NoCertificates(PathBuf),
75    NoPrivateKey(PathBuf),
76    Rustls(tokio_rustls::rustls::Error),
77}
78
79impl std::fmt::Display for TlsError {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        match self {
82            Self::Io { path, source } =>
83                write!(f, "cannot read TLS file {}: {source}", path.display()),
84            Self::NoCertificates(p) =>
85                write!(f, "no PEM certificates found in {}", p.display()),
86            Self::NoPrivateKey(p) =>
87                write!(f, "no PEM private key found in {}", p.display()),
88            Self::Rustls(e) => write!(f, "TLS configuration error: {e}"),
89        }
90    }
91}
92
93impl std::error::Error for TlsError {}
94
95/// OPEN cert source: read a PEM certificate chain + private key from two files.
96pub struct FileCertSource {
97    cert_path: PathBuf,
98    key_path: PathBuf,
99}
100
101impl FileCertSource {
102    pub fn new(cert_path: impl Into<PathBuf>, key_path: impl Into<PathBuf>) -> Self {
103        Self { cert_path: cert_path.into(), key_path: key_path.into() }
104    }
105}
106
107impl TlsCertSource for FileCertSource {
108    fn load(&self) -> Result<TlsMaterial, TlsError> {
109        Ok(TlsMaterial {
110            cert_chain: load_certs(&self.cert_path)?,
111            private_key: load_key(&self.key_path)?,
112        })
113    }
114}
115
116fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>, TlsError> {
117    let data = std::fs::read(path).map_err(|source| TlsError::Io { path: path.to_path_buf(), source })?;
118    let mut reader: &[u8] = &data;
119    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut reader)
120        .collect::<Result<_, _>>()
121        .map_err(|source| TlsError::Io { path: path.to_path_buf(), source })?;
122    if certs.is_empty() {
123        return Err(TlsError::NoCertificates(path.to_path_buf()));
124    }
125    Ok(certs)
126}
127
128fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>, TlsError> {
129    let data = std::fs::read(path).map_err(|source| TlsError::Io { path: path.to_path_buf(), source })?;
130    let mut reader: &[u8] = &data;
131    rustls_pemfile::private_key(&mut reader)
132        .map_err(|source| TlsError::Io { path: path.to_path_buf(), source })?
133        .ok_or_else(|| TlsError::NoPrivateKey(path.to_path_buf()))
134}
135
136/// Build a rustls [`ServerConfig`] from a cert source + ALPN list. Uses the `ring` crypto
137/// provider explicitly (no process-global `install_default`, so multiple configs — e.g. in
138/// tests — never race over the default).
139pub fn build_server_config(source: &dyn TlsCertSource, alpn: &[String]) -> Result<ServerConfig, TlsError> {
140    let provider = Arc::new(tokio_rustls::rustls::crypto::ring::default_provider());
141    let builder = ServerConfig::builder_with_provider(provider)
142        .with_safe_default_protocol_versions()
143        .map_err(TlsError::Rustls)?;
144
145    // Client auth: an injected verifier (enterprise mTLS / managed PKI) or none (OPEN).
146    let builder = match source.client_verifier() {
147        Some(verifier) => builder.with_client_cert_verifier(verifier),
148        None => builder.with_no_client_auth(),
149    };
150
151    // Server cert: a dynamic resolver (enterprise hitless rotation / ACME) takes over and
152    // bypasses load(); otherwise the single cert from load() (the OPEN FileCertSource path,
153    // byte-identical to before).
154    let mut cfg = match source.resolver() {
155        Some(resolver) => builder.with_cert_resolver(resolver),
156        None => {
157            let material = source.load()?;
158            builder
159                .with_single_cert(material.cert_chain, material.private_key)
160                .map_err(TlsError::Rustls)?
161        }
162    };
163
164    cfg.alpn_protocols = alpn.iter().map(|p| p.as_bytes().to_vec()).collect();
165    // TLS-ALPN-01: when a resolver drives ACME on this same listener, the challenge is
166    // negotiated via the `acme-tls/1` ALPN — advertise it so the validation handshake can
167    // select it (the resolver serves the challenge cert for it). Only when a resolver is set,
168    // so the normal (None) path keeps exactly the configured ALPN list.
169    if source.resolver().is_some() {
170        cfg.alpn_protocols.push(b"acme-tls/1".to_vec());
171    }
172    Ok(cfg)
173}
174
175/// Build the [`TlsAcceptor`] with an **injected** cert source, or `Ok(None)` when TLS is
176/// off. `tls.enabled` (operator switch) and `tls.alpn` still come from config; the source
177/// only governs cert *provenance* — when `Some`, the file paths in config are ignored, so
178/// an enterprise ACME/managed-PKI source needs no `cert_path`/`key_path`. `None` falls back
179/// to the OPEN [`FileCertSource`]. An enabled-but-unbuildable terminator is `Err` → the
180/// proxy fails to bind (fatal boot, no silent cleartext fallback).
181pub fn acceptor_from_source(
182    tls: &TlsConfig,
183    source: Option<Arc<dyn TlsCertSource>>,
184) -> Result<Option<TlsAcceptor>, TlsError> {
185    if !tls.enabled {
186        return Ok(None);
187    }
188    let cfg = match source {
189        Some(s) => build_server_config(s.as_ref(), &tls.alpn)?,
190        None => build_server_config(&FileCertSource::new(&tls.cert_path, &tls.key_path), &tls.alpn)?,
191    };
192    Ok(Some(TlsAcceptor::from(Arc::new(cfg))))
193}
194
195/// Build the [`TlsAcceptor`] from config with the default OPEN [`FileCertSource`]. Thin
196/// wrapper over [`acceptor_from_source`] with no injected source.
197pub fn acceptor_from_config(tls: &TlsConfig) -> Result<Option<TlsAcceptor>, TlsError> {
198    acceptor_from_source(tls, None)
199}