[tests] Tests first, fix round 2: same caddy.json reload rereads certificates, forward-auth hosts kept under Caddy as under edge, crash mid-trial under Caddy, Caddy reloaded during the watch, watching crash point, caddy-revert after a crash, TLS 1.2 device after a bad ALPN (red)

This commit is contained in:
2026-11-08 11:48:10 +01:00
parent 503916492d
commit ba3a060b2e
2 changed files with 427 additions and 0 deletions
+355
View File
@@ -392,4 +392,359 @@ esac
&& !edge_json.contains("c.test")
);
}
// ---------------------------------------------------------------- QC round 2
async fn qc_env_with_caddy_site(site: String) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
site,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
/// QC r2: a forward-auth host with a health check is kept under edge (edge checks the
/// upstream). Under Caddy the watch probes *through* Caddy without a session: Authelia's
/// redirect is not 2xx, so the same change is reverted.
#[tokio::test(flavor = "multi_thread")]
async fn qc_forward_auth_host_with_health_check_is_kept_under_caddy_as_under_edge() {
let auth = ianitor_testkit::authelia::MockAuthelia::start().await;
let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url());
let Some(ce) = qc_env_with_caddy_site(site).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| {
json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi",
"auth": "forward-auth", "health_check": {"path": "/", "interval_secs": 1}}})
};
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await;
eprintln!("QC under edge: {}", rec["state"]);
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
eprintln!(
"QC under caddy: {} {}",
rec["state"], rec["reason"]["detail"]
);
assert_eq!(rec["state"], "kept", "{rec}");
}
/// QC r2: control nudges Caddy (device list, renewed certificates) by POST /load of the
/// unchanged caddy.json. Caddy skips a load of an identical config, so the files it read at
/// start are not read again.
#[tokio::test(flavor = "multi_thread")]
async fn qc_reloading_the_same_caddy_json_rereads_the_certificate_files() {
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})))
.await;
assert_eq!(rec["state"], "kept");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
assert_eq!(visit(env, ce.https, "a.test").await, 200);
// Replace a.test's certificate with one from a root the client does not trust.
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = ianitor_core::pki::create_root(now).unwrap();
let k = ianitor_core::pki::generate_key().unwrap();
let csr =
ianitor_core::pki::intermediate_csr(&k, ianitor_core::pki::INTERMEDIATE_CN).unwrap();
let int = ianitor_core::pki::Intermediate::new(
&ianitor_core::pki::sign_intermediate(&root, &rk, &csr, now).unwrap(),
k,
)
.unwrap();
let leaf = ianitor_core::pki::issue_server(&int, "a.test", now).unwrap();
std::fs::write(env.dir.join("certs/a.test.key"), &leaf.key_pem).unwrap();
std::fs::write(env.dir.join("certs/a.test.crt"), &leaf.chain_pem).unwrap();
// What control does in devices_changed / reload_serving_engine under Caddy.
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
let r = ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &text).await;
assert!(r.is_ok(), "{r:?}");
let after = visit(env, ce.https, "a.test").await;
eprintln!(
"QC after same-config load: visit = {after} (200 = old certificate still served)"
);
assert_ne!(
after, 200,
"Caddy still serves the certificate it read at start"
);
}
/// QC r2: a control crash with a trial loaded into Caddy. Edge reverts an unconfirmed trial
/// by itself; Caddy has no deadline, so the unverified config keeps serving while control
/// is down.
#[tokio::test(flavor = "multi_thread")]
async fn qc_control_crash_mid_trial_under_caddy_leaves_the_last_good_config() {
let Some(mut ce) = env_with_caddy().await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let host = |h: &str| json!({"host": {"hostname": h, "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
assert_eq!(
ce.env
.apply("POST", "/api/v1/hosts", Some(host("a.test")))
.await["state"],
"kept"
);
let r = ce
.env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(&ce.env, "caddy").await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(host("b.test")))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let st = ce.env.wait_control_exit(Duration::from_secs(30));
eprintln!("QC control exit: {st:?}");
assert!(st.is_some());
// Longer than edge's trial deadline would allow.
tokio::time::sleep(Duration::from_secs(15)).await;
let during = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test through Caddy 15 s after the crash, control down: {during}");
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(3)).await;
let after = visit(&ce.env, ce.https, "b.test").await;
eprintln!("QC b.test after control restarted (recovery): {after}");
assert_ne!(after, 200, "recovery must revert the trial");
assert_ne!(
during, 200,
"Caddy served the unconfirmed trial while control was down"
);
}
// ---------------------------------------------------------------- fix round 2
/// Like `env_with_caddy`, with a chosen watch, and with or without the Caddy trial guard
/// (the fake systemctl starts it next to Caddy unless `fake/no-guard` exists).
async fn caddy_env(watch_secs: u64, guard: bool) -> Option<CaddyEnv> {
let caddy = ianitor_testkit::proc::require_binary("caddy")?;
let mut env = Env::new(EnvSpec {
watch_secs,
..Default::default()
})
.await;
let fake = env.dir.join("fake/systemctl");
std::fs::create_dir_all(env.dir.join("fake/units")).unwrap();
std::fs::create_dir_all(env.dir.join("caddy-state")).unwrap();
if !guard {
std::fs::write(env.dir.join("fake/no-guard"), "").unwrap();
}
std::fs::write(&fake, fake_with_caddy(&env.dir.join("."), &caddy)).unwrap();
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap();
let http = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let https = ianitor_testkit::proc::local(ianitor_testkit::proc::free_port());
let d = |p: &str| env.dir.join(p).display().to_string();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n\n[compile_caddy]\nhttp_listen = \"{http}\"\nhttps_listen = \"{https}\"\ncert_dir = \"{}\"\nstate_dir = \"{}\"\naccess_log = \"{}\"\ncaddy_credentials_dir = \"{}\"\ncaddy_admin_socket = \"{}\"\n",
d("engine"),
fake.display(),
d("certs"),
d("caddy-state"),
d("logs/caddy-access.log"),
d("creds"),
d("caddy/admin.sock"),
);
std::fs::write(env.config_path(), text).unwrap();
env.start_control(None);
Some(CaddyEnv { env, https })
}
async fn to_caddy_with(env: &Env, echo: &ianitor_testkit::upstream::Echo) {
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
async fn wait_state(env: &Env, id: &str, state: &str) {
let deadline = Instant::now() + Duration::from_secs(20);
loop {
let r = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
if r.json["state"] == state {
return;
}
assert!(Instant::now() < deadline, "never {state}: {}", r.text);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
fn b_host(echo: &ianitor_testkit::upstream::Echo) -> Value {
json!({"host": {"hostname": "b.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}})
}
/// QC round 2, M2: something reloads Caddy during a trial's watch (a device change, a
/// restart of caddy-fallback). The trial is gone from Caddy; the watch must notice and
/// treat it as interrupted, not report it kept while Caddy serves the old config.
#[tokio::test(flavor = "multi_thread")]
async fn a_reload_of_caddy_during_the_watch_is_noticed() {
let Some(ce) = caddy_env(8, true).await else {
return;
};
let env = &ce.env;
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(env, &echo).await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
assert_eq!(
visit(env, ce.https, "b.test").await,
200,
"the trial serves"
);
// What a device change or a Caddy restart does: Caddy gets the last good config.
let good = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&env.dir.join("caddy/admin.sock"), &good)
.await
.unwrap();
let rec = env.wait_apply(&id).await;
assert_ne!(rec["state"], "kept", "{rec}");
assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost", "{rec}");
let now_good = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap();
assert!(!now_good.contains("b.test"), "{now_good}");
assert_ne!(visit(env, ce.https, "b.test").await, 200);
}
/// QC round 2, minor 3: the `watching` crash point under Caddy.
#[tokio::test(flavor = "multi_thread")]
async fn a_crash_while_watching_under_caddy_is_reverted() {
let Some(mut ce) = caddy_env(4, true).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("watching"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
ce.env.start_control(None);
let rec = ce.env.wait_apply(&id).await;
assert_eq!(rec["state"], "reverted", "{rec}");
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC round 2, B2 (a): what systemd runs after control stops (ExecStopPost): with an
/// unconfirmed trial in the journal, Caddy goes back to the last good caddy.json at once,
/// without waiting for the guard's deadline.
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_after_a_crash_loads_the_last_good_config() {
let Some(mut ce) = caddy_env(3, false).await else {
return;
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
to_caddy_with(&ce.env, &echo).await;
ce.env.kill_control();
ce.env.start_control(Some("trial_loaded"));
let r = ce
.env
.call("POST", "/api/v1/hosts", Some(b_host(&echo)))
.await;
assert_eq!(r.status, 202, "{}", r.text);
assert!(ce.env.wait_control_exit(Duration::from_secs(30)).is_some());
assert_eq!(
visit(&ce.env, ce.https, "b.test").await,
200,
"the trial was loaded"
);
let config = ce.env.config_path();
let revert = || {
std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control"))
.args(["caddy-revert", "--config"])
.arg(&config)
.output()
.unwrap()
};
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_ne!(visit(&ce.env, ce.https, "b.test").await, 200);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
// After recovery there is no trial: it changes nothing and succeeds.
ce.env.start_control(None);
tokio::time::sleep(Duration::from_secs(2)).await;
let out = revert();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
}