Skip to main content

rustls_letsencrypt/
config.rs

1use std::{net::{IpAddr, SocketAddr}, path::PathBuf, sync::Arc};
2
3use serde::{Deserialize, Serialize};
4use url::Url;
5
6use crate::{DnsName, Error, Event, Result, store::CertStore};
7
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub enum HostPattern {
10    Exact(DnsName),
11    SingleLabelWildcard(DnsName),
12    /// A complete hostname pattern where each `*` matches exactly one label.
13    LabelPattern(Vec<String>),
14}
15
16impl HostPattern {
17    pub fn exact(value: impl AsRef<str>) -> Result<Self> {
18        Ok(Self::Exact(DnsName::parse(value)?))
19    }
20
21    pub fn single_label_wildcard(value: impl AsRef<str>) -> Result<Self> {
22        let value = value.as_ref();
23        let suffix = value
24            .strip_prefix("*.")
25            .ok_or_else(|| Error::InvalidConfig(format!("wildcard must start with '*.' ({value})")))?;
26        Ok(Self::SingleLabelWildcard(DnsName::parse(suffix)?))
27    }
28
29    #[must_use]
30    pub fn matches(&self, name: &DnsName) -> bool {
31        match self {
32            Self::Exact(exact) => exact == name,
33            Self::SingleLabelWildcard(suffix) => {
34                name.as_str()
35                    .strip_suffix(suffix.as_str())
36                    .and_then(|prefix| prefix.strip_suffix('.'))
37                    .is_some_and(|label| !label.is_empty() && !label.contains('.'))
38            }
39            Self::LabelPattern(pattern) => {
40                let labels: Vec<_> = name.as_str().split('.').collect();
41                labels.len() == pattern.len() && pattern.iter().zip(labels).all(|(expected, actual)| wildcard_label_matches(expected, actual))
42            }
43        }
44    }
45}
46
47impl std::str::FromStr for HostPattern {
48    type Err = Error;
49    fn from_str(s: &str) -> Result<Self> {
50        if !s.contains('*') { return Self::exact(s); }
51        let raw = s.trim_end_matches('.');
52        let mut pattern = Vec::new();
53        for label in raw.split('.') {
54            if label.is_empty() { return Err(Error::InvalidConfig(format!("empty host-pattern label ({s})"))); }
55            if label.contains('*') {
56                let candidate = label.replace('*', "a");
57                let _ = DnsName::parse(candidate)?;
58                // Keep the glob markers while normalizing literal ASCII case.
59                let mut normalized_pattern = String::with_capacity(label.len());
60                for character in label.chars() { normalized_pattern.push(if character == '*' { '*' } else { character.to_ascii_lowercase() }); }
61                pattern.push(normalized_pattern);
62            } else { pattern.push(DnsName::parse(label)?.as_str().to_owned()); }
63        }
64        Ok(Self::LabelPattern(pattern))
65    }
66}
67
68fn wildcard_label_matches(pattern: &str, value: &str) -> bool {
69    let pattern: Vec<_> = pattern.chars().collect();
70    let value: Vec<_> = value.chars().collect();
71    let mut matched = vec![vec![false; value.len() + 1]; pattern.len() + 1];
72    matched[0][0] = true;
73    for (index, character) in pattern.iter().enumerate() {
74        for offset in 0..=value.len() {
75            if !matched[index][offset] { continue; }
76            if *character == '*' {
77                matched[index + 1][offset] = true;
78                if offset < value.len() { matched[index][offset + 1] = true; }
79            } else if offset < value.len() && *character == value[offset] {
80                matched[index + 1][offset + 1] = true;
81            }
82        }
83    }
84    matched[pattern.len()][value.len()]
85}
86
87#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
88#[serde(rename_all = "lowercase")]
89pub enum EventOutput {
90    Subscribe,
91    #[default]
92    Stderr,
93    Stdout,
94}
95
96/// Transport policy for an explicitly configured DNS resolver.
97#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
98#[serde(rename_all = "snake_case")]
99pub enum DnsTransport {
100    Udp,
101    Tcp,
102    /// Query over UDP and retry/fail over using TCP (the default for a bare address).
103    UdpThenTcp,
104}
105
106/// An explicit DNS resolver and the transport used to reach it.
107#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
108pub struct DnsServer {
109    pub transport: DnsTransport,
110    pub address: SocketAddr,
111}
112
113impl DnsServer {
114    #[must_use] pub const fn udp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Udp, address } }
115    #[must_use] pub const fn tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Tcp, address } }
116    #[must_use] pub const fn udp_then_tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::UdpThenTcp, address } }
117}
118
119impl std::str::FromStr for DnsServer {
120    type Err = Error;
121
122    fn from_str(value: &str) -> Result<Self> {
123        let (transport, address) = if let Some(address) = value.strip_prefix("udp://") {
124            (DnsTransport::Udp, address)
125        } else if let Some(address) = value.strip_prefix("tcp://") {
126            (DnsTransport::Tcp, address)
127        } else if value.contains("://") {
128            return Err(Error::InvalidConfig(format!("unsupported DNS server transport: {value}")));
129        } else {
130            (DnsTransport::UdpThenTcp, value)
131        };
132        let address = address.parse().map_err(|_| Error::InvalidConfig(format!("invalid DNS server address: {value}")))?;
133        Ok(Self { transport, address })
134    }
135}
136
137impl std::fmt::Display for DnsServer {
138    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        match self.transport {
140            DnsTransport::Udp => write!(formatter, "udp://{}", self.address),
141            DnsTransport::Tcp => write!(formatter, "tcp://{}", self.address),
142            DnsTransport::UdpThenTcp => write!(formatter, "{}", self.address),
143        }
144    }
145}
146
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub enum LetsEncryptAcmeProfile { Production, Staging }
149
150impl LetsEncryptAcmeProfile {
151    #[must_use]
152    pub fn directory_url(self) -> &'static str {
153        match self {
154            Self::Production => "https://acme-v02.api.letsencrypt.org/directory",
155            Self::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
156        }
157    }
158}
159
160#[derive(Clone, Debug)]
161pub struct ManagedPebbleConfig {
162    pub pebble_bind: std::net::SocketAddr,
163    pub pebble_executable: Option<PathBuf>,
164    pub working_directory: Option<PathBuf>,
165    pub state_directory: Option<PathBuf>,
166}
167
168impl Default for ManagedPebbleConfig {
169    fn default() -> Self {
170        Self { pebble_bind: "127.0.0.1:14000".parse().expect("literal"), pebble_executable: None, working_directory: None, state_directory: None }
171    }
172}
173
174#[derive(Clone, Debug)]
175pub enum AcmeEndpoint {
176    /// Disable public ACME and issue only through the persisted `AcmeLocalCA`.
177    LocalOnly,
178    LetsEncrypt(LetsEncryptAcmeProfile),
179    Pebble(ManagedPebbleConfig),
180    Custom { directory_url: Url, issuer_id: String, tls_trust_roots: Vec<Vec<u8>> },
181}
182
183impl Default for AcmeEndpoint {
184    fn default() -> Self { Self::LetsEncrypt(LetsEncryptAcmeProfile::Staging) }
185}
186
187pub type EventHandler = Arc<dyn Fn(&Event) + Send + Sync + 'static>;
188
189#[derive(Clone)]
190pub struct AlpnHandlerConfig {
191    pub allowed_hosts: Vec<HostPattern>,
192    pub public_ip_addresses: Vec<IpAddr>,
193    pub verify_dns_before_issuance: bool,
194    pub dns_servers: Option<Vec<DnsServer>>,
195    pub cert_store_directory: PathBuf,
196    pub cert_store: Option<Arc<dyn CertStore>>,
197    pub acme_endpoint: AcmeEndpoint,
198    pub acme_contacts: Vec<String>,
199    pub renew_days_before_expiry: u32,
200    pub renew_check_interval_secs: u64,
201    pub renew_check_max_interval_secs: u64,
202    pub client_hello_timeout_secs: u64,
203    pub issuance_attempt_timeout_secs: u64,
204    pub initial_connection_wait_timeout_secs: u64,
205    pub dns_lookup_timeout_secs: u64,
206    pub pebble_startup_timeout_secs: u64,
207    pub local_fallback_enabled: bool,
208    pub local_leaf_validity_days: u32,
209    pub events: EventOutput,
210    pub event_handler: Option<EventHandler>,
211    pub event_channel_capacity: usize,
212    pub event_history_capacity: usize,
213    pub allow_non_443_listener: bool,
214    pub application_alpn_protocols: Vec<Vec<u8>>,
215}
216
217impl std::fmt::Debug for AlpnHandlerConfig {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        f.debug_struct("AlpnHandlerConfig")
220            .field("allowed_hosts", &self.allowed_hosts)
221            .field("public_ip_addresses", &self.public_ip_addresses)
222            .field("cert_store_directory", &self.cert_store_directory)
223            .field("acme_endpoint", &self.acme_endpoint)
224            .finish_non_exhaustive()
225    }
226}
227
228impl Default for AlpnHandlerConfig {
229    fn default() -> Self {
230        Self {
231            allowed_hosts: Vec::new(), public_ip_addresses: Vec::new(),
232            verify_dns_before_issuance: true, dns_servers: None,
233            cert_store_directory: PathBuf::from("certificates"), cert_store: None,
234            acme_endpoint: AcmeEndpoint::default(), acme_contacts: Vec::new(),
235            renew_days_before_expiry: 15, renew_check_interval_secs: 3600,
236            renew_check_max_interval_secs: 43_200, client_hello_timeout_secs: 5,
237            issuance_attempt_timeout_secs: 60, initial_connection_wait_timeout_secs: 60,
238            dns_lookup_timeout_secs: 5, pebble_startup_timeout_secs: 30,
239            local_fallback_enabled: true,
240            local_leaf_validity_days: 30, events: EventOutput::Stderr, event_handler: None,
241            event_channel_capacity: 1024, event_history_capacity: 256,
242            allow_non_443_listener: false, application_alpn_protocols: Vec::new(),
243        }
244    }
245}
246
247impl AlpnHandlerConfig {
248    /// Create a configuration for the common single-host case.
249    ///
250    /// Advanced users can replace `allowed_hosts` with exact and wildcard
251    /// [`HostPattern`] values after construction.
252    pub fn for_host(host: impl AsRef<str>) -> Result<Self> {
253        Self::for_hosts([host])
254    }
255
256    /// Create a configuration for one or more exact or `*.` single-label hosts.
257    pub fn for_hosts<I, S>(hosts: I) -> Result<Self>
258    where
259        I: IntoIterator<Item = S>,
260        S: AsRef<str>,
261    {
262        let mut config = Self::default();
263        config.allowed_hosts = hosts.into_iter().map(|host| host.as_ref().parse()).collect::<Result<_>>()?;
264        if config.allowed_hosts.is_empty() {
265            return Err(Error::InvalidConfig("at least one managed host is required".into()));
266        }
267        Ok(config)
268    }
269
270    #[must_use]
271    pub fn builder() -> AlpnHandlerConfigBuilder { AlpnHandlerConfigBuilder(Self::default()) }
272
273    pub(crate) fn validate(&self) -> Result<()> {
274        for (name, value) in [
275            ("renew_check_interval_secs", self.renew_check_interval_secs),
276            ("renew_check_max_interval_secs", self.renew_check_max_interval_secs),
277            ("client_hello_timeout_secs", self.client_hello_timeout_secs),
278            ("issuance_attempt_timeout_secs", self.issuance_attempt_timeout_secs),
279            ("initial_connection_wait_timeout_secs", self.initial_connection_wait_timeout_secs),
280            ("dns_lookup_timeout_secs", self.dns_lookup_timeout_secs),
281        ] { if value == 0 { return Err(Error::InvalidConfig(format!("{name} must be positive"))); } }
282        if self.renew_check_max_interval_secs < self.renew_check_interval_secs {
283            return Err(Error::InvalidConfig("renew_check_max_interval_secs must be >= renew_check_interval_secs".into()));
284        }
285        if self.verify_dns_before_issuance && self.public_ip_addresses.is_empty() && !matches!(self.acme_endpoint, AcmeEndpoint::Pebble(_) | AcmeEndpoint::LocalOnly) {
286            return Err(Error::InvalidConfig("public_ip_addresses is required when DNS verification is enabled".into()));
287        }
288        if self.dns_servers.as_ref().is_some_and(Vec::is_empty) {
289            return Err(Error::InvalidConfig("dns_servers cannot be an empty list; use None".into()));
290        }
291        if matches!(self.acme_endpoint, AcmeEndpoint::LocalOnly) && !self.local_fallback_enabled {
292            return Err(Error::InvalidConfig("AcmeEndpoint::LocalOnly requires local_fallback_enabled".into()));
293        }
294        Ok(())
295    }
296}
297
298pub struct AlpnHandlerConfigBuilder(AlpnHandlerConfig);
299impl AlpnHandlerConfigBuilder {
300    pub fn allowed_hosts(mut self, hosts: impl IntoIterator<Item = impl AsRef<str>>) -> Result<Self> { self.0.allowed_hosts = hosts.into_iter().map(|h| h.as_ref().parse()).collect::<Result<_>>()?; Ok(self) }
301    #[must_use] pub fn cert_store(mut self, store: Arc<dyn CertStore>) -> Self { self.0.cert_store = Some(store); self }
302    #[must_use] pub fn event_handler(mut self, handler: EventHandler) -> Self { self.0.event_handler = Some(handler); self }
303    pub fn build(self) -> Result<AlpnHandlerConfig> { self.0.validate()?; Ok(self.0) }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    #[test]
310    fn wildcard_matches_one_label_only() {
311        let pattern = HostPattern::single_label_wildcard("*.example.com").unwrap();
312        assert!(pattern.matches(&DnsName::parse("a.example.com").unwrap()));
313        assert!(!pattern.matches(&DnsName::parse("example.com").unwrap()));
314        assert!(!pattern.matches(&DnsName::parse("a.b.example.com").unwrap()));
315        assert!(!pattern.matches(&DnsName::parse("badexample.com").unwrap()));
316    }
317
318    #[test]
319    fn dns_server_parses_transport_and_ipv6() {
320        let udp: DnsServer = "udp://127.0.0.1:53".parse().unwrap();
321        assert_eq!(udp.transport, DnsTransport::Udp);
322        let tcp: DnsServer = "tcp://[2001:4860:4860::8888]:1053".parse().unwrap();
323        assert_eq!(tcp.transport, DnsTransport::Tcp);
324        assert_eq!(tcp.address.port(), 1053);
325        let automatic: DnsServer = "1.1.1.1:53".parse().unwrap();
326        assert_eq!(automatic.transport, DnsTransport::UdpThenTcp);
327        assert!("https://1.1.1.1:443".parse::<DnsServer>().is_err());
328    }
329
330    #[test]
331    fn for_host_detects_single_label_wildcard() {
332        let config = AlpnHandlerConfig::for_host("*.example.com").unwrap();
333        assert!(config.allowed_hosts[0].matches(&DnsName::parse("api.example.com").unwrap()));
334        assert!(!config.allowed_hosts[0].matches(&DnsName::parse("api.v2.example.com").unwrap()));
335        let one_label = AlpnHandlerConfig::for_host("*").unwrap();
336        assert!(one_label.allowed_hosts[0].matches(&DnsName::parse("localhost").unwrap()));
337        assert!(!one_label.allowed_hosts[0].matches(&DnsName::parse("api.example.com").unwrap()));
338        let middle = AlpnHandlerConfig::for_host("api.*.example.com").unwrap();
339        assert!(middle.allowed_hosts[0].matches(&DnsName::parse("api.v2.example.com").unwrap()));
340        assert!(AlpnHandlerConfig::for_host("*.bad_$.com").is_err());
341        let broad = AlpnHandlerConfig::for_host("*.*.*").unwrap();
342        assert!(broad.allowed_hosts[0].matches(&DnsName::parse("a.b.c").unwrap()));
343        assert!(!broad.allowed_hosts[0].matches(&DnsName::parse("a.b.c.d").unwrap()));
344        let partial = AlpnHandlerConfig::for_host("*help.wushilin.net").unwrap();
345        assert!(partial.allowed_hosts[0].matches(&DnsName::parse("myhelp.wushilin.net").unwrap()));
346        assert!(!partial.allowed_hosts[0].matches(&DnsName::parse("myhelp.other.net").unwrap()));
347        let many = AlpnHandlerConfig::for_hosts(["api.example.com", "*.internal.example"]).unwrap();
348        assert_eq!(many.allowed_hosts.len(), 2);
349        assert!(AlpnHandlerConfig::for_hosts(std::iter::empty::<&str>()).is_err());
350    }
351}