domani/src/domain/manager.rs

330 lines
10 KiB
Rust
Raw Normal View History

use crate::domain::{self, acme, checker, config};
use crate::error::unexpected::{self, Mappable};
use crate::origin;
use crate::util;
2023-05-17 10:34:24 +00:00
use std::{future, pin, sync};
use tokio_util::sync::CancellationToken;
#[derive(thiserror::Error, Debug)]
pub enum GetConfigError {
#[error("not found")]
NotFound,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
impl From<config::GetError> for GetConfigError {
fn from(e: config::GetError) -> GetConfigError {
match e {
config::GetError::NotFound => GetConfigError::NotFound,
config::GetError::Unexpected(e) => GetConfigError::Unexpected(e),
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum ReadFileIntoError {
#[error("domain not found")]
DomainNotFound,
#[error("file not found")]
FileNotFound,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
impl From<config::GetError> for ReadFileIntoError {
fn from(e: config::GetError) -> Self {
match e {
config::GetError::NotFound => Self::DomainNotFound,
config::GetError::Unexpected(e) => Self::Unexpected(e),
}
}
}
impl From<origin::ReadFileIntoError> for ReadFileIntoError {
fn from(e: origin::ReadFileIntoError) -> Self {
match e {
origin::ReadFileIntoError::DescrNotSynced => {
Self::Unexpected(unexpected::Error::from("origin descr not synced"))
}
origin::ReadFileIntoError::FileNotFound => Self::FileNotFound,
origin::ReadFileIntoError::Unexpected(e) => Self::Unexpected(e),
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum SyncError {
#[error("not found")]
NotFound,
#[error("already in progress")]
AlreadyInProgress,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
impl From<config::GetError> for SyncError {
fn from(e: config::GetError) -> SyncError {
match e {
config::GetError::NotFound => SyncError::NotFound,
config::GetError::Unexpected(e) => SyncError::Unexpected(e),
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum SyncWithConfigError {
#[error("invalid url")]
InvalidURL,
#[error("invalid branch name")]
InvalidBranchName,
#[error("already in progress")]
AlreadyInProgress,
2023-05-15 20:16:29 +00:00
#[error("target A/AAAA not set")]
TargetANotSet,
#[error("challenge token not set")]
ChallengeTokenNotSet,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
impl From<origin::SyncError> for SyncWithConfigError {
fn from(e: origin::SyncError) -> SyncWithConfigError {
match e {
origin::SyncError::InvalidURL => SyncWithConfigError::InvalidURL,
origin::SyncError::InvalidBranchName => SyncWithConfigError::InvalidBranchName,
origin::SyncError::AlreadyInProgress => SyncWithConfigError::AlreadyInProgress,
origin::SyncError::Unexpected(e) => SyncWithConfigError::Unexpected(e),
}
}
}
impl From<checker::CheckDomainError> for SyncWithConfigError {
fn from(e: checker::CheckDomainError) -> SyncWithConfigError {
match e {
2023-05-15 20:16:29 +00:00
checker::CheckDomainError::TargetANotSet => SyncWithConfigError::TargetANotSet,
checker::CheckDomainError::ChallengeTokenNotSet => {
SyncWithConfigError::ChallengeTokenNotSet
}
checker::CheckDomainError::Unexpected(e) => SyncWithConfigError::Unexpected(e),
}
}
}
impl From<config::SetError> for SyncWithConfigError {
fn from(e: config::SetError) -> SyncWithConfigError {
match e {
config::SetError::Unexpected(e) => SyncWithConfigError::Unexpected(e),
}
}
}
pub type GetAcmeHttp01ChallengeKeyError = acme::manager::GetHttp01ChallengeKeyError;
//#[mockall::automock]
pub trait Manager: Sync + Send + rustls::server::ResolvesServerCert {
fn get_config(&self, domain: &domain::Name) -> Result<config::Config, GetConfigError>;
2023-05-17 12:37:23 +00:00
fn read_file_into(
&self,
domain: &domain::Name,
path: &str,
into: &mut dyn std::io::Write,
) -> Result<(), ReadFileIntoError>;
2023-06-18 12:46:52 +00:00
fn sync_cert<'mgr>(
&'mgr self,
domain: domain::Name,
) -> pin::Pin<Box<dyn future::Future<Output = Result<(), unexpected::Error>> + Send + 'mgr>>;
fn sync_with_config<'mgr>(
&'mgr self,
domain: domain::Name,
config: config::Config,
) -> pin::Pin<Box<dyn future::Future<Output = Result<(), SyncWithConfigError>> + Send + 'mgr>>;
fn get_acme_http01_challenge_key(
&self,
token: &str,
) -> Result<String, GetAcmeHttp01ChallengeKeyError>;
2023-06-18 11:53:02 +00:00
fn all_domains(&self) -> Result<Vec<domain::Name>, unexpected::Error>;
}
pub struct ManagerImpl {
origin_store: Box<dyn origin::Store + Send + Sync>,
domain_config_store: Box<dyn config::Store + Send + Sync>,
domain_checker: checker::DNSChecker,
acme_manager: Option<Box<dyn acme::manager::Manager + Send + Sync>>,
}
impl ManagerImpl {
pub fn new<
OriginStore: origin::Store + Send + Sync + 'static,
DomainConfigStore: config::Store + Send + Sync + 'static,
AcmeManager: acme::manager::Manager + Send + Sync + 'static,
>(
task_stack: &mut util::TaskStack<unexpected::Error>,
origin_store: OriginStore,
domain_config_store: DomainConfigStore,
domain_checker: checker::DNSChecker,
acme_manager: Option<AcmeManager>,
2023-07-04 17:42:12 +00:00
) -> sync::Arc<Self> {
let manager = sync::Arc::new(ManagerImpl {
origin_store: Box::from(origin_store),
domain_config_store: Box::from(domain_config_store),
2023-07-04 17:42:12 +00:00
domain_checker,
acme_manager: acme_manager
.map(|m| Box::new(m) as Box<dyn acme::manager::Manager + Send + Sync>),
});
task_stack.push_spawn(|canceller| {
let manager = manager.clone();
2023-07-04 17:42:12 +00:00
async move {
manager.sync_origins(canceller).await;
Ok(())
}
});
manager
}
async fn sync_origins(&self, canceller: CancellationToken) {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(20 * 60));
loop {
tokio::select! {
_ = interval.tick() => {
match self.origin_store.all_descrs() {
Ok(iter) => iter.into_iter(),
Err(err) => {
log::error!("Error fetching origin descriptors: {err}");
return;
}
2023-06-21 12:05:28 +00:00
}
.for_each(|descr| {
if let Err(err) = self.origin_store.sync(&descr) {
2023-07-04 17:42:12 +00:00
log::error!("Failed to sync store for {:?}: {err}", descr)
}
});
},
_ = canceller.cancelled() => return,
}
}
}
}
2023-06-18 11:53:02 +00:00
impl Manager for ManagerImpl {
fn get_config(&self, domain: &domain::Name) -> Result<config::Config, GetConfigError> {
Ok(self.domain_config_store.get(domain)?)
}
fn read_file_into(
&self,
domain: &domain::Name,
path: &str,
into: &mut dyn std::io::Write,
) -> Result<(), ReadFileIntoError> {
let config = self.domain_config_store.get(domain)?;
self.origin_store
.read_file_into(&config.origin_descr, path, into)?;
Ok(())
}
2023-06-18 12:46:52 +00:00
fn sync_cert<'mgr>(
&'mgr self,
domain: domain::Name,
) -> pin::Pin<Box<dyn future::Future<Output = Result<(), unexpected::Error>> + Send + 'mgr>>
{
Box::pin(async move {
if let Some(ref acme_manager) = self.acme_manager {
acme_manager.sync_domain(domain.clone()).await?;
}
Ok(())
})
}
fn sync_with_config<'mgr>(
&'mgr self,
domain: domain::Name,
config: config::Config,
) -> pin::Pin<Box<dyn future::Future<Output = Result<(), SyncWithConfigError>> + Send + 'mgr>>
{
Box::pin(async move {
let config_hash = config
.hash()
.or_unexpected_while("calculating config hash")?;
self.domain_checker
.check_domain(&domain, &config_hash)
.await?;
self.origin_store.sync(&config.origin_descr)?;
self.domain_config_store.set(&domain, &config)?;
2023-06-18 12:46:52 +00:00
self.sync_cert(domain).await?;
Ok(())
})
}
2023-05-17 12:37:23 +00:00
fn get_acme_http01_challenge_key(
&self,
token: &str,
) -> Result<String, GetAcmeHttp01ChallengeKeyError> {
if let Some(ref acme_manager) = self.acme_manager {
return acme_manager.get_http01_challenge_key(token);
}
Err(GetAcmeHttp01ChallengeKeyError::NotFound)
}
2023-06-18 11:53:02 +00:00
fn all_domains(&self) -> Result<Vec<domain::Name>, unexpected::Error> {
self.domain_config_store.all_domains()
}
}
impl rustls::server::ResolvesServerCert for ManagerImpl {
fn resolve(
&self,
client_hello: rustls::server::ClientHello<'_>,
) -> Option<sync::Arc<rustls::sign::CertifiedKey>> {
let domain = client_hello.server_name()?;
match self.acme_manager.as_ref()?.get_certificate(domain) {
Err(acme::manager::GetCertificateError::NotFound) => {
log::warn!("No cert found for domain {domain}");
Ok(None)
}
Err(acme::manager::GetCertificateError::Unexpected(err)) => Err(err),
Ok((key, cert)) => {
match rustls::sign::any_supported_type(&key.into()).or_unexpected() {
Err(err) => Err(err),
Ok(key) => Ok(Some(sync::Arc::new(rustls::sign::CertifiedKey {
cert: cert.into_iter().map(|cert| cert.into()).collect(),
key,
ocsp: None,
sct_list: None,
}))),
}
}
}
.unwrap_or_else(|err| {
log::error!("Unexpected error getting cert for domain {domain}: {err}");
None
})
}
}