[control] Fix round 2: Caddy rereads its files on every load and the served certificate is checked, Caddy trials get a deadline outside control (caddy-guard, caddy-revert), the watch under Caddy judges upstreams as edge does, a reload of Caddy during the watch is noticed and device changes wait for the apply, stricter root key scan, IPv4-mapped trusted proxies

This commit is contained in:
2026-11-08 12:04:13 +01:00
parent ba3a060b2e
commit 23a283ece9
12 changed files with 884 additions and 159 deletions
+285 -108
View File
@@ -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<ianitor_core::Upstream>,
path: String,
has_check: bool,
}
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
@@ -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<String, Rule> {
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<String> = 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<String, (u32, u32, u32, Option<Probe>)> = 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<String> = 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<String> = 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<String, Rule>,
plan: &Plan,
addr: SocketAddr,
ends: u64,
) -> Result<(), Reason> {
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
let mut seq = 0u64;
let mut silent: BTreeMap<String, (u32, String)> = BTreeMap::new();
let paths: HashMap<String, String> = 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(())
}
}