// 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/. //! Switching the engine at runtime (ROADMAP §3, §4; G18) with a fake `systemctl`: the engine //! file is written first, the old unit stopped and the new one started; while Caddy serves, //! changes and share links wait; a switch whose target does not come up goes back. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #[cfg(unix)] mod common; // On Windows this target has nothing to run: it shows as one *ignored* test, never as a // pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] #[ignore = "needs Linux: run it in WSL2, see CLAUDE.md"] fn needs_linux() {} #[cfg(unix)] mod unix { use std::time::{Duration, Instant}; use crate::common::{Env, EnvSpec}; use serde_json::{Value, json}; /// Records every call; `is-active` answers from marker files; a unit named in /// `fail-start` cannot start. const FAKE: &str = r#"#!/bin/sh dir="$(dirname "$0")/units" mkdir -p "$dir" [ "$1" = "--no-ask-password" ] && shift echo "$*" >> "$dir/../calls.log" case "$1" in start) if grep -qx "$2" "$dir/../fail-start" 2>/dev/null; then exit 1; fi; touch "$dir/$2" ;; stop) rm -f "$dir/$2" ;; restart) touch "$dir/$2" ;; is-active) [ "$2" = "--quiet" ] && shift; [ -e "$dir/$2" ] ;; *) exit 2 ;; esac "#; async fn env() -> Env { let mut env = Env::new(EnvSpec::default()).await; let fake = env.dir.join("fake/systemctl"); std::fs::create_dir_all(env.dir.join("fake/units")).unwrap(); std::fs::write(&fake, FAKE).unwrap(); { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); } // Edge runs now. std::fs::write(env.dir.join("fake/units/ianitor-edge.service"), "").unwrap(); let text = std::fs::read_to_string(env.config_path()).unwrap() + &format!( "\n[engine]\nfile = \"{}\"\nsystemctl = \"{}\"\n", env.dir.join("engine").display(), fake.display() ); std::fs::write(env.config_path(), text).unwrap(); env.start_control(None); env } fn calls(env: &Env) -> Vec { std::fs::read_to_string(env.dir.join("fake/calls.log")) .unwrap_or_default() .lines() .map(str::to_owned) .filter(|l| !l.starts_with("is-active")) .collect() } async fn wait_engine(env: &Env, running: &str) -> Value { let deadline = Instant::now() + Duration::from_secs(30); loop { let r = env.call("GET", "/api/v1/engine", None).await; // On a loaded machine a switch takes longer: stay under the API's 120 calls a // minute rather than fail on a 429. if r.status == 429 { tokio::time::sleep(Duration::from_secs(1)).await; continue; } assert_eq!(r.status, 200, "{}", r.text); if r.json["state"] == "running" && r.json["running"] == running { return r.json; } if Instant::now() > deadline { panic!("engine is {}\n{}", r.text, env.control_log()); } tokio::time::sleep(Duration::from_millis(300)).await; } } #[tokio::test(flavor = "multi_thread")] async fn switch_to_caddy_and_back() { let env = env().await; let echo = ianitor_testkit::upstream::Echo::start("app").await; let host = json!({"host": {"hostname": "a.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "share_links": true}}); let rec = env.apply("POST", "/api/v1/hosts", Some(host)).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); let e = wait_engine(&env, "caddy").await; assert!(e["last_error"].is_null(), "{e}"); assert_eq!( calls(&env), ["stop ianitor-edge.service", "start caddy-fallback.service"] ); assert_eq!( std::fs::read_to_string(env.dir.join("engine")).unwrap(), "caddy" ); // Caddy starts from the current tree. let caddy = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap(); assert!(caddy.contains("a.test")); // While Caddy serves: changes go on (changes_apply_while_caddy_serves), share links wait. let ov = env.call("GET", "/api/v1/overview", None).await; assert_eq!(ov.json["engine"]["running"], "caddy", "{}", ov.text); assert!(ov.json["paused"].is_null(), "{}", ov.text); assert_eq!(ov.json["site"]["share_links_available"], false); let share = env .call( "POST", "/api/v1/hosts/a.test/share-links", Some(json!({"path_prefix": "/", "expires_in_s": 86400})), ) .await; assert_eq!(share.status, 409, "{}", share.text); assert_eq!(share.json["error"]["code"], "share.engine_caddy"); // The same target again is refused. let again = env .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) .await; assert_eq!(again.status, 409); assert_eq!(again.json["error"]["code"], "engine.same"); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "pingora"}))) .await; assert_eq!(r.status, 202, "{}", r.text); wait_engine(&env, "pingora").await; assert_eq!( calls(&env)[2..], ["stop caddy-fallback.service", "start ianitor-edge.service"] ); assert_eq!( std::fs::read_to_string(env.dir.join("engine")).unwrap(), "pingora" ); let ov = env.call("GET", "/api/v1/overview", None).await; assert!(ov.json["paused"].is_null(), "{}", ov.text); let share = env .call( "POST", "/api/v1/hosts/a.test/share-links", Some(json!({"path_prefix": "/", "expires_in_s": 86400})), ) .await; assert_eq!(share.status, 201, "{}", share.text); } #[tokio::test(flavor = "multi_thread")] async fn a_target_that_does_not_start_switches_back() { let env = env().await; std::fs::write(env.dir.join("fake/fail-start"), "caddy-fallback.service\n").unwrap(); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) .await; assert_eq!(r.status, 202, "{}", r.text); // It ends where it started, and says why. let deadline = Instant::now() + Duration::from_secs(30); let e = loop { let r = env.call("GET", "/api/v1/engine", None).await; if r.json["state"] == "running" && !r.json["last_error"].is_null() { break r.json; } assert!(Instant::now() < deadline, "{}", r.text); tokio::time::sleep(Duration::from_millis(100)).await; }; assert_eq!(e["running"], "pingora"); assert_eq!(e["last_error"]["code"], "engine.switch_failed"); assert_eq!( calls(&env), [ "stop ianitor-edge.service", "start caddy-fallback.service", "stop caddy-fallback.service", "start ianitor-edge.service" ] ); assert_eq!( std::fs::read_to_string(env.dir.join("engine")).unwrap(), "pingora" ); // Changes go on as before. let ov = env.call("GET", "/api/v1/overview", None).await; assert!(ov.json["paused"].is_null(), "{}", ov.text); } #[tokio::test(flavor = "multi_thread")] async fn without_engine_settings_nothing_switches() { let mut env = Env::new(EnvSpec::default()).await; env.start_control(None); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) .await; assert_eq!(r.status, 409, "{}", r.text); assert_eq!(r.json["error"]["code"], "engine.unmanaged"); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "nginx"}))) .await; assert_eq!(r.status, 409); let e = env.call("GET", "/api/v1/engine", None).await; assert_eq!(e.json["switchable"], false); } /// The fake systemctl that really runs Caddy for caddy-fallback.service (edge runs in this /// process and keeps its own ports; Caddy gets others through [compile_caddy]). fn fake_with_caddy(dir: &std::path::Path, caddy: &std::path::Path) -> String { format!( r#"#!/bin/sh dir="{d}/fake/units" mkdir -p "$dir" [ "$1" = "--no-ask-password" ] && shift echo "$*" >> "{d}/fake/calls.log" case "$1:$2" in start:caddy-fallback.service) # Like systemd: starting a unit that is active does nothing. [ -e "$dir/$2" ] && exit 0 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" # 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 # fake/start-delay: Caddy serves at once, the unit reports active only later (a switch # that is still in wait_serving while Caddy has read its files). if [ -f "{d}/fake/start-delay" ]; then (sleep "$(cat "{d}/fake/start-delay")"; touch "$dir/$2") >/dev/null 2>&1 & else touch "$dir/$2" fi ;; stop:caddy-fallback.service) # fake/stop-delay and fake/fail-stop: a slow stop, and one that fails (Caddy keeps running). [ -f "{d}/fake/stop-delay" ] && sleep "$(cat "{d}/fake/stop-delay")" grep -qx "$2" "{d}/fake/fail-stop" 2>/dev/null && exit 1 [ -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" ] ;; *) exit 2 ;; esac "#, d = dir.display(), c = caddy.display(), g = env!("CARGO_BIN_EXE_ianitor-control"), ) } struct CaddyEnv { env: Env, https: std::net::SocketAddr, } impl Drop for CaddyEnv { fn drop(&mut self) { 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(); } } } } async fn env_with_caddy() -> Option { let caddy = ianitor_testkit::proc::require_binary("caddy")?; let mut env = Env::new(EnvSpec::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 }) } async fn visit(env: &Env, at: std::net::SocketAddr, host: &str) -> u16 { match ianitor_testkit::client::https( at, host, env.ca.roots(), &ianitor_testkit::client::Req::get(host, "/"), ) .await { Ok(r) => r.status, Err(_) => 0, } } /// Mark, 2026-11-08: changes keep working while Caddy serves. An apply is loaded into /// Caddy, watched through it, and kept, or reverted by loading the previous caddy.json; /// Undo works the same way; share links stay off. Switching back brings edge up to date. #[tokio::test(flavor = "multi_thread")] async fn changes_apply_while_caddy_serves() { let Some(ce) = env_with_caddy().await else { return; }; let env = &ce.env; let echo = ianitor_testkit::upstream::Echo::start("app").await; let host = |h: &str, up: String| json!({"host": {"hostname": h, "upstreams": [up], "tls": "domi", "auth": "none", "share_links": true}}); assert_eq!( env.apply("POST", "/api/v1/hosts", Some(host("a.test", echo.url()))) .await["state"], "kept" ); 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; assert_eq!( visit(env, ce.https, "a.test").await, 200, "{}", env.control_log() ); // No pause while Caddy serves. let ov = env.call("GET", "/api/v1/overview", None).await; assert!(ov.json["paused"].is_null(), "{}", ov.text); // Kept through Caddy. let rec = env .apply("POST", "/api/v1/hosts", Some(host("b.test", echo.url()))) .await; assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); assert_eq!(visit(env, ce.https, "b.test").await, 200); // A broken change is reverted by loading the previous caddy.json. let broken = json!({"host": {"hostname": "c.test", "upstreams": [format!("http://127.0.0.1:{}", ianitor_testkit::upstream::closed_port())], "tls": "domi", "auth": "none", "health_check": {"path": "/", "interval_secs": 1}}}); let rec = env.apply("POST", "/api/v1/hosts", Some(broken)).await; assert_eq!(rec["state"], "reverted", "{rec}\n{}", env.control_log()); let caddy_json = std::fs::read_to_string(env.dir.join("caddy/caddy.json")).unwrap(); assert!(!caddy_json.contains("c.test")); assert_eq!(visit(env, ce.https, "a.test").await, 200); assert_eq!(visit(env, ce.https, "b.test").await, 200); // Undo (removes b.test) works under Caddy too. let u = env.call("GET", "/api/v1/undo", None).await; let target = u.json["target"]["change_id"].as_str().unwrap().to_owned(); let rec = env .apply( "POST", "/api/v1/undo", Some(json!({"target_change_id": target})), ) .await; assert_eq!(rec["state"], "kept", "{rec}"); assert_ne!(visit(env, ce.https, "b.test").await, 200); // Share links stay off. let s = env .call( "POST", "/api/v1/hosts/a.test/share-links", Some(json!({"path_prefix": "/", "expires_in_s": 86400})), ) .await; assert_eq!(s.status, 409, "{}", s.text); assert_eq!(s.json["error"]["code"], "share.engine_caddy"); // Back to Pingora: edge serves what was kept under Caddy. let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "pingora"}))) .await; assert_eq!(r.status, 202, "{}", r.text); wait_engine(env, "pingora").await; let edge = env.edge.as_ref().unwrap(); assert_eq!(visit(env, edge.https, "a.test").await, 200); assert_ne!(visit(env, edge.https, "b.test").await, 200); let edge_json = std::fs::read_to_string(env.dir.join("edge/edge.json")).unwrap(); assert!( edge_json.contains("a.test") && !edge_json.contains("b.test") && !edge_json.contains("c.test") ); } // ---------------------------------------------------------------- QC round 2 async fn qc_env_with_caddy_site(site: String) -> Option { 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 { 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(250)).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); } /// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads /// caddy.json (must-revalidate); the revoked device must no longer get in, the newly /// allowed one must. #[tokio::test(flavor = "multi_thread")] async fn qc_device_revoked_under_caddy_is_refused() { use ianitor_core::pki; use ianitor_testkit::client::{self, ClientCert, Req}; let Some(ce) = env_with_caddy().await else { return; }; let env = &ce.env; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as i64; let (root, rk) = pki::create_root(now).unwrap(); let k = pki::generate_key().unwrap(); let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); let int = pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k) .unwrap(); let phone = pki::issue_device(&int, "phone", now).unwrap(); let laptop = pki::issue_device(&int, "laptop", now).unwrap(); std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap(); std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap(); let cc = |d: &pki::Issued| ClientCert { chain_pem: d.chain_pem.clone(), key_pem: d.key_pem.clone(), tls12_only: false, }; let echo = ianitor_testkit::upstream::Echo::start("app").await; let rec = env .apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}}))) .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); wait_engine(env, "caddy").await; let visit_as = |d: &pki::Issued| { let c = cc(d); let roots = env.ca.roots(); async move { match client::https_with_cert( ce.https, "d.test", roots, &c, &Req::get("d.test", "/"), ) .await { Ok(r) => r.status, Err(_) => 0, } } }; let before = visit_as(&phone).await; eprintln!("QC phone under Caddy before revocation: {before}"); assert_eq!(before, 200); // Revoke the phone, allow the laptop; tell Caddy the way control does. std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap(); let sock = env.dir.join("caddy/admin.sock"); let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap(); ianitor_control::caddy_link::load(&sock, &text) .await .unwrap(); assert!( ianitor_control::caddy_link::runs(&sock, &text) .await .unwrap() ); let phone_after = visit_as(&phone).await; let laptop_after = visit_as(&laptop).await; eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}"); assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy"); assert_eq!( laptop_after, 200, "newly allowed laptop is not let in under Caddy" ); } // ---------------------------------------------------------------- fix round 3 /// A control with the Domi CA, an intermediate signed by a test root, one device issued /// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves. struct PkiEnv { ce: CaddyEnv, roots: std::sync::Arc, device_id: String, device: ianitor_testkit::client::ClientCert, } async fn pki_env(watch_secs: u64, caddy: bool) -> Option { use ianitor_core::pki; let ce = caddy_env(watch_secs, true).await?; let mut ce = ce; let env = &mut ce.env; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as i64; let (root_pem, root_key) = pki::create_root(now).unwrap(); std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap(); std::fs::write( env.dir.join("creds/pki-password"), "round-three-password-123", ) .unwrap(); let text = std::fs::read_to_string(env.config_path()).unwrap() + &format!( "\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n", env.dir.join("offline-root.crt").display() ); std::fs::write(env.config_path(), text).unwrap(); env.kill_control(); env.start_control(None); let cli = |env: &Env, args: &[&str]| { env.command() .args(args) .arg("--config") .arg(env.config_path()) .output() .unwrap() }; // The intermediate, signed offline. let r = env .call( "POST", "/api/v1/certs/intermediate/renewal", Some(json!({})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap(); std::fs::write(env.dir.join("int.crt"), signed).unwrap(); let int_path = env.dir.join("int.crt").display().to_string(); let out = cli(env, &["pki", "install", &int_path]); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); // One device. let r = env .call( "POST", "/api/v1/certs/devices", Some(json!({"name": "phone", "kind": "phone"})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let code = r.json["match_code"].as_str().unwrap().to_owned(); let out = cli(env, &["pki", "approve", &code]); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); let devices: Value = serde_json::from_str( &std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(), ) .unwrap(); let d = &devices[0]; let device_id = d["id"].as_str().unwrap().to_owned(); let sealed = std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key"))) .unwrap(); let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap(); let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap(); let device = ianitor_testkit::client::ClientCert { chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()), key_pem: key.serialize_pem(), tls12_only: false, }; let mut store = rustls::RootCertStore::empty(); store .add(rustls_pki_types::CertificateDer::from( pki::chain_der(&root_pem).unwrap().remove(0), )) .unwrap(); let echo = ianitor_testkit::upstream::Echo::start("app").await; let rec = env .apply( "POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})), ) .await; assert_eq!(rec["state"], "kept", "{rec}"); // The echo upstream must outlive this function: keep it running in the background. std::mem::forget(echo); if caddy { 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; } Some(PkiEnv { ce, roots: std::sync::Arc::new(store), device_id, device, }) } impl PkiEnv { async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 { match ianitor_testkit::client::https_with_cert( at, "d.test", self.roots.clone(), &self.device, &ianitor_testkit::client::Req::get("d.test", "/"), ) .await { Ok(r) => r.status, Err(_) => 0, } } fn serving(&self, caddy: bool) -> std::net::SocketAddr { if caddy { self.ce.https } else { self.ce.env.edge.as_ref().unwrap().https } } } /// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE /// answers at once, the allow list is on disk at once, and the device is refused within /// edge's backstop window although an apply is still watching. async fn revoke_during_a_watch(caddy: bool) { let Some(p) = pki_env(6, caddy).await else { return; }; let env = &p.ce.env; let at = p.serving(caddy); assert_eq!(p.visit_as_device(at).await, 200, "the device gets in"); let echo = ianitor_testkit::upstream::Echo::start("app").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; let t = Instant::now(); let d = env .call( "DELETE", &format!("/api/v1/certs/devices/{}", p.device_id), None, ) .await; let took = t.elapsed(); assert_eq!(d.status, 204, "{}", d.text); assert!( took < Duration::from_millis(1500), "the DELETE waited {took:?}" ); let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); let listed = p .device .chain_pem .split("-----END CERTIFICATE-----") .next() .unwrap(); assert!( !allow.contains(listed.trim()), "the revoked device is still on the list" ); if caddy { // Caddy keeps the trial until the apply ends; then the device is out at once. let rec = env.wait_apply(&id).await; assert_eq!(rec["state"], "kept", "{rec}"); assert_ne!( p.visit_as_device(at).await, 200, "revoked device still gets in under Caddy" ); } else { let deadline = Instant::now() + Duration::from_secs(6); while p.visit_as_device(at).await == 200 { assert!( Instant::now() < deadline, "revoked device still gets in under Pingora" ); tokio::time::sleep(Duration::from_millis(250)).await; } let rec = env.wait_apply(&id).await; assert_eq!(rec["state"], "kept", "{rec}"); } let c = env.call("GET", "/api/v1/certs", None).await; assert!(c.json["devices_problem"].is_null(), "{}", c.text); } #[tokio::test(flavor = "multi_thread")] async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() { revoke_during_a_watch(false).await; } #[tokio::test(flavor = "multi_thread")] async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() { revoke_during_a_watch(true).await; } /// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and /// caddy-revert succeeds (the unit must not show failed). #[tokio::test(flavor = "multi_thread")] async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() { let mut env = env().await; env.kill_control(); std::fs::write( env.dir.join("state/caddy-trial.json"), r#"{"apply_id":"ch_x","deadline":1}"#, ) .unwrap(); let out = env .command() .args(["caddy-revert", "--config"]) .arg(env.config_path()) .output() .unwrap(); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); assert!(!env.dir.join("state/caddy-trial.json").exists()); } // ---------------------------------------------------------------- fix round 4 async fn engine_view(env: &Env) -> Value { env.call("GET", "/api/v1/engine", None).await.json } async fn wait_switching(env: &Env) { let deadline = Instant::now() + Duration::from_secs(10); while engine_view(env).await["state"] != "switching" { assert!(Instant::now() < deadline, "the switch never started"); tokio::time::sleep(Duration::from_millis(200)).await; } } async fn wait_switch_over(env: &Env) -> Value { let deadline = Instant::now() + Duration::from_secs(40); loop { let e = engine_view(env).await; if e["state"] == "running" { return e; } assert!(Instant::now() < deadline, "the switch never ended: {e}"); tokio::time::sleep(Duration::from_millis(300)).await; } } async fn revoke(env: &Env, id: &str) { let t = Instant::now(); let d = env .call("DELETE", &format!("/api/v1/certs/devices/{id}"), None) .await; assert_eq!(d.status, 204, "{}", d.text); assert!( t.elapsed() < Duration::from_secs(3), "the DELETE waited {:?}", t.elapsed() ); } async fn refused_soon(p: &PkiEnv, at: std::net::SocketAddr, what: &str) { let deadline = Instant::now() + Duration::from_secs(4); while p.visit_as_device(at).await == 200 { assert!(Instant::now() < deadline, "{what}"); tokio::time::sleep(Duration::from_millis(250)).await; } } /// QC round 4, case A: a device is revoked while a switch to Caddy is still waiting for /// the unit, after Caddy has already read the allow list. The switch ends by telling /// Caddy again, so the device is refused once Caddy serves. #[tokio::test(flavor = "multi_thread")] async fn a_revocation_during_a_switch_to_caddy_is_in_force_when_it_ends() { let Some(p) = pki_env(2, false).await else { return; }; let env = &p.ce.env; std::fs::write(env.dir.join("fake/start-delay"), "5").unwrap(); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))) .await; assert_eq!(r.status, 202, "{}", r.text); wait_switching(env).await; // Caddy is up and has read its files; the unit is not reported active yet. let deadline = Instant::now() + Duration::from_secs(5); while p.visit_as_device(p.ce.https).await != 200 { assert!(Instant::now() < deadline, "Caddy did not come up"); tokio::time::sleep(Duration::from_millis(200)).await; } assert_eq!(engine_view(env).await["state"], "switching"); revoke(env, &p.device_id).await; let e = wait_switch_over(env).await; assert_eq!(e["running"], "caddy", "{e}"); refused_soon( &p, p.ce.https, "the revoked device still gets in under Caddy after the switch", ) .await; } /// QC round 4, case B: a switch away from Caddy fails before Caddy is stopped, and a /// device was revoked meanwhile. The Caddy that kept serving must refuse it. #[tokio::test(flavor = "multi_thread")] async fn a_revocation_during_a_failed_switch_away_from_caddy_is_in_force() { let Some(p) = pki_env(2, true).await else { return; }; let env = &p.ce.env; assert_eq!( p.visit_as_device(p.ce.https).await, 200, "the device gets in" ); std::fs::write(env.dir.join("fake/stop-delay"), "4").unwrap(); std::fs::write(env.dir.join("fake/fail-stop"), "caddy-fallback.service\n").unwrap(); let r = env .call("POST", "/api/v1/engine", Some(json!({"target": "pingora"}))) .await; assert_eq!(r.status, 202, "{}", r.text); wait_switching(env).await; revoke(env, &p.device_id).await; let e = wait_switch_over(env).await; assert_eq!(e["running"], "caddy", "{e}"); assert!(!e["last_error"].is_null(), "{e}"); refused_soon( &p, p.ce.https, "the revoked device still gets in under the Caddy that kept serving", ) .await; // Nothing is left pending. let deadline = Instant::now() + Duration::from_secs(6); loop { let c = env.call("GET", "/api/v1/certs", None).await; if c.json["devices_problem"].is_null() { break; } assert!(Instant::now() < deadline, "{}", c.text); tokio::time::sleep(Duration::from_millis(500)).await; } } }