Files
ianitor/crates/control/tests/engine_switch.rs
T

762 lines
32 KiB
Rust

// 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;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux; run it in WSL2",
file!()
);
}
#[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<String> {
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;
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(100)).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)
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
touch "$dir/$2" ;;
stop:caddy-fallback.service)
[ -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<CaddyEnv> {
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<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);
}
}