[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:
@@ -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<TrialDeadline> {
|
||||
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::<Journal>(&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<bool, String> {
|
||||
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<bool, String> {
|
||||
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<bool, String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user