[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:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,4 +264,76 @@ mod unix {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that
|
||||
/// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() {
|
||||
use std::sync::Arc;
|
||||
let echo = Echo::start("app").await;
|
||||
let p = pki();
|
||||
let (phone, phone_pem) = device(&p, "phone");
|
||||
let edge = setup(&echo, &p, &[&phone_pem]).await;
|
||||
let roots = edge.roots();
|
||||
let req = Req::get("locked.test", "/");
|
||||
let mut failures = Vec::new();
|
||||
let mut poisoned = 0;
|
||||
for i in 0..40 {
|
||||
let addr = edge.https;
|
||||
let r2 = roots.clone();
|
||||
let failed = tokio::task::spawn_blocking(move || {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let mut cfg = rustls::ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(r2)
|
||||
.with_no_client_auth();
|
||||
cfg.alpn_protocols = vec![b"foo".to_vec()];
|
||||
let mut conn = rustls::ClientConnection::new(
|
||||
Arc::new(cfg),
|
||||
rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut sock = std::net::TcpStream::connect(addr).unwrap();
|
||||
sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut r = Ok((0, 0));
|
||||
for _ in 0..5 {
|
||||
r = conn.complete_io(&mut sock);
|
||||
if r.is_err() || !conn.is_handshaking() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
r.is_err()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if failed {
|
||||
poisoned += 1;
|
||||
}
|
||||
match client::https_with_cert(
|
||||
edge.https,
|
||||
"locked.test",
|
||||
roots.clone(),
|
||||
&tls12(&phone),
|
||||
&req,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) if r.status == 200 => {}
|
||||
other => failures.push(format!("{i}: {other:?}")),
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"QC poison handshakes that failed: {poisoned}/40; device failures: {}",
|
||||
failures.len()
|
||||
);
|
||||
assert_eq!(poisoned, 40, "the poison handshake must fail");
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"{} of 40 TLS 1.2 device handshakes failed: {:?}",
|
||||
failures.len(),
|
||||
failures.first()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user