use std::{net::{IpAddr, SocketAddr}, path::PathBuf, sync::Arc};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{DnsName, Error, Event, Result, store::CertStore};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HostPattern {
Exact(DnsName),
SingleLabelWildcard(DnsName),
LabelPattern(Vec<String>),
}
impl HostPattern {
pub fn exact(value: impl AsRef<str>) -> Result<Self> {
Ok(Self::Exact(DnsName::parse(value)?))
}
pub fn single_label_wildcard(value: impl AsRef<str>) -> Result<Self> {
let value = value.as_ref();
let suffix = value
.strip_prefix("*.")
.ok_or_else(|| Error::InvalidConfig(format!("wildcard must start with '*.' ({value})")))?;
Ok(Self::SingleLabelWildcard(DnsName::parse(suffix)?))
}
#[must_use]
pub fn matches(&self, name: &DnsName) -> bool {
match self {
Self::Exact(exact) => exact == name,
Self::SingleLabelWildcard(suffix) => {
name.as_str()
.strip_suffix(suffix.as_str())
.and_then(|prefix| prefix.strip_suffix('.'))
.is_some_and(|label| !label.is_empty() && !label.contains('.'))
}
Self::LabelPattern(pattern) => {
let labels: Vec<_> = name.as_str().split('.').collect();
labels.len() == pattern.len() && pattern.iter().zip(labels).all(|(expected, actual)| wildcard_label_matches(expected, actual))
}
}
}
}
impl std::str::FromStr for HostPattern {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
if !s.contains('*') { return Self::exact(s); }
let raw = s.trim_end_matches('.');
let mut pattern = Vec::new();
for label in raw.split('.') {
if label.is_empty() { return Err(Error::InvalidConfig(format!("empty host-pattern label ({s})"))); }
if label.contains('*') {
let candidate = label.replace('*', "a");
let _ = DnsName::parse(candidate)?;
let mut normalized_pattern = String::with_capacity(label.len());
for character in label.chars() { normalized_pattern.push(if character == '*' { '*' } else { character.to_ascii_lowercase() }); }
pattern.push(normalized_pattern);
} else { pattern.push(DnsName::parse(label)?.as_str().to_owned()); }
}
Ok(Self::LabelPattern(pattern))
}
}
fn wildcard_label_matches(pattern: &str, value: &str) -> bool {
let pattern: Vec<_> = pattern.chars().collect();
let value: Vec<_> = value.chars().collect();
let mut matched = vec![vec![false; value.len() + 1]; pattern.len() + 1];
matched[0][0] = true;
for (index, character) in pattern.iter().enumerate() {
for offset in 0..=value.len() {
if !matched[index][offset] { continue; }
if *character == '*' {
matched[index + 1][offset] = true;
if offset < value.len() { matched[index][offset + 1] = true; }
} else if offset < value.len() && *character == value[offset] {
matched[index + 1][offset + 1] = true;
}
}
}
matched[pattern.len()][value.len()]
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum EventOutput {
Subscribe,
#[default]
Stderr,
Stdout,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DnsTransport {
Udp,
Tcp,
UdpThenTcp,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DnsServer {
pub transport: DnsTransport,
pub address: SocketAddr,
}
impl DnsServer {
#[must_use] pub const fn udp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Udp, address } }
#[must_use] pub const fn tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::Tcp, address } }
#[must_use] pub const fn udp_then_tcp(address: SocketAddr) -> Self { Self { transport: DnsTransport::UdpThenTcp, address } }
}
impl std::str::FromStr for DnsServer {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
let (transport, address) = if let Some(address) = value.strip_prefix("udp://") {
(DnsTransport::Udp, address)
} else if let Some(address) = value.strip_prefix("tcp://") {
(DnsTransport::Tcp, address)
} else if value.contains("://") {
return Err(Error::InvalidConfig(format!("unsupported DNS server transport: {value}")));
} else {
(DnsTransport::UdpThenTcp, value)
};
let address = address.parse().map_err(|_| Error::InvalidConfig(format!("invalid DNS server address: {value}")))?;
Ok(Self { transport, address })
}
}
impl std::fmt::Display for DnsServer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.transport {
DnsTransport::Udp => write!(formatter, "udp://{}", self.address),
DnsTransport::Tcp => write!(formatter, "tcp://{}", self.address),
DnsTransport::UdpThenTcp => write!(formatter, "{}", self.address),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LetsEncryptAcmeProfile { Production, Staging }
impl LetsEncryptAcmeProfile {
#[must_use]
pub fn directory_url(self) -> &'static str {
match self {
Self::Production => "https://acme-v02.api.letsencrypt.org/directory",
Self::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
}
}
}
#[derive(Clone, Debug)]
pub struct ManagedPebbleConfig {
pub pebble_bind: std::net::SocketAddr,
pub pebble_executable: Option<PathBuf>,
pub working_directory: Option<PathBuf>,
pub state_directory: Option<PathBuf>,
}
impl Default for ManagedPebbleConfig {
fn default() -> Self {
Self { pebble_bind: "127.0.0.1:14000".parse().expect("literal"), pebble_executable: None, working_directory: None, state_directory: None }
}
}
#[derive(Clone, Debug)]
pub enum AcmeEndpoint {
LocalOnly,
LetsEncrypt(LetsEncryptAcmeProfile),
Pebble(ManagedPebbleConfig),
Custom { directory_url: Url, issuer_id: String, tls_trust_roots: Vec<Vec<u8>> },
}
impl Default for AcmeEndpoint {
fn default() -> Self { Self::LetsEncrypt(LetsEncryptAcmeProfile::Staging) }
}
pub type EventHandler = Arc<dyn Fn(&Event) + Send + Sync + 'static>;
#[derive(Clone)]
pub struct AlpnHandlerConfig {
pub allowed_hosts: Vec<HostPattern>,
pub public_ip_addresses: Vec<IpAddr>,
pub verify_dns_before_issuance: bool,
pub dns_servers: Option<Vec<DnsServer>>,
pub cert_store_directory: PathBuf,
pub cert_store: Option<Arc<dyn CertStore>>,
pub acme_endpoint: AcmeEndpoint,
pub acme_contacts: Vec<String>,
pub renew_days_before_expiry: u32,
pub renew_check_interval_secs: u64,
pub renew_check_max_interval_secs: u64,
pub client_hello_timeout_secs: u64,
pub issuance_attempt_timeout_secs: u64,
pub initial_connection_wait_timeout_secs: u64,
pub dns_lookup_timeout_secs: u64,
pub pebble_startup_timeout_secs: u64,
pub local_fallback_enabled: bool,
pub local_leaf_validity_days: u32,
pub events: EventOutput,
pub event_handler: Option<EventHandler>,
pub event_channel_capacity: usize,
pub event_history_capacity: usize,
pub allow_non_443_listener: bool,
pub application_alpn_protocols: Vec<Vec<u8>>,
}
impl std::fmt::Debug for AlpnHandlerConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AlpnHandlerConfig")
.field("allowed_hosts", &self.allowed_hosts)
.field("public_ip_addresses", &self.public_ip_addresses)
.field("cert_store_directory", &self.cert_store_directory)
.field("acme_endpoint", &self.acme_endpoint)
.finish_non_exhaustive()
}
}
impl Default for AlpnHandlerConfig {
fn default() -> Self {
Self {
allowed_hosts: Vec::new(), public_ip_addresses: Vec::new(),
verify_dns_before_issuance: true, dns_servers: None,
cert_store_directory: PathBuf::from("certificates"), cert_store: None,
acme_endpoint: AcmeEndpoint::default(), acme_contacts: Vec::new(),
renew_days_before_expiry: 15, renew_check_interval_secs: 3600,
renew_check_max_interval_secs: 43_200, client_hello_timeout_secs: 5,
issuance_attempt_timeout_secs: 60, initial_connection_wait_timeout_secs: 60,
dns_lookup_timeout_secs: 5, pebble_startup_timeout_secs: 30,
local_fallback_enabled: true,
local_leaf_validity_days: 30, events: EventOutput::Stderr, event_handler: None,
event_channel_capacity: 1024, event_history_capacity: 256,
allow_non_443_listener: false, application_alpn_protocols: Vec::new(),
}
}
}
impl AlpnHandlerConfig {
pub fn for_host(host: impl AsRef<str>) -> Result<Self> {
Self::for_hosts([host])
}
pub fn for_hosts<I, S>(hosts: I) -> Result<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut config = Self::default();
config.allowed_hosts = hosts.into_iter().map(|host| host.as_ref().parse()).collect::<Result<_>>()?;
if config.allowed_hosts.is_empty() {
return Err(Error::InvalidConfig("at least one managed host is required".into()));
}
Ok(config)
}
#[must_use]
pub fn builder() -> AlpnHandlerConfigBuilder { AlpnHandlerConfigBuilder(Self::default()) }
pub(crate) fn validate(&self) -> Result<()> {
for (name, value) in [
("renew_check_interval_secs", self.renew_check_interval_secs),
("renew_check_max_interval_secs", self.renew_check_max_interval_secs),
("client_hello_timeout_secs", self.client_hello_timeout_secs),
("issuance_attempt_timeout_secs", self.issuance_attempt_timeout_secs),
("initial_connection_wait_timeout_secs", self.initial_connection_wait_timeout_secs),
("dns_lookup_timeout_secs", self.dns_lookup_timeout_secs),
] { if value == 0 { return Err(Error::InvalidConfig(format!("{name} must be positive"))); } }
if self.renew_check_max_interval_secs < self.renew_check_interval_secs {
return Err(Error::InvalidConfig("renew_check_max_interval_secs must be >= renew_check_interval_secs".into()));
}
if self.verify_dns_before_issuance && self.public_ip_addresses.is_empty() && !matches!(self.acme_endpoint, AcmeEndpoint::Pebble(_) | AcmeEndpoint::LocalOnly) {
return Err(Error::InvalidConfig("public_ip_addresses is required when DNS verification is enabled".into()));
}
if self.dns_servers.as_ref().is_some_and(Vec::is_empty) {
return Err(Error::InvalidConfig("dns_servers cannot be an empty list; use None".into()));
}
if matches!(self.acme_endpoint, AcmeEndpoint::LocalOnly) && !self.local_fallback_enabled {
return Err(Error::InvalidConfig("AcmeEndpoint::LocalOnly requires local_fallback_enabled".into()));
}
Ok(())
}
}
pub struct AlpnHandlerConfigBuilder(AlpnHandlerConfig);
impl AlpnHandlerConfigBuilder {
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) }
#[must_use] pub fn cert_store(mut self, store: Arc<dyn CertStore>) -> Self { self.0.cert_store = Some(store); self }
#[must_use] pub fn event_handler(mut self, handler: EventHandler) -> Self { self.0.event_handler = Some(handler); self }
pub fn build(self) -> Result<AlpnHandlerConfig> { self.0.validate()?; Ok(self.0) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wildcard_matches_one_label_only() {
let pattern = HostPattern::single_label_wildcard("*.example.com").unwrap();
assert!(pattern.matches(&DnsName::parse("a.example.com").unwrap()));
assert!(!pattern.matches(&DnsName::parse("example.com").unwrap()));
assert!(!pattern.matches(&DnsName::parse("a.b.example.com").unwrap()));
assert!(!pattern.matches(&DnsName::parse("badexample.com").unwrap()));
}
#[test]
fn dns_server_parses_transport_and_ipv6() {
let udp: DnsServer = "udp://127.0.0.1:53".parse().unwrap();
assert_eq!(udp.transport, DnsTransport::Udp);
let tcp: DnsServer = "tcp://[2001:4860:4860::8888]:1053".parse().unwrap();
assert_eq!(tcp.transport, DnsTransport::Tcp);
assert_eq!(tcp.address.port(), 1053);
let automatic: DnsServer = "1.1.1.1:53".parse().unwrap();
assert_eq!(automatic.transport, DnsTransport::UdpThenTcp);
assert!("https://1.1.1.1:443".parse::<DnsServer>().is_err());
}
#[test]
fn for_host_detects_single_label_wildcard() {
let config = AlpnHandlerConfig::for_host("*.example.com").unwrap();
assert!(config.allowed_hosts[0].matches(&DnsName::parse("api.example.com").unwrap()));
assert!(!config.allowed_hosts[0].matches(&DnsName::parse("api.v2.example.com").unwrap()));
let one_label = AlpnHandlerConfig::for_host("*").unwrap();
assert!(one_label.allowed_hosts[0].matches(&DnsName::parse("localhost").unwrap()));
assert!(!one_label.allowed_hosts[0].matches(&DnsName::parse("api.example.com").unwrap()));
let middle = AlpnHandlerConfig::for_host("api.*.example.com").unwrap();
assert!(middle.allowed_hosts[0].matches(&DnsName::parse("api.v2.example.com").unwrap()));
assert!(AlpnHandlerConfig::for_host("*.bad_$.com").is_err());
let broad = AlpnHandlerConfig::for_host("*.*.*").unwrap();
assert!(broad.allowed_hosts[0].matches(&DnsName::parse("a.b.c").unwrap()));
assert!(!broad.allowed_hosts[0].matches(&DnsName::parse("a.b.c.d").unwrap()));
let partial = AlpnHandlerConfig::for_host("*help.wushilin.net").unwrap();
assert!(partial.allowed_hosts[0].matches(&DnsName::parse("myhelp.wushilin.net").unwrap()));
assert!(!partial.allowed_hosts[0].matches(&DnsName::parse("myhelp.other.net").unwrap()));
let many = AlpnHandlerConfig::for_hosts(["api.example.com", "*.internal.example"]).unwrap();
assert_eq!(many.allowed_hosts.len(), 2);
assert!(AlpnHandlerConfig::for_hosts(std::iter::empty::<&str>()).is_err());
}
}