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}
13
14impl HostPattern {
15 pub fn exact(value: impl AsRef<str>) -> Result<Self> {
16 Ok(Self::Exact(DnsName::parse(value)?))
17 }
18
19 pub fn single_label_wildcard(value: impl AsRef<str>) -> Result<Self> {
20 let value = value.as_ref();
21 let suffix = value
22 .strip_prefix("*.")
23 .ok_or_else(|| Error::InvalidConfig(format!("wildcard must start with '*.' ({value})")))?;
24 Ok(Self::SingleLabelWildcard(DnsName::parse(suffix)?))
25 }
26
27 #[must_use]
28 pub fn matches(&self, name: &DnsName) -> bool {
29 match self {
30 Self::Exact(exact) => exact == name,
31 Self::SingleLabelWildcard(suffix) => {
32 name.as_str()
33 .strip_suffix(suffix.as_str())
34 .and_then(|prefix| prefix.strip_suffix('.'))
35 .is_some_and(|label| !label.is_empty() && !label.contains('.'))
36 }
37 }
38 }
39}
40
41impl std::str::FromStr for HostPattern {
42 type Err = Error;
43 fn from_str(s: &str) -> Result<Self> {
44 if s.starts_with("*.") { Self::single_label_wildcard(s) } else { Self::exact(s) }
45 }
46}
47
48#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
49#[serde(rename_all = "lowercase")]
50pub enum EventOutput {
51 Subscribe,
52 #[default]
53 Stderr,
54 Stdout,
55}
56
57#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
59#[serde(rename_all = "snake_case")]
60pub enum DnsTransport {
61 Udp,
62 Tcp,
63 UdpThenTcp,
65}
66
67#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
69pub struct DnsServer {
70 pub transport: DnsTransport,
71 pub address: SocketAddr,
72}
73
74impl DnsServer {
75 #[must_use] pub const fn udp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Udp, address } }
76 #[must_use] pub const fn tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Tcp, address } }
77 #[must_use] pub const fn udp_then_tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::UdpThenTcp, address } }
78}
79
80impl std::str::FromStr for DnsServer {
81 type Err = Error;
82
83 fn from_str(value: &str) -> Result<Self> {
84 let (transport, address) = if let Some(address) = value.strip_prefix("udp://") {
85 (DnsTransport::Udp, address)
86 } else if let Some(address) = value.strip_prefix("tcp://") {
87 (DnsTransport::Tcp, address)
88 } else if value.contains("://") {
89 return Err(Error::InvalidConfig(format!("unsupported DNS server transport: {value}")));
90 } else {
91 (DnsTransport::UdpThenTcp, value)
92 };
93 let address = address.parse().map_err(|_| Error::InvalidConfig(format!("invalid DNS server address: {value}")))?;
94 Ok(Self { transport, address })
95 }
96}
97
98impl std::fmt::Display for DnsServer {
99 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 match self.transport {
101 DnsTransport::Udp => write!(formatter, "udp://{}", self.address),
102 DnsTransport::Tcp => write!(formatter, "tcp://{}", self.address),
103 DnsTransport::UdpThenTcp => write!(formatter, "{}", self.address),
104 }
105 }
106}
107
108#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109pub enum LetsEncryptAcmeProfile { Production, Staging }
110
111impl LetsEncryptAcmeProfile {
112 #[must_use]
113 pub fn directory_url(self) -> &'static str {
114 match self {
115 Self::Production => "https://acme-v02.api.letsencrypt.org/directory",
116 Self::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
117 }
118 }
119}
120
121#[derive(Clone, Debug)]
122pub struct ManagedPebbleConfig {
123 pub pebble_bind: std::net::SocketAddr,
124 pub pebble_executable: Option<PathBuf>,
125 pub working_directory: Option<PathBuf>,
126 pub state_directory: Option<PathBuf>,
127}
128
129impl Default for ManagedPebbleConfig {
130 fn default() -> Self {
131 Self { pebble_bind: "127.0.0.1:14000".parse().expect("literal"), pebble_executable: None, working_directory: None, state_directory: None }
132 }
133}
134
135#[derive(Clone, Debug)]
136pub enum AcmeEndpoint {
137 LocalOnly,
139 LetsEncrypt(LetsEncryptAcmeProfile),
140 Pebble(ManagedPebbleConfig),
141 Custom { directory_url: Url, issuer_id: String, tls_trust_roots: Vec<Vec<u8>> },
142}
143
144impl Default for AcmeEndpoint {
145 fn default() -> Self { Self::LetsEncrypt(LetsEncryptAcmeProfile::Staging) }
146}
147
148pub type EventHandler = Arc<dyn Fn(&Event) + Send + Sync + 'static>;
149
150#[derive(Clone)]
151pub struct AlpnHandlerConfig {
152 pub allowed_hosts: Vec<HostPattern>,
153 pub public_ip_addresses: Vec<IpAddr>,
154 pub verify_dns_before_issuance: bool,
155 pub dns_servers: Option<Vec<DnsServer>>,
156 pub cert_store_directory: PathBuf,
157 pub cert_store: Option<Arc<dyn CertStore>>,
158 pub acme_endpoint: AcmeEndpoint,
159 pub acme_contacts: Vec<String>,
160 pub renew_days_before_expiry: u32,
161 pub renew_check_interval_secs: u64,
162 pub renew_check_max_interval_secs: u64,
163 pub client_hello_timeout_secs: u64,
164 pub issuance_attempt_timeout_secs: u64,
165 pub initial_connection_wait_timeout_secs: u64,
166 pub dns_lookup_timeout_secs: u64,
167 pub pebble_startup_timeout_secs: u64,
168 pub local_fallback_enabled: bool,
169 pub local_leaf_validity_days: u32,
170 pub events: EventOutput,
171 pub event_handler: Option<EventHandler>,
172 pub event_channel_capacity: usize,
173 pub event_history_capacity: usize,
174 pub allow_non_443_listener: bool,
175 pub application_alpn_protocols: Vec<Vec<u8>>,
176}
177
178impl std::fmt::Debug for AlpnHandlerConfig {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 f.debug_struct("AlpnHandlerConfig")
181 .field("allowed_hosts", &self.allowed_hosts)
182 .field("public_ip_addresses", &self.public_ip_addresses)
183 .field("cert_store_directory", &self.cert_store_directory)
184 .field("acme_endpoint", &self.acme_endpoint)
185 .finish_non_exhaustive()
186 }
187}
188
189impl Default for AlpnHandlerConfig {
190 fn default() -> Self {
191 Self {
192 allowed_hosts: Vec::new(), public_ip_addresses: Vec::new(),
193 verify_dns_before_issuance: true, dns_servers: None,
194 cert_store_directory: PathBuf::from("certificates"), cert_store: None,
195 acme_endpoint: AcmeEndpoint::default(), acme_contacts: Vec::new(),
196 renew_days_before_expiry: 15, renew_check_interval_secs: 3600,
197 renew_check_max_interval_secs: 43_200, client_hello_timeout_secs: 5,
198 issuance_attempt_timeout_secs: 60, initial_connection_wait_timeout_secs: 60,
199 dns_lookup_timeout_secs: 5, pebble_startup_timeout_secs: 30,
200 local_fallback_enabled: true,
201 local_leaf_validity_days: 30, events: EventOutput::Stderr, event_handler: None,
202 event_channel_capacity: 1024, event_history_capacity: 256,
203 allow_non_443_listener: false, application_alpn_protocols: Vec::new(),
204 }
205 }
206}
207
208impl AlpnHandlerConfig {
209 #[must_use]
210 pub fn builder() -> AlpnHandlerConfigBuilder { AlpnHandlerConfigBuilder(Self::default()) }
211
212 pub(crate) fn validate(&self) -> Result<()> {
213 for (name, value) in [
214 ("renew_check_interval_secs", self.renew_check_interval_secs),
215 ("renew_check_max_interval_secs", self.renew_check_max_interval_secs),
216 ("client_hello_timeout_secs", self.client_hello_timeout_secs),
217 ("issuance_attempt_timeout_secs", self.issuance_attempt_timeout_secs),
218 ("initial_connection_wait_timeout_secs", self.initial_connection_wait_timeout_secs),
219 ("dns_lookup_timeout_secs", self.dns_lookup_timeout_secs),
220 ] { if value == 0 { return Err(Error::InvalidConfig(format!("{name} must be positive"))); } }
221 if self.renew_check_max_interval_secs < self.renew_check_interval_secs {
222 return Err(Error::InvalidConfig("renew_check_max_interval_secs must be >= renew_check_interval_secs".into()));
223 }
224 if self.verify_dns_before_issuance && self.public_ip_addresses.is_empty() && !matches!(self.acme_endpoint, AcmeEndpoint::Pebble(_) | AcmeEndpoint::LocalOnly) {
225 return Err(Error::InvalidConfig("public_ip_addresses is required when DNS verification is enabled".into()));
226 }
227 if self.dns_servers.as_ref().is_some_and(Vec::is_empty) {
228 return Err(Error::InvalidConfig("dns_servers cannot be an empty list; use None".into()));
229 }
230 if matches!(self.acme_endpoint, AcmeEndpoint::LocalOnly) && !self.local_fallback_enabled {
231 return Err(Error::InvalidConfig("AcmeEndpoint::LocalOnly requires local_fallback_enabled".into()));
232 }
233 Ok(())
234 }
235}
236
237pub struct AlpnHandlerConfigBuilder(AlpnHandlerConfig);
238impl AlpnHandlerConfigBuilder {
239 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) }
240 #[must_use] pub fn cert_store(mut self, store: Arc<dyn CertStore>) -> Self { self.0.cert_store = Some(store); self }
241 #[must_use] pub fn event_handler(mut self, handler: EventHandler) -> Self { self.0.event_handler = Some(handler); self }
242 pub fn build(self) -> Result<AlpnHandlerConfig> { self.0.validate()?; Ok(self.0) }
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248 #[test]
249 fn wildcard_matches_one_label_only() {
250 let pattern = HostPattern::single_label_wildcard("*.example.com").unwrap();
251 assert!(pattern.matches(&DnsName::parse("a.example.com").unwrap()));
252 assert!(!pattern.matches(&DnsName::parse("example.com").unwrap()));
253 assert!(!pattern.matches(&DnsName::parse("a.b.example.com").unwrap()));
254 assert!(!pattern.matches(&DnsName::parse("badexample.com").unwrap()));
255 }
256
257 #[test]
258 fn dns_server_parses_transport_and_ipv6() {
259 let udp: DnsServer = "udp://127.0.0.1:53".parse().unwrap();
260 assert_eq!(udp.transport, DnsTransport::Udp);
261 let tcp: DnsServer = "tcp://[2001:4860:4860::8888]:1053".parse().unwrap();
262 assert_eq!(tcp.transport, DnsTransport::Tcp);
263 assert_eq!(tcp.address.port(), 1053);
264 let automatic: DnsServer = "1.1.1.1:53".parse().unwrap();
265 assert_eq!(automatic.transport, DnsTransport::UdpThenTcp);
266 assert!("https://1.1.1.1:443".parse::<DnsServer>().is_err());
267 }
268}