diff --git a/Cargo.lock b/Cargo.lock index 5cfaa270e..798ad31f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1519,12 +1519,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" -[[package]] -name = "humantime" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -4009,7 +4003,6 @@ dependencies = [ "axum", "clap", "futures-util", - "humantime", "hyper", "hyper-util", "k8s-openapi", @@ -4194,7 +4187,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", "windows-sys 0.61.2", diff --git a/Cargo.toml b/Cargo.toml index 2d93394c3..a7f06cb29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,6 @@ futures = "0.3.34" futures-util = "0.3.34" hickory-resolver = "0.26.3" http = "1.5.0" -humantime = "2.4.0" indexmap = "2.14.2" indoc = "2.0.8" jiff = "1.0.1" diff --git a/crates/stackable-webhook/Cargo.toml b/crates/stackable-webhook/Cargo.toml index d3a07e411..afcc6370e 100644 --- a/crates/stackable-webhook/Cargo.toml +++ b/crates/stackable-webhook/Cargo.toml @@ -15,7 +15,6 @@ arc-swap.workspace = true async-trait.workspace = true axum.workspace = true futures-util.workspace = true -humantime.workspace = true hyper-util.workspace = true hyper.workspace = true k8s-openapi.workspace = true diff --git a/crates/stackable-webhook/src/tls/cert_resolver.rs b/crates/stackable-webhook/src/tls/cert_resolver.rs index 4f4108e4b..d4f58ad8d 100644 --- a/crates/stackable-webhook/src/tls/cert_resolver.rs +++ b/crates/stackable-webhook/src/tls/cert_resolver.rs @@ -7,9 +7,9 @@ use tokio::sync::mpsc; use tokio_rustls::rustls::{ crypto::CryptoProvider, server::ResolvesServerCert, sign::CertifiedKey, }; -use x509_cert::Certificate; +use x509_cert::{Certificate, der::DateTime, time::Time}; -use super::{WEBHOOK_CA_LIFETIME, WEBHOOK_CERTIFICATE_LIFETIME}; +use super::{CERTIFICATE_EXPIRY_BUFFER, WEBHOOK_CA_LIFETIME, WEBHOOK_CERTIFICATE_LIFETIME}; type Result = std::result::Result; @@ -45,6 +45,19 @@ pub enum CertificateResolverError { #[snafu(display("no default rustls CryptoProvider installed"))] NoDefaultCryptoProviderInstalled, + + #[snafu(display("failed to compute certificate rotation deadline"))] + ComputeRotationDeadline { source: x509_cert::der::Error }, +} + +/// The wall-clock expiry times of a certificate. +#[derive(Debug)] +struct CertificateExpiry { + /// The `notAfter` time of the certificate. + not_after: Time, + + /// When to rotate the certificate: `notAfter` minus [`CERTIFICATE_EXPIRY_BUFFER`]. + rotation_deadline: Time, } /// This struct serves as [`ResolvesServerCert`] to always hand out the current certificate for TLS @@ -58,9 +71,9 @@ pub struct CertificateResolver { /// (and performant) bridge between async write and sync read. current_certified_key: ArcSwap, - /// The wall-clock expiry time (`not_after`) of the current certificate. + /// The wall-clock expiry times of the current certificate. /// Used to detect clock drift between monotonic and wall-clock time. - current_not_after: ArcSwap, + current_expiry: ArcSwap, subject_alternative_dns_names: Arc>, @@ -73,7 +86,7 @@ impl CertificateResolver { certificate_tx: mpsc::Sender, ) -> Result { let subject_alternative_dns_names = Arc::new(subject_alternative_dns_names); - let (certified_key, not_after) = Self::generate_new_certificate_inner( + let (certified_key, expiry) = Self::generate_new_certificate_inner( subject_alternative_dns_names.clone(), &certificate_tx, ) @@ -82,51 +95,48 @@ impl CertificateResolver { Ok(Self { subject_alternative_dns_names, current_certified_key: ArcSwap::new(certified_key), - current_not_after: ArcSwap::new(Arc::new(not_after)), + current_expiry: ArcSwap::new(Arc::new(expiry)), certificate_tx, }) } pub async fn rotate_certificate(&self) -> Result<()> { - let (certified_key, not_after) = self.generate_new_certificate().await?; + let (certified_key, expiry) = self.generate_new_certificate().await?; // TODO: Sign the new cert somehow with the old cert. See https://github.com/stackabletech/decisions/issues/56 self.current_certified_key.store(certified_key); - self.current_not_after.store(Arc::new(not_after)); + self.current_expiry.store(Arc::new(expiry)); Ok(()) } /// Returns `true` if the current certificate is expired or will expire - /// within the given `buffer` duration according to wall-clock time. + /// within [`CERTIFICATE_EXPIRY_BUFFER`] according to wall-clock time. /// /// This catches cases where the monotonic timer (used by `tokio::time`) /// has drifted from wall-clock time, e.g. due to system hibernation. - pub fn needs_rotation(&self, buffer: std::time::Duration) -> bool { - let not_after = **self.current_not_after.load(); - // If subtraction underflows (buffer > time since epoch), fall back to - // UNIX_EPOCH so that the comparison always triggers rotation. - let deadline = not_after - .checked_sub(buffer) - .unwrap_or(SystemTime::UNIX_EPOCH); + pub fn needs_rotation(&self) -> bool { + let expiry = self.current_expiry.load(); tracing::debug!( x509.subject_alternative_names = ?self.subject_alternative_dns_names, - x509.not_after = %humantime::format_rfc3339(not_after), - deadline = %humantime::format_rfc3339(deadline), + // Will print in RFC 3339 format + x509.not_after = %expiry.not_after, + deadline = %expiry.rotation_deadline, + expiry_buffer = %CERTIFICATE_EXPIRY_BUFFER, "checking if certificate needs rotation" ); - SystemTime::now() >= deadline + SystemTime::now() >= expiry.rotation_deadline.to_system_time() } - async fn generate_new_certificate(&self) -> Result<(Arc, SystemTime)> { + async fn generate_new_certificate(&self) -> Result<(Arc, CertificateExpiry)> { let subject_alternative_dns_names = self.subject_alternative_dns_names.clone(); Self::generate_new_certificate_inner(subject_alternative_dns_names, &self.certificate_tx) .await } - /// Creates a new certificate and returns the certified key as well as `notAfter` timestamp. + /// Creates a new certificate and returns the certified key as well as its expiry times. /// /// The certificate is send to the passed `cert_tx`. /// @@ -136,7 +146,7 @@ impl CertificateResolver { async fn generate_new_certificate_inner( subject_alternative_dns_names: Arc>, certificate_tx: &mpsc::Sender, - ) -> Result<(Arc, SystemTime)> { + ) -> Result<(Arc, CertificateExpiry)> { // The certificate generations can take a while, so we use `spawn_blocking` let (cert, certified_key) = tokio::task::spawn_blocking(move || { let tls_provider = @@ -174,17 +184,32 @@ impl CertificateResolver { .await .context(TokioSpawnBlockingSnafu)??; - let not_after = cert.tbs_certificate().validity().not_after.to_system_time(); + let not_after = cert.tbs_certificate().validity().not_after; + let expiry = CertificateExpiry { + not_after, + rotation_deadline: rotation_deadline(not_after, *CERTIFICATE_EXPIRY_BUFFER)?, + }; certificate_tx .send(cert) .await .map_err(|_err| CertificateResolverError::SendCertificateToChannel)?; - Ok((certified_key, not_after)) + Ok((certified_key, expiry)) } } +/// Returns the time at which a certificate expiring at `not_after` should be rotated. +fn rotation_deadline(not_after: Time, expiry_buffer: std::time::Duration) -> Result