[control] Fix round 1: changes apply while Caddy serves (admin socket, watch through Caddy), revocations that fail are errors and catch up, proof only on the forward-auth UI host, root keys found by content, intermediates checked before install, stale SNI cleared before each handshake

This commit is contained in:
2026-11-08 10:49:31 +01:00
parent 0749119f19
commit e84eb1ba74
36 changed files with 934 additions and 131 deletions
+270
View File
@@ -0,0 +1,270 @@
// 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/.
//! 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.
use super::*;
use crate::caddy_link::{self, Probe};
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
self.cfg
.caddy_compile()
.caddy_admin_socket
.as_ref()
.map(std::path::PathBuf::from)
}
/// Load caddy.json (the last good config) into the running Caddy.
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
}
pub(super) async fn run_under_caddy(
&self,
id: &str,
mut j: Journal,
plan: &Plan,
caddy_text: &str,
change: &Change,
) {
let fail = |code: &str, detail: String| {
let mut r = reason(code, messages::params([("engine", "Caddy".into())]));
r.detail = Some(detail);
r
};
let Some(sock) = self.caddy_socket() else {
let r = fail(
"apply.failed.reload",
"no caddy_admin_socket is configured".into(),
);
return self.revert(id, &j, r, "failed").await;
};
let watch_hosts: Vec<String> = plan
.hosts
.iter()
.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 existed: BTreeSet<String> = self
.repo
.tree(&j.base)
.map(|t| {
watch_hosts
.iter()
.filter(|h| t.host(h).is_some())
.cloned()
.collect()
})
.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) {
was_down.insert(h.clone());
}
}
if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await {
return self
.revert(id, &j, fail("apply.failed.reload", e), "failed")
.await;
}
j.stage = "trial_loaded".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("trial_loaded");
self.update(id, |r| r.step("reload", "done"));
let judged: Vec<String> = watch_hosts
.iter()
.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",
messages::params([("hostname", plan.hosts.join(", "))]),
)
} else {
reason(
"apply.kept",
messages::params([
("hostname", watch_hosts.join(", ")),
("seconds", window.to_string()),
]),
)
};
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");
r.watch = Some(Watch {
ends,
hosts: judged
.iter()
.map(|h| WatchHost {
hostname: h.clone(),
..Default::default()
})
.collect(),
});
});
// hostname -> (passed, failed, failed in a row, last probe)
let mut stats: BTreeMap<String, (u32, u32, u32, Option<Probe>)> = judged
.iter()
.map(|h| (h.clone(), (0, 0, 0, None)))
.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",
messages::params([("hostname", no_check.join(", "))]),
);
}
self.update(id, |r| r.step("watch", "done"));
}
crash::point("watched");
j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("confirmed");
if let Err(e) = self.promote() {
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string());
p.params.insert("apply_id".into(), id.to_owned());
if let Err(pe) = self.pause(p) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
return;
}
crash::point("promoted");
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
self.clear_journal();
if self.paused().is_some() && matches!(change, Change::Restore { .. }) {
self.unpause();
}
self.push_wake.notify_one();
}
}