diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index 30ab398..1ab3760 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -281,6 +281,7 @@ pub async fn overview( intermediate: super::pki::intermediate_view(c), site, paused_reason: c.effective_pause().map(|p| p.code), + paused_detail: c.effective_pause().and_then(|p| p.detail), paused: c.effective_pause().map(|p| Blocked { code: "control.paused".into(), message: message("control.paused", &messages::params([("reason", p.message)])), diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs index c7e7996..323efd1 100644 --- a/crates/control/src/api/views.rs +++ b/crates/control/src/api/views.rs @@ -544,6 +544,8 @@ pub struct Overview { /// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`, /// `repo.unreadable`, …), so the UI can offer the right action. pub paused_reason: Option, + /// The technical detail behind the pause, for "Show details" (never a secret). + pub paused_detail: Option, /// Set when control cannot read health from edge (`health.unavailable`). pub health_error: Option, pub rev: Option, diff --git a/crates/control/src/caddy_guard.rs b/crates/control/src/caddy_guard.rs new file mode 100644 index 0000000..cac05a2 --- /dev/null +++ b/crates/control/src/caddy_guard.rs @@ -0,0 +1,204 @@ +// 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/. + +//! The deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an +//! unconfirmed change never outlives control). Edge drops a trial by itself when control does +//! not confirm it in time; Caddy has no such clock, so two things outside control's own process +//! stand in for it: +//! +//! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs +//! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the +//! last good config) at once; +//! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is +//! covered too): once a second, it reverts a trial whose deadline has passed. +//! +//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial +//! and *claims* it (an atomic rename) before it confirms; the guard *expires* it with the same +//! kind of rename. Whoever renames first wins, so a trial is either confirmed by control or +//! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed +//! config, so loading it is always safe. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::config::Config; +use crate::records::Journal; +use crate::util::{read_json, write_json}; + +pub const DEADLINE_FILE: &str = "caddy-trial.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TrialDeadline { + pub apply_id: String, + /// Unix seconds. + pub deadline: u64, +} + +fn path(state_dir: &Path, suffix: &str) -> PathBuf { + state_dir.join(format!("{DEADLINE_FILE}{suffix}")) +} + +/// Before a trial goes into Caddy. +pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> { + write_json( + &path(state_dir, ""), + &TrialDeadline { + apply_id: apply_id.to_owned(), + deadline, + }, + ) +} + +/// Control, before it confirms: `true` if it got the deadline first (the guard has not +/// reverted the trial), `false` if the guard did. +pub fn claim(state_dir: &Path) -> bool { + let claimed = path(state_dir, ".claimed"); + if std::fs::rename(path(state_dir, ""), &claimed).is_err() { + return false; + } + let _ = std::fs::remove_file(claimed); + true +} + +/// After a trial is reverted (or at start): nothing is out any more. +pub fn disarm(state_dir: &Path) { + for s in ["", ".claimed", ".expired"] { + let _ = std::fs::remove_file(path(state_dir, s)); + } +} + +pub fn armed(state_dir: &Path) -> Option { + read_json(&path(state_dir, "")).ok().flatten() +} + +/// Whether control's journal says the change is confirmed (then it is being promoted and +/// caddy.json will hold it; nothing to revert). +fn confirmed(state_dir: &Path) -> bool { + read_json::(&state_dir.join("journal.json")) + .ok() + .flatten() + .is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted") +} + +/// What to do now, for a deadline file as found (pure, for the tests). +#[derive(Debug, PartialEq, Eq)] +pub enum Verdict { + Nothing, + Revert, +} + +pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict { + match armed { + Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert, + _ => Verdict::Nothing, + } +} + +/// Take the deadline away from control (rename) and load the last good caddy.json. +async fn revert(cfg: &Config, why: &str) -> Result { + let dir = &cfg.state_dir; + let expired = path(dir, ".expired"); + if std::fs::rename(path(dir, ""), &expired).is_err() { + // Control claimed it a moment ago: it confirms; nothing to do. + return Ok(false); + } + let sock = cfg + .caddy_compile() + .caddy_admin_socket + .clone() + .ok_or("no caddy_admin_socket is configured")?; + let text = std::fs::read(&cfg.caddy.config) + .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; + crate::caddy_link::load(Path::new(&sock), &text).await?; + log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config"); + Ok(true) +} + +/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once. +pub async fn revert_after_stop(cfg: &Config) -> Result { + let dir = &cfg.state_dir; + match verdict( + armed(dir).as_ref(), + confirmed(dir), + crate::util::now(), + true, + ) { + Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await, + Verdict::Nothing => Ok(false), + } +} + +/// One tick of `ianitor-control caddy-guard`. +pub async fn tick(cfg: &Config) -> Result { + let dir = &cfg.state_dir; + match verdict( + armed(dir).as_ref(), + confirmed(dir), + crate::util::now(), + false, + ) { + Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await, + Verdict::Nothing => Ok(false), + } +} + +/// `ianitor-control caddy-guard`: forever, once a second. +pub async fn run(cfg: Config) -> Result<(), String> { + log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display()); + loop { + if let Err(e) = tick(&cfg).await { + log::error!(target: "ianitor::caddy-guard", "{e}"); + } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn d(deadline: u64) -> TrialDeadline { + TrialDeadline { + apply_id: "ch_1".into(), + deadline, + } + } + + #[test] + fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() { + assert_eq!(verdict(None, false, 100, false), Verdict::Nothing); + assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing); + assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert); + assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing); + } + + #[test] + fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() { + assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert); + assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing); + assert_eq!(verdict(None, false, 1, true), Verdict::Nothing); + } + + #[test] + fn control_and_the_guard_cannot_both_have_the_deadline() { + let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + arm(&dir, "ch_1", 10).unwrap(); + assert_eq!(armed(&dir), Some(d(10))); + // The guard took it (as `revert` does): control's claim fails. + std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap(); + assert!(!claim(&dir)); + disarm(&dir); + // Control claims first: nothing is left for the guard. + arm(&dir, "ch_1", 10).unwrap(); + assert!(claim(&dir)); + assert!(armed(&dir).is_none()); + assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err()); + disarm(&dir); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs index 48c839c..4dcc777 100644 --- a/crates/control/src/caddy_link.rs +++ b/crates/control/src/caddy_link.rs @@ -4,7 +4,9 @@ //! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep //! working under Caddy): loading a config through Caddy's admin API on its Unix socket -//! (`POST /load`, the whole JSON), and probing a host *through* Caddy for the health watch. +//! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host +//! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch, +//! judged like edge's), and the certificate Caddy serves. use std::net::SocketAddr; use std::path::Path; @@ -13,20 +15,14 @@ use std::time::{Duration, Instant}; const TIMEOUT: Duration = Duration::from_secs(10); -/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the -/// old one). -pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { +/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). +async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec), String> { #[cfg(unix)] { use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let head = format!( - "POST /load HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n", - config.len() - ); let exchange = async { let mut s = tokio::net::UnixStream::connect(socket).await?; - s.write_all(head.as_bytes()).await?; - s.write_all(config).await?; + s.write_all(request).await?; let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; Ok::<_, std::io::Error>(buf) @@ -35,29 +31,69 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { .await .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; - let text = String::from_utf8_lossy(&buf); - let status: u16 = text + let split = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("no answer from Caddy's admin API")?; + let head = String::from_utf8_lossy(&buf[..split]); + let status: u16 = head .split(' ') .nth(1) .and_then(|s| s.parse().ok()) .ok_or("no answer from Caddy's admin API")?; - if (200..300).contains(&status) { - Ok(()) - } else { - let body = text.split("\r\n\r\n").nth(1).unwrap_or("").trim(); - Err(format!( - "Caddy refused the config ({status}): {}", - body.chars().take(400).collect::() - )) - } + Ok((status, buf[split + 4..].to_vec())) } #[cfg(not(unix))] { - let _ = (socket, config); + let _ = (socket, request); Err("Caddy's admin socket needs Unix".into()) } } +/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the +/// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as +/// the running one, so certificate and device files are read again (without it an identical +/// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`). +pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { + let mut req = format!( + "POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", + config.len() + ) + .into_bytes(); + req.extend_from_slice(config); + let (status, body) = admin(socket, &req).await?; + if (200..300).contains(&status) { + Ok(()) + } else { + Err(format!( + "Caddy refused the config ({status}): {}", + String::from_utf8_lossy(&body) + .trim() + .chars() + .take(400) + .collect::() + )) + } +} + +/// The config Caddy runs now. +pub async fn running_config(socket: &Path) -> Result { + let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?; + if status != 200 { + return Err(format!( + "Caddy's admin API answered {status} to GET /config/" + )); + } + serde_json::from_slice(&body).map_err(|e| format!("Caddy's running config is not JSON: {e}")) +} + +/// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter). +pub async fn runs(socket: &Path, config: &[u8]) -> Result { + let want: serde_json::Value = + serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?; + Ok(running_config(socket).await? == want) +} + /// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Probe { @@ -156,3 +192,175 @@ pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe { )), } } + +/// SHA-256 (hex) of the leaf certificate Caddy serves for this name: after a reload, whether +/// Caddy really read the certificate files again (the backstop for B1). +pub async fn served_cert_sha256(addr: SocketAddr, host: &str) -> Result { + let run = async { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|e| e.to_string())? + .dangerous() + .with_custom_certificate_verifier(Arc::new(AnyCert)) + .with_no_client_auth(); + let name = + rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?; + let tcp = tokio::net::TcpStream::connect(addr) + .await + .map_err(|e| e.to_string())?; + let tls = tokio_rustls::TlsConnector::from(Arc::new(cfg)) + .connect(name, tcp) + .await + .map_err(|e| e.to_string())?; + let (_, conn) = tls.get_ref(); + let leaf = conn + .peer_certificates() + .and_then(|c| c.first()) + .ok_or("Caddy sent no certificate")?; + Ok::<_, String>(crate::util::sha256_hex(leaf.as_ref())) + }; + tokio::time::timeout(Duration::from_secs(5), run) + .await + .map_err(|_| "Caddy did not finish the handshake within 5 s".to_owned())? +} + +/// One health probe of an upstream, made by control while Caddy serves, with edge's rules +/// (crates/edge/src/health.rs): a host with a health check gets `GET ` with the upstream +/// address as Host and passes on 2xx; a host without one gets `GET /` with its own name as +/// Host and passes on any answer below 500. 5 s timeout. `kind` uses edge's words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpstreamProbe { + pub ok: bool, + pub kind: Option<&'static str>, + pub status: Option, + pub latency_ms: Option, +} + +fn status_kind(status: u16) -> &'static str { + match status { + 300..=399 => "redirect", + 401 | 403 => "sign_in", + 404 => "not_found", + 500..=599 => "server_error", + _ => "bad_answer", + } +} + +fn io_kind(e: &std::io::Error) -> &'static str { + use std::io::ErrorKind as K; + match e.kind() { + K::ConnectionRefused | K::ConnectionReset | K::ConnectionAborted | K::BrokenPipe => { + "refused" + } + K::TimedOut => "timeout", + _ if e.to_string().contains("lookup") => "name", + _ => "refused", + } +} + +/// The roots an `https://` upstream is checked against: the system bundle (`SSL_CERT_FILE`, +/// else the usual Debian/NixOS path), read once. +fn system_roots() -> Arc { + static ROOTS: std::sync::OnceLock> = std::sync::OnceLock::new(); + ROOTS + .get_or_init(|| { + let mut store = rustls::RootCertStore::empty(); + let path = std::env::var("SSL_CERT_FILE") + .unwrap_or_else(|_| "/etc/ssl/certs/ca-certificates.crt".into()); + if let Ok(pem) = std::fs::read_to_string(path) { + for der in ianitor_core::pki::chain_der(&pem).unwrap_or_default() { + let _ = store.add(rustls_pki_types::CertificateDer::from(der)); + } + } + Arc::new(store) + }) + .clone() +} + +pub async fn probe_upstream( + u: &ianitor_core::Upstream, + path: &str, + host_header: &str, + watch_only: bool, +) -> UpstreamProbe { + use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + let started = Instant::now(); + let fail = |kind: &'static str| UpstreamProbe { + ok: false, + kind: Some(kind), + status: None, + latency_ms: None, + }; + async fn ask( + mut s: S, + req: &[u8], + ) -> Result, std::io::Error> { + s.write_all(req).await?; + let mut head = [0u8; 64]; + let mut n = 0; + while n < 13 { + let k = s.read(&mut head[n..]).await?; + if k == 0 { + break; + } + n += k; + } + Ok(String::from_utf8_lossy(&head[..n]) + .split(' ') + .nth(1) + .and_then(|x| x.parse::().ok())) + } + let req = format!( + "GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n" + ); + let run = async { + let tcp = match tokio::net::TcpStream::connect(u.authority()).await { + Ok(t) => t, + Err(e) => return Err(io_kind(&e)), + }; + if u.scheme == ianitor_core::Scheme::Https { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let Ok(b) = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + else { + return Err("tls"); + }; + let cfg = b + .with_root_certificates(system_roots()) + .with_no_client_auth(); + let Ok(name) = rustls_pki_types::ServerName::try_from(u.host_str()) else { + return Err("name"); + }; + let tls = match tokio_rustls::TlsConnector::from(Arc::new(cfg)) + .connect(name, tcp) + .await + { + Ok(t) => t, + Err(_) => return Err("tls"), + }; + ask(tls, req.as_bytes()).await.map_err(|e| io_kind(&e)) + } else { + ask(tcp, req.as_bytes()).await.map_err(|e| io_kind(&e)) + } + }; + match tokio::time::timeout(Duration::from_secs(5), run).await { + Err(_) => fail("timeout"), + Ok(Err(kind)) => fail(kind), + Ok(Ok(None)) => fail("bad_answer"), + Ok(Ok(Some(status))) => { + let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let ok = if watch_only { + (100..500).contains(&status) + } else { + (200..300).contains(&status) + }; + UpstreamProbe { + ok, + kind: (!ok).then(|| status_kind(status)), + status: Some(status), + latency_ms: Some(latency), + } + } + } +} diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 5ac9f59..d5d1a8c 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -1541,8 +1541,9 @@ impl Control { remove_if_exists(&p).map_err(|e| e.to_string())?; } if caddy { - // Caddy must run caddy.json again, the last good config. + // Caddy must run caddy.json again, the last good config; no trial is out any more. self.caddy_reload().await?; + crate::caddy_guard::disarm(&self.cfg.state_dir); return Ok(rev); } // Edge must now run edge.json, the last good config. If it confirmed the trial after @@ -1703,10 +1704,15 @@ impl Control { self.unpause(); self.sync_files().await; } - if self.engine_running() == "caddy" - && let Err(e) = self.caddy_reload().await - { - log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}"); + if self.engine_running() == "caddy" { + match self.caddy_reload().await { + Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir), + Err(e) => { + log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}") + } + } + } else { + crate::caddy_guard::disarm(&self.cfg.state_dir); } if let Err(e) = self.shares.ensure_revocation_file() { log::error!(target: "ianitor::share", "{e}"); diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs index 55bc6ce..d1ee226 100644 --- a/crates/control/src/engine/caddy_apply.rs +++ b/crates/control/src/engine/caddy_apply.rs @@ -3,13 +3,44 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same -//! pipeline and journal as with edge; only the trial, the watch and the revert differ: the -//! trial is loaded into Caddy through its admin socket, the touched hosts are probed through -//! Caddy, and a revert loads caddy.json (the last good config) again. +//! pipeline and journal as with edge; only the trial, the watch and the revert differ: +//! +//! - the trial is loaded into Caddy through its admin socket, after its deadline is armed +//! (crate::caddy_guard: a crashed or hung control cannot leave it serving); +//! - the watch judges health the way edge does (QC round 2, M1): control probes the upstreams +//! itself with edge's rules, and the probe *through* Caddy only asks whether Caddy answers +//! at all (any status counts, also its auth redirect, 401, 403 or 421); +//! - every round checks that Caddy still runs the trial (M2: a reload by anyone else drops it); +//! - a revert loads caddy.json (the last good config) again; a confirm claims the deadline, +//! then promotes, loads caddy.json and checks that Caddy runs it. + +use std::net::SocketAddr; use super::*; +use crate::caddy_guard; use crate::caddy_link::{self, Probe}; +/// Where control reaches Caddy's HTTPS listener (its own machine). +fn local(addr: SocketAddr) -> SocketAddr { + if addr.ip().is_unspecified() { + let ip: std::net::IpAddr = if addr.is_ipv6() { + std::net::Ipv6Addr::LOCALHOST.into() + } else { + std::net::Ipv4Addr::LOCALHOST.into() + }; + SocketAddr::new(ip, addr.port()) + } else { + addr + } +} + +/// How one host is probed (edge's rules, crates/edge/src/health.rs). +struct Rule { + upstreams: Vec, + path: String, + has_check: bool, +} + impl Control { /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). pub fn caddy_socket(&self) -> Option { @@ -20,14 +51,87 @@ impl Control { .map(std::path::PathBuf::from) } - /// Load caddy.json (the last good config) into the running Caddy. + /// Load caddy.json (the last good config) into the running Caddy, even when it is the + /// config Caddy already runs (so it reads its files again), and check that it runs it. pub async fn caddy_reload(&self) -> Result<(), String> { let sock = self .caddy_socket() .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; let text = std::fs::read(&self.cfg.caddy.config) .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; - caddy_link::load(&sock, &text).await + caddy_link::load(&sock, &text).await?; + if !caddy_link::runs(&sock, &text).await? { + return Err("Caddy took the config but does not run it".into()); + } + Ok(()) + } + + /// `caddy_reload`, then the backstop for certificate and device changes: Caddy must serve + /// the certificate that is on disk now for a Domi host (it proves the files were read). + pub async fn caddy_reload_checked(&self) -> Result<(), String> { + self.caddy_reload().await?; + let Ok((_, _, model)) = self.head_model() else { + return Ok(()); + }; + let Some(h) = model + .hosts() + .iter() + .find(|h| h.tls == ianitor_core::TlsMode::Domi) + else { + return Ok(()); + }; + let file = std::path::Path::new(&self.cfg.caddy_compile().cert_dir) + .join(format!("{}.crt", h.hostname)); + let want = std::fs::read_to_string(&file) + .ok() + .and_then(|pem| ianitor_core::pki::chain_der(&pem).ok()) + .and_then(|c| c.into_iter().next()) + .map(|der| crate::util::sha256_hex(&der)) + .ok_or_else(|| format!("cannot read {}", file.display()))?; + let addr = local(self.cfg.caddy_compile().https_listen); + let got = caddy_link::served_cert_sha256(addr, h.hostname.as_str()).await?; + if got != want { + return Err(format!( + "Caddy still serves an older certificate for {} after the reload", + h.hostname + )); + } + Ok(()) + } + + fn caddy_rules(&self, plan: &Plan) -> BTreeMap { + plan.model + .hosts() + .iter() + .map(|h| { + ( + h.hostname.to_string(), + Rule { + upstreams: h.upstreams.clone(), + path: h + .health_check + .as_ref() + .map_or("/".to_owned(), |c| c.path.clone()), + has_check: h.health_check.is_some(), + }, + ) + }) + .collect() + } + + /// One round of edge-style upstream probes for one host; `(address, probe)` per upstream. + async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> { + let mut out = Vec::new(); + for u in &r.upstreams { + let host_header = if r.has_check { + u.authority() + } else { + hostname.to_owned() + }; + let p = caddy_link::probe_upstream(u, &r.path, &host_header, !r.has_check).await; + out.push((u.authority(), p)); + } + out } pub(super) async fn run_under_caddy( @@ -56,27 +160,10 @@ impl Control { .filter(|h| plan.target.host(h).is_some()) .cloned() .collect(); - let addr = self.cfg.caddy_compile().https_listen; - let path_of = |h: &str| -> (String, bool) { - plan.model - .hosts() - .iter() - .find(|x| x.hostname.as_str() == h) - .and_then(|x| x.health_check.as_ref()) - .map(|hc| (hc.path.clone(), true)) - .unwrap_or_else(|| ("/".to_owned(), false)) - }; - let good = |p: &Probe, has_check: bool| match p { - Probe::Status(s) => { - if has_check { - (200..300).contains(s) - } else { - *s < 500 - } - } - Probe::NoAnswer(_) => false, - }; - // A host that already failed through Caddy before the change is no reason to revert. + let addr = local(self.cfg.caddy_compile().https_listen); + let rules = self.caddy_rules(plan); + // A host whose upstreams already failed before the change is no reason to revert + // (edge: `down_hosts`). Judged by the upstreams, as edge does. let existed: BTreeSet = self .repo .tree(&j.base) @@ -90,12 +177,21 @@ impl Control { .unwrap_or_default(); let mut was_down = BTreeSet::new(); for h in &existed { - let (path, check) = path_of(h); - if !good(&caddy_link::probe(addr, h, &path).await, check) { + if let Some(r) = rules.get(h) + && !Self::probe_host(h, r).await.iter().any(|(_, p)| p.ok) + { was_down.insert(h.clone()); } } + let window = self.cfg.watch_secs; + // The deadline goes out before the trial does (crate::caddy_guard). + let deadline = now() + window + self.cfg.trial_margin_secs + 5; + if let Err(e) = caddy_guard::arm(&self.cfg.state_dir, id, deadline) { + let mut r = reason("internal", Params::new()); + r.detail = Some(e); + return self.revert(id, &j, r, "failed").await; + } if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await { return self .revert(id, &j, fail("apply.failed.reload", e), "failed") @@ -115,7 +211,6 @@ impl Control { .filter(|h| !was_down.contains(*h)) .cloned() .collect(); - let window = self.cfg.watch_secs; let mut kept_reason = if watch_hosts.is_empty() { reason( "apply.kept.removed", @@ -130,10 +225,10 @@ impl Control { ]), ) }; + let ends = now() + window; if judged.is_empty() { self.update(id, |r| r.step("watch", "skipped")); } else { - let ends = now() + window; self.update(id, |r| { r.state = "watching".into(); r.step("watch", "running"); @@ -148,86 +243,19 @@ impl Control { .collect(), }); }); - // hostname -> (passed, failed, failed in a row, last probe) - let mut stats: BTreeMap)> = judged + } + if let Err(r) = self + .caddy_watch(id, &sock, caddy_text, &judged, &rules, plan, addr, ends) + .await + { + return self.revert(id, &j, r, "reverted").await; + } + if !judged.is_empty() { + let no_check: Vec = judged .iter() - .map(|h| (h.clone(), (0, 0, 0, None))) + .filter(|h| rules.get(*h).is_some_and(|r| !r.has_check)) + .cloned() .collect(); - let no_check: Vec = judged.iter().filter(|h| !path_of(h).1).cloned().collect(); - loop { - for h in &judged { - let (path, check) = path_of(h); - let p = caddy_link::probe(addr, h, &path).await; - let ok = good(&p, check); - if let Some(s) = stats.get_mut(h) { - if ok { - s.0 += 1; - s.2 = 0; - } else { - s.1 += 1; - s.2 += 1; - } - s.3 = Some(p); - } - } - self.update(id, |r| { - if let Some(w) = &mut r.watch { - for wh in &mut w.hosts { - if let Some(s) = stats.get(&wh.hostname) { - wh.passed = s.0; - wh.failed = s.1; - wh.total = s.0 + s.1; - } - } - } - }); - let over = now() >= ends; - let failing = stats - .iter() - .find(|(_, s)| s.2 >= 3 || (over && s.2 > 0)) - .map(|(h, s)| (h.clone(), s.clone())); - if let Some((h, s)) = failing { - let upstream = plan - .model - .hosts() - .iter() - .find(|x| x.hostname.as_str() == h) - .and_then(|x| x.upstreams.first()) - .map(|u| u.to_string()) - .unwrap_or_default(); - let mut p = messages::params([ - ("hostname", h.clone()), - ("verb", plan.verb.into()), - ("upstream", upstream.clone()), - ("count", s.1.to_string()), - ("of", (s.0 + s.1).to_string()), - ("seconds", window.to_string()), - ]); - let (code, detail) = match &s.3 { - Some(Probe::Status(st)) => { - p.insert("status".into(), st.to_string()); - ( - "apply.reverted.server_error", - format!("through Caddy: HTTP {st}"), - ) - } - Some(Probe::NoAnswer(e)) => { - ("apply.reverted.no_answer", format!("through Caddy: {e}")) - } - None => ("apply.reverted.no_answer", String::new()), - }; - let mut r = reason(code, p); - r.hostname = Some(h.clone()); - r.upstream = Some(upstream); - r.field = Some("upstreams[0]".into()); - r.detail = Some(detail); - return self.revert(id, &j, r, "reverted").await; - } - if over { - break; - } - tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await; - } if !no_check.is_empty() && no_check.len() == judged.len() { kept_reason = reason( "apply.kept.no_watch", @@ -237,6 +265,16 @@ impl Control { self.update(id, |r| r.step("watch", "done")); } crash::point("watched"); + // The guard may have reverted a trial that ran past its deadline (a stalled control): + // then this change is not kept. + if !caddy_guard::claim(&self.cfg.state_dir) { + let mut r = reason("apply.interrupted", Params::new()); + r.detail = Some( + "the trial ran past its deadline, so Caddy went back to the last good config" + .into(), + ); + return self.revert(id, &j, r, "reverted").await; + } j.stage = "confirmed".into(); if let Err(e) = self.journal(&j) { let mut r = reason("internal", Params::new()); @@ -258,6 +296,10 @@ impl Control { return; } crash::point("promoted"); + // caddy.json now holds the change: Caddy loads what was written, and must run it. + if let Err(e) = self.caddy_reload().await { + log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}"); + } let push_step = self.push_step(); self.update(id, |r| r.step("push", push_step)); self.finish(id, "kept", Some(kept_reason), Vec::new()); @@ -267,4 +309,139 @@ impl Control { } self.push_wake.notify_one(); } + + /// The watch under Caddy until `ends`: the reason to revert, if any. + #[allow(clippy::too_many_arguments)] + async fn caddy_watch( + &self, + id: &str, + sock: &std::path::Path, + trial: &str, + judged: &[String], + rules: &BTreeMap, + plan: &Plan, + addr: SocketAddr, + ends: u64, + ) -> Result<(), Reason> { + let mut seen: HashMap<(String, String), BTreeMap> = HashMap::new(); + let mut seq = 0u64; + let mut silent: BTreeMap = BTreeMap::new(); + let paths: HashMap = rules + .iter() + .map(|(h, r)| (h.clone(), r.path.clone())) + .collect(); + let mut first = true; + loop { + // Anyone else's reload (a device change, a restart of caddy-fallback) drops the + // trial: then this is not a verdict on the change. + match caddy_link::runs(sock, trial.as_bytes()).await { + Ok(true) => {} + Ok(false) => { + let mut r = reason("apply.reverted.edge_lost", Params::new()); + r.detail = Some("Caddy no longer runs the trial config".into()); + return Err(r); + } + Err(e) => { + let mut r = reason("apply.reverted.edge_lost", Params::new()); + r.detail = Some(e); + return Err(r); + } + } + if first { + crash::point("watching"); + first = false; + } + let mut counts = Vec::new(); + for h in judged { + let Some(rule) = rules.get(h) else { continue }; + // Does Caddy answer for this host at all? Any status does. + match caddy_link::probe(addr, h, "/").await { + Probe::Status(_) => { + silent.remove(h); + } + Probe::NoAnswer(e) => { + let s = silent.entry(h.clone()).or_insert((0, String::new())); + s.0 += 1; + s.1 = e; + } + } + if let Some((n, e)) = silent.get(h) + && *n >= 3 + { + let mut r = reason( + "apply.reverted.no_answer", + messages::params([ + ("hostname", h.clone()), + ("verb", plan.verb.into()), + ("seconds", self.cfg.watch_secs.to_string()), + ]), + ); + r.hostname = Some(h.clone()); + r.detail = Some(format!("Caddy does not answer for {h}: {e}")); + return Err(r); + } + for (address, p) in Self::probe_host(h, rule).await { + seq += 1; + seen.entry((h.clone(), address)).or_default().insert( + seq, + Check { + seq, + at: now(), + ok: p.ok, + source: if rule.has_check { + "health_check".into() + } else { + "watch".into() + }, + kind: p.kind.map(str::to_owned), + status: p.status, + latency_ms: p.latency_ms, + }, + ); + } + let mut passed = 0u32; + let mut failed = 0u32; + let mut all_failing = !rule.upstreams.is_empty(); + for ((host, _), m) in &seen { + if host != h { + continue; + } + passed += m.values().filter(|c| c.ok).count() as u32; + failed += m.values().filter(|c| !c.ok).count() as u32; + if m.values().rev().take_while(|c| !c.ok).count() < 3 { + all_failing = false; + } + } + counts.push(WatchHost { + hostname: h.clone(), + passed, + failed, + total: passed + failed, + }); + if all_failing { + return Err(self.revert_reason(h, plan, &seen, &paths)); + } + } + self.update(id, |r| { + if let Some(w) = &mut r.watch { + w.hosts = counts; + } + }); + if now() >= ends { + break; + } + tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await; + } + // At the end, as with edge: every judged host needs an upstream whose last probe passed. + for h in judged { + let last_ok = seen + .iter() + .filter(|((host, _), _)| host == h) + .any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok)); + if !last_ok { + return Err(self.revert_reason(h, plan, &seen, &paths)); + } + } + Ok(()) + } } diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 81bc905..65d3279 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -7,6 +7,7 @@ //! edge keeps serving the last good config. pub mod api; +pub mod caddy_guard; pub mod caddy_link; pub mod config; pub mod crash; diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index f979b10..a5fc768 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -30,7 +30,8 @@ fn usage() -> ExitCode { eprintln!( "usage: ianitor-control --config | --dev [--edge-bin ] | \ token create --name [--expires-days | --never] (--config | --state-dir ) | \ - token list (...) | token revoke (...) | openapi | check --config " + token list (...) | token revoke (...) | openapi | check --config | \ + caddy-revert --config | caddy-guard --config " ); ExitCode::from(2) } @@ -395,6 +396,27 @@ fn main() -> ExitCode { Ok(()) } Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), + // Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard. + Some(verb @ ("caddy-revert" | "caddy-guard")) => match args + .iter() + .position(|a| a == "--config") + .and_then(|i| args.get(i + 1)) + { + Some(p) => match Config::load(&PathBuf::from(p)) { + Ok(cfg) if verb == "caddy-guard" => { + rt.block_on(ianitor_control::caddy_guard::run(cfg)) + } + Ok(cfg) => rt + .block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg)) + .map(|done| { + if done { + eprintln!("Caddy is back on the last good config."); + } + }), + Err(e) => Err(e.to_string()), + }, + None => return usage(), + }, Some("--dev") => rt.block_on(dev::run(&args[1..])), Some("--config") => match args.get(1) { Some(p) => match Config::load(&PathBuf::from(p)) { diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs index a20227a..1586e3d 100644 --- a/crates/control/src/pki.rs +++ b/crates/control/src/pki.rs @@ -218,9 +218,11 @@ fn bundle_password() -> Result { /// Private keys in `dir` that are not control's own: control refuses to run with one in its /// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any -/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`, `*root*.pem` with -/// a key); the only keys allowed are `pki/intermediate.key`, `pki/pending-*.key` and -/// `pki/devices/*.key`, which control writes encrypted itself. +/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys +/// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those +/// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link +/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`, +/// compressed history) is not read. pub fn root_key_files(dir: &Path) -> Vec { let allowed = |p: &Path| -> bool { let Ok(rel) = p.strip_prefix(dir) else { @@ -242,6 +244,12 @@ pub fn root_key_files(dir: &Path) -> Vec { _ => false, } }; + let own_armour = |b: &[u8]| -> bool { + let t = String::from_utf8_lossy(b); + let begins = t.matches("-----BEGIN ").count(); + let ours = t.matches(OWN_BEGIN).count(); + begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2 + }; let mut found = Vec::new(); let mut stack = vec![(dir.to_path_buf(), 0)]; while let Some((d, depth)) = stack.pop() { @@ -250,21 +258,41 @@ pub fn root_key_files(dir: &Path) -> Vec { }; for e in rd.flatten() { let p = e.path(); - let Ok(meta) = e.metadata() else { continue }; + // symlink_metadata: a link is looked at, not followed. + let Ok(meta) = std::fs::symlink_metadata(&p) else { + continue; + }; + if meta.file_type().is_symlink() { + found.push(p); + continue; + } if meta.is_dir() { - if depth < 8 { + let git_objects = + e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git"); + if depth < 8 && !git_objects { stack.push((p, depth + 1)); } continue; } - if !meta.is_file() || allowed(&p) { + if !meta.is_file() { + continue; + } + let read = || { + (meta.len() <= 1 << 20) + .then(|| std::fs::read(&p).ok()) + .flatten() + }; + if allowed(&p) { + // Control's own key files: one key, in control's encrypted armour. + if !read().is_some_and(|b| own_armour(&b)) { + found.push(p); + } continue; } let name = e.file_name().to_string_lossy().to_ascii_lowercase(); let by_name = name.contains("root") && name.contains("key"); - let by_content = meta.len() <= 1 << 20 - && std::fs::read(&p) - .is_ok_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes())); + let by_content = + read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes())); if by_name || by_content { found.push(p); } @@ -275,6 +303,7 @@ pub fn root_key_files(dir: &Path) -> Vec { // Split so that this file does not match the pre-commit hook itself. const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----"); +const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----"); impl Pki { /// Open the CA state. The root certificate must be a CA and self-signed; the password @@ -1182,3 +1211,45 @@ pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result Result<(), String> { let Some(p) = &self.pki else { return Ok(()) }; + // Behind a running apply (QC round 2, M2): a reload during a Caddy trial's watch would + // drop the trial; afterwards it loads whatever is current. + let _apply = self.apply_lock.lock().await; let _engine = self.engine_lock.lock().await; let t = now(); let mut result = Ok(()); @@ -180,7 +183,7 @@ impl Control { // Tell the serving engine every time, changed or not: a repeated Revoke nudges again. if result.is_ok() { result = if self.engine_running() == "caddy" { - self.caddy_reload() + self.caddy_reload_checked() .await .map_err(|e| format!("Caddy did not reload the device list: {e}")) } else if self.edge.attached() { @@ -204,7 +207,7 @@ impl Control { 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().await { + 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() diff --git a/crates/control/tests/engine_switch.rs b/crates/control/tests/engine_switch.rs index bdbb9c5..dcab758 100644 --- a/crates/control/tests/engine_switch.rs +++ b/crates/control/tests/engine_switch.rs @@ -230,9 +230,17 @@ case "$1:$2" in start:caddy-fallback.service) XDG_DATA_HOME="{d}/caddy-state" XDG_CONFIG_HOME="{d}/caddy-state" HOME="{d}/caddy-state" \ nohup "{c}" run --config "{d}/caddy/caddy.json" >> "{d}/logs/caddy.log" 2>&1 & - echo $! > "{d}/fake/caddy.pid"; touch "$dir/$2" ;; + echo $! > "{d}/fake/caddy.pid" + # The NixOS module starts ianitor-caddy-guard with caddy-fallback (crate::caddy_guard). + if [ ! -e "{d}/fake/no-guard" ]; then + IANITOR_LOG=info nohup "{g}" caddy-guard --config "{d}/control.toml" >> "{d}/logs/caddy-guard.log" 2>&1 & + echo $! > "{d}/fake/guard.pid" + fi + touch "$dir/$2" ;; stop:caddy-fallback.service) - [ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null; rm -f "$dir/$2" "{d}/fake/caddy.pid" ;; + [ -f "{d}/fake/caddy.pid" ] && kill "$(cat "{d}/fake/caddy.pid")" 2>/dev/null + [ -f "{d}/fake/guard.pid" ] && kill "$(cat "{d}/fake/guard.pid")" 2>/dev/null + rm -f "$dir/$2" "{d}/fake/caddy.pid" "{d}/fake/guard.pid" ;; start:*) touch "$dir/$2" ;; stop:*) rm -f "$dir/$2" ;; is-active:*) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; @@ -240,7 +248,8 @@ case "$1:$2" in esac "#, d = dir.display(), - c = caddy.display() + c = caddy.display(), + g = env!("CARGO_BIN_EXE_ianitor-control"), ) } @@ -251,8 +260,10 @@ esac impl Drop for CaddyEnv { fn drop(&mut self) { - if let Ok(p) = std::fs::read_to_string(self.env.dir.join("fake/caddy.pid")) { - let _ = std::process::Command::new("kill").arg(p.trim()).status(); + for f in ["fake/caddy.pid", "fake/guard.pid"] { + if let Ok(p) = std::fs::read_to_string(self.env.dir.join(f)) { + let _ = std::process::Command::new("kill").arg(p.trim()).status(); + } } } } diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 895e0e1..f79e8cd 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -78,12 +78,23 @@ pub fn hostname(host_header: &str) -> String { /// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost /// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's /// `trusted_proxies_strict`). Anything a client could forge to the left is ignored. +/// An IPv4 address carried as IPv6 (`::ffff:127.0.0.1`) is the IPv4 address. +fn canonical(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), + v4 => v4, + } +} + pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option { - let peer = session - .client_addr() - .and_then(|a| a.as_inet()) - .map(|a| a.ip())?; - if !trusted.contains(&peer) { + let peer = canonical( + session + .client_addr() + .and_then(|a| a.as_inet()) + .map(|a| a.ip())?, + ); + let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip); + if !trusted_ip(&peer) { return Some(peer); } let mut last = peer; @@ -96,8 +107,8 @@ pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option { { let Ok(s) = v.to_str() else { return Some(last) }; for part in s.rsplit(',') { - match part.trim().parse::() { - Ok(ip) if trusted.contains(&ip) => last = ip, + match part.trim().parse::().map(canonical) { + Ok(ip) if trusted_ip(&ip) => last = ip, Ok(ip) => return Some(ip), Err(_) => return Some(last), } @@ -506,6 +517,14 @@ pub fn contains(hay: &[u8], needle: &[u8]) -> bool { mod tests { use super::*; + #[test] + fn an_ipv4_mapped_address_is_the_ipv4_address() { + let m = IpAddr::V6(std::net::Ipv4Addr::LOCALHOST.to_ipv6_mapped()); + assert_eq!(canonical(m), IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)); + let v6 = IpAddr::V6(std::net::Ipv6Addr::LOCALHOST); + assert_eq!(canonical(v6), v6); + } + #[test] fn hostname_strips_port_and_case() { assert_eq!(hostname("App.Test:8443"), "app.test");