// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Control's side of the Domi CA: certificates for the hosts of every tree that is applied, //! the device files both engines read, and what happens after an approval, a renewal or a //! revocation. // A refusal is built once per failed request; boxing it buys nothing. #![allow(clippy::result_large_err)] use std::path::Path; use std::sync::Arc; use std::time::Duration; use ianitor_core::TlsMode; use crate::engine::{Control, Fail}; use crate::messages::{self, Params}; use crate::pki::PkiFail; use crate::util::now; /// The HTTP status for a PKI refusal. pub fn status_of(code: &str) -> u16 { match code { "pki.request_not_found" | "pki.device_not_found" => 404, "pki.bundle_used" => 410, "pki.bad_certificate" | "pki.not_our_root" | "pki.wrong_key" | "pki.device_name" | "pki.device_kind" | "pki.wrong_code" | "pki.manual.not_ca" | "pki.manual.eku" | "pki.manual.dates" => 422, "pki.devices_unwritten" => 503, "pki.too_many_requests" => 429, _ => 409, } } pub fn pki_fail(e: PkiFail) -> Fail { match e { PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()), PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d), } } impl Control { pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> { self.pki .as_ref() .ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new())) } /// Every certificate directory a compiler output points at. fn cert_dirs(&self) -> Vec<&Path> { let mut v = vec![Path::new(&self.cfg.compile.cert_dir)]; let c = Path::new(&self.cfg.caddy_compile().cert_dir); if c != v[0] { v.push(c); } v } /// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the /// device files when a host needs them. Without `[pki]` nothing is issued (the files are /// expected to be there, as in phase 2). Returns whether a file changed. pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result { let Some(p) = &self.pki else { return Ok(false); }; let t = now(); let domi: Vec = model .hosts() .iter() .filter(|h| h.tls == TlsMode::Domi) .map(|h| h.hostname.to_string()) .collect(); let mut changed = false; for dir in self.cert_dirs() { let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| { let mut f = pki_fail(e); // The apply's reason names a host so the UI can point at it. if let Some(h) = domi.first() { f.reason.hostname = Some(h.clone()); } f })?; if !issued.is_empty() { log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", ")); changed = true; } // Always: the files are tiny, and a list that failed to be written catches up here. changed |= p.write_device_files(dir, t).map_err(pki_fail)?; } Ok(changed) } /// Every couple of seconds: act on approvals; once an hour: renew server certificates. pub async fn pki_poller(self: Arc) { if self.pki.is_none() { return; } let mut last_renewal_check = now(); // At start: bring the device files in line (a revocation that could not be written // before a restart is in force now). let _ = self.devices_changed().await; loop { tokio::time::sleep(Duration::from_secs(2)).await; let me = self.clone(); let polled = tokio::task::spawn_blocking(move || match &me.pki { Some(p) => p.poll(now()), None => Ok(Default::default()), }) .await; let changes = match polled { Ok(Ok(c)) => c, Ok(Err(e)) => { log::error!(target: "ianitor::pki", "{e}"); continue; } Err(e) => { log::error!(target: "ianitor::pki", "pki poll crashed: {e}"); continue; } }; let t = now(); if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 { last_renewal_check = t; self.refresh_certificates(changes.intermediate).await; } let retry = self .devices_problem .lock() .map(|p| p.is_some()) .unwrap_or(false); if changes.devices || retry { let _ = self.devices_changed().await; } } } /// Issue what the current tree needs (after a new intermediate: everything) and reload /// the engine that serves, under the apply lock so no trial is running. pub async fn refresh_certificates(&self, new_intermediate: bool) { let _lock = self.apply_lock.lock().await; let Ok((_, _, model)) = self.head_model() else { return; }; match self.pki_prepare(&model) { Ok(changed) if changed || new_intermediate => { if new_intermediate { log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued"); } self.reload_serving_engine().await; } Ok(_) => {} Err(f) => { log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message); } } } /// The device files changed (issue or revoke): rewrite them and tell the engine at once. /// /// It never waits for an apply (fix round 3): the files go to disk at once and edge is told /// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves /// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now /// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote, /// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch /// (engine lock busy for more than a second) the engine being started reads them anyway. pub async fn devices_changed(&self) -> Result<(), String> { let Some(p) = &self.pki else { return Ok(()) }; let _files = self.devices_lock.lock().await; let t = now(); let mut result = Ok(()); for dir in self.cert_dirs() { if let Err(e) = p.write_device_files(dir, t) { result = Err(format!( "the device files in {} could not be written: {e}", dir.display() )); } } // The engine lock is held for long only by a switch; an apply holds it for a moment // (loading a trial, or from the claim to the promoted reload), so then this waits. let engine = match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await { Ok(g) => Some(g), Err(_) if self.engine_state().state == "switching" => None, Err(_) => Some(self.engine_lock.lock().await), }; // Tell the serving engine every time, changed or not: a repeated Revoke nudges again. // During a switch it is not told now, and never silently (QC round 4): the problem // stays set, so the retry tells whichever engine serves once the switch is over (the // switch itself also ends by telling it). let mut pending = None; if result.is_ok() { if engine.is_none() { pending = Some( "an engine switch is under way; the engine that serves after it is told then" .to_owned(), ); } else { result = self.nudge_devices().await; } } if let Ok(mut pr) = self.devices_problem.lock() { *pr = result.as_ref().err().cloned().or(pending.clone()); } if let Some(p) = &pending { log::info!(target: "ianitor::pki", "{p}"); } if let Err(e) = &result { log::error!(target: "ianitor::pki", "{e}; retrying"); } result } /// Tell the engine that serves to read the device files again. The caller holds the engine /// lock. Under Caddy with a trial out, the end of that apply does it (promote, revert, the /// guard and caddy-revert all load caddy.json, which reads the files). pub(crate) async fn nudge_devices(&self) -> Result<(), String> { let caddy = self.engine_running() == "caddy"; if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() { log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends"); Ok(()) } else if caddy { self.caddy_reload_checked() .await .map_err(|e| format!("Caddy did not reload the device list: {e}")) } else if self.edge.attached() { self.edge .reload_devices() .await .map_err(|e| format!("edge did not re-read the device list: {e}")) } else { Ok(()) } } async fn reload_serving_engine(&self) { let _engine = self.engine_lock.lock().await; if self.engine_running() == "caddy" { if let Err(e) = self.caddy_reload_checked().await { log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}"); } } else if self.edge.attached() && let Err(e) = self.edge.reload().await { log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}"); } } /// The code and message for a PKI request that waits for its approval. pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) { let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual"); let c = match (kind, manual) { ("intermediate", _) => "pki.renew.manual", (_, true) => "pki.waiting.manual", (_, false) => "pki.waiting", }; ( c.to_owned(), messages::message(c, &messages::params([("code", code.to_owned())])), ) } }