1use std::sync::Arc;
22use std::time::Duration;
23
24use time::OffsetDateTime;
25use tokio::sync::watch;
26use tracing::{error, info, warn};
27
28use super::config::AccountZoneConfig;
29use super::dns::DnsProvider;
30use super::tls::{CertHandle, IssuanceError, IssuedCert, WildcardCertIssuer};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CertHealth {
35 Ok,
37 ExpiringSoon,
40 Critical,
43 Expired,
45 Unissued,
47 Unprovisioned,
52}
53
54impl CertHealth {
55 pub fn label(self) -> &'static str {
57 match self {
58 CertHealth::Ok => "ok",
59 CertHealth::ExpiringSoon => "expiring_soon",
60 CertHealth::Critical => "critical",
61 CertHealth::Expired => "expired",
62 CertHealth::Unissued => "unissued",
63 CertHealth::Unprovisioned => "unprovisioned",
64 }
65 }
66}
67
68#[derive(Debug, Clone, Copy)]
70pub struct AlarmThresholds {
71 pub warn_lead: Duration,
73 pub critical_lead: Duration,
75}
76
77impl Default for AlarmThresholds {
78 fn default() -> Self {
79 Self {
81 warn_lead: Duration::from_secs(30 * 24 * 3600),
82 critical_lead: Duration::from_secs(7 * 24 * 3600),
83 }
84 }
85}
86
87pub fn classify(
92 handle: &CertHandle,
93 last_result: Option<&Result<IssuedCert, IssuanceError>>,
94 now: OffsetDateTime,
95 thresholds: &AlarmThresholds,
96 unprovisioned: bool,
97) -> CertHealth {
98 if unprovisioned {
99 return CertHealth::Unprovisioned;
100 }
101 let last_failed = matches!(last_result, Some(Err(_)));
103 let Some(not_after) = handle.not_after() else {
104 return if last_failed {
105 CertHealth::Critical
106 } else {
107 CertHealth::Unissued
108 };
109 };
110 let remaining = not_after - now;
111 if remaining.is_negative() {
112 return CertHealth::Expired;
113 }
114 let dur = Duration::try_from(remaining).unwrap_or(Duration::ZERO);
115 if last_failed || dur < thresholds.critical_lead {
121 CertHealth::Critical
122 } else if dur < thresholds.warn_lead {
123 CertHealth::ExpiringSoon
124 } else {
125 CertHealth::Ok
126 }
127}
128
129#[derive(Debug, Clone)]
131pub struct CertHealthMonitor {
132 thresholds: AlarmThresholds,
133}
134
135impl CertHealthMonitor {
136 pub fn new(thresholds: AlarmThresholds) -> Self {
137 Self { thresholds }
138 }
139
140 pub fn observe(
143 &self,
144 handle: &CertHandle,
145 last_result: Option<&Result<IssuedCert, IssuanceError>>,
146 unprovisioned: bool,
147 ) -> CertHealth {
148 let now = OffsetDateTime::now_utc();
149 let state = classify(handle, last_result, now, &self.thresholds, unprovisioned);
150 match state {
151 CertHealth::Ok | CertHealth::Unprovisioned => {
152 tracing::debug!(
153 account_tls_health = state.label(),
154 "account-zone wildcard TLS health: {}", state.label()
155 );
156 }
157 CertHealth::ExpiringSoon => warn!(
158 account_tls_health = state.label(),
159 "account-zone wildcard certificate expiring soon — renewal should be imminent"
160 ),
161 CertHealth::Critical => error!(
162 account_tls_health = state.label(),
163 "account-zone wildcard certificate CRITICAL — one cert failing breaks ALL account resolution for this deployment"
164 ),
165 CertHealth::Expired => error!(
166 account_tls_health = state.label(),
167 "account-zone wildcard certificate EXPIRED — account resolution is failing now"
168 ),
169 CertHealth::Unissued => info!(
170 account_tls_health = state.label(),
171 "account-zone wildcard certificate not yet issued"
172 ),
173 }
174 state
175 }
176}
177
178pub struct CertRenewer {
192 cfg: AccountZoneConfig,
193 issuer: Arc<dyn WildcardCertIssuer>,
194 dns: Arc<dyn DnsProvider>,
195 sender: watch::Sender<Option<IssuedCert>>,
196 handle: CertHandle,
197 thresholds: AlarmThresholds,
198 renew_lead: Duration,
200 tick: Duration,
202}
203
204impl CertRenewer {
205 pub fn new(
206 cfg: AccountZoneConfig,
207 issuer: Arc<dyn WildcardCertIssuer>,
208 dns: Arc<dyn DnsProvider>,
209 sender: watch::Sender<Option<IssuedCert>>,
210 handle: CertHandle,
211 ) -> Self {
212 Self {
213 cfg,
214 issuer,
215 dns,
216 sender,
217 handle,
218 thresholds: AlarmThresholds::default(),
219 renew_lead: Duration::from_secs(30 * 24 * 3600),
220 tick: Duration::from_secs(3600),
221 }
222 }
223
224 pub fn with_renew_lead(mut self, lead: Duration) -> Self {
226 self.renew_lead = lead;
227 self
228 }
229
230 pub fn with_thresholds(mut self, t: AlarmThresholds) -> Self {
232 self.thresholds = t;
233 self
234 }
235
236 pub fn with_tick(mut self, tick: Duration) -> Self {
238 self.tick = tick;
239 self
240 }
241
242 pub async fn run(self) {
249 let monitor = CertHealthMonitor::new(self.thresholds);
250 let zone = match super::tls::require_provisioned(&self.cfg) {
254 Ok(z) => Some(z),
255 Err(e) => {
256 warn!("account-zone wildcard TLS not provisioned: {e}");
257 None
258 }
259 };
260 let unprovisioned = zone.is_none();
261 let mut last_result: Option<Result<IssuedCert, IssuanceError>> = None;
262
263 loop {
264 if let Some(zone) = zone.as_ref() {
265 let due = match self.handle.not_after() {
266 None => true,
267 Some(na) => {
268 let remaining = na - OffsetDateTime::now_utc();
269 let dur = Duration::try_from(remaining).unwrap_or(Duration::ZERO);
270 dur < self.renew_lead
271 }
272 };
273 if due {
274 let res = self.issuer.issue(zone, &self.cfg, self.dns.as_ref()).await;
275 match &res {
276 Ok(c) => {
277 info!(
278 san = %c.san,
279 not_after = %c.not_after,
280 "account-zone wildcard certificate (re)issued"
281 );
282 let _ = self.sender.send(Some(c.clone()));
284 }
285 Err(e) => {
286 error!(
287 error = %e,
288 "account-zone wildcard certificate renewal FAILED — outage risk for ALL account resolution"
289 );
290 }
291 }
292 last_result = Some(res);
293 }
294 }
295 monitor.observe(&self.handle, last_result.as_ref(), unprovisioned);
296 tokio::time::sleep(self.tick).await;
298 }
299 }
300}
301
302#[cfg(test)]
303#[allow(clippy::unwrap_used)]
304mod tests {
305 use super::*;
306 use crate::account::config::AccountZoneConfig;
307 use crate::account::dns::UnconfiguredDnsProvider;
308 use crate::account::tls::NullWildcardCertIssuer;
309
310 fn handle_with_cert(not_after: OffsetDateTime) -> CertHandle {
311 let (tx, h) = CertHandle::channel();
312 let _ = tx.send(Some(IssuedCert {
313 cert_der: vec![],
314 chain_der: vec![],
315 key_der: zeroize::Zeroizing::new(vec![]),
316 not_after,
317 san: "*.acct.example.com".to_owned(),
318 }));
319 h
320 }
321
322 #[test]
323 fn classify_states() {
324 let t = AlarmThresholds::default();
325 let now = OffsetDateTime::now_utc();
326 let h = handle_with_cert(now + time::Duration::days(60));
327 assert_eq!(classify(&h, None, now, &t, false), CertHealth::Ok);
328 let h = handle_with_cert(now + time::Duration::days(20));
329 assert_eq!(classify(&h, None, now, &t, false), CertHealth::ExpiringSoon);
330 let h = handle_with_cert(now + time::Duration::days(3));
331 assert_eq!(classify(&h, None, now, &t, false), CertHealth::Critical);
332 let h = handle_with_cert(now - time::Duration::days(1));
333 assert_eq!(classify(&h, None, now, &t, false), CertHealth::Expired);
334
335 let (tx, empty) = CertHandle::channel();
337 drop(tx);
338 assert_eq!(classify(&empty, None, now, &t, false), CertHealth::Unissued);
339 assert_eq!(
340 classify(&empty, None, now, &t, true),
341 CertHealth::Unprovisioned
342 );
343
344 let h = handle_with_cert(now + time::Duration::days(60));
346 let err: Result<IssuedCert, IssuanceError> = Err(IssuanceError::Unprovisioned("x".into()));
347 assert_eq!(
348 classify(&h, Some(&err), now, &t, false),
349 CertHealth::Critical
350 );
351
352 let h = handle_with_cert(now + time::Duration::days(20)); assert_eq!(classify(&h, None, now, &t, false), CertHealth::ExpiringSoon);
357 assert_eq!(
358 classify(&h, Some(&err), now, &t, false),
359 CertHealth::Critical,
360 "failed renewal in the warn band must escalate to Critical, not ExpiringSoon"
361 );
362 }
363
364 #[tokio::test]
365 async fn renewer_degrades_when_unprovisioned() {
366 let cfg = AccountZoneConfig::default();
368 let issuer = Arc::new(NullWildcardCertIssuer) as Arc<dyn WildcardCertIssuer>;
369 let dns = Arc::new(UnconfiguredDnsProvider::new()) as Arc<dyn DnsProvider>;
370 let (sender, handle) = CertHandle::channel();
371 let renewer =
372 CertRenewer::new(cfg, issuer, dns, sender, handle).with_tick(Duration::from_millis(10));
373 let task = tokio::spawn(async move {
376 renewer.run().await;
377 });
378 tokio::time::sleep(Duration::from_millis(30)).await;
379 task.abort();
380 }
381}