diff --git a/tests/diff/Cargo.toml b/tests/diff/Cargo.toml index 0689194..bb43b75 100644 --- a/tests/diff/Cargo.toml +++ b/tests/diff/Cargo.toml @@ -15,5 +15,8 @@ tokio.workspace = true serde_json.workspace = true rustls.workspace = true +[dev-dependencies] +ianitor-control = { path = "../../crates/control" } + [lints.rust] unsafe_code = "forbid" diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index a2297aa..ad29998 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -37,6 +37,9 @@ pub struct Env { pub dir: TempDir, pub ca: TestCa, pub model: Model, + /// The routes behind `model`: the site file and `(hosts/.toml, contents)`. + pub site: String, + pub hosts: Vec<(String, String)>, _upstreams: (Echo, Echo, Echo, Echo, WsEcho, MockAuthelia), } @@ -146,6 +149,8 @@ impl Env { dir, ca, model, + site, + hosts, _upstreams: (app, sick, rr_a, rr_b, ws, auth), } } @@ -877,10 +882,33 @@ fn short(o: &Observation) -> Observation { o } +/// The host a case is about (its SNI, or the Host header of plain-HTTP cases). +pub fn case_host(case: &Case) -> String { + match &case.action { + Action::Https { sni, .. } | Action::Websocket { sni, .. } => (*sni).to_owned(), + Action::Http { req } => req + .headers + .iter() + .find(|(n, _)| n == "host") + .map(|(_, v)| v.to_ascii_lowercase()) + .unwrap_or_default(), + } +} + /// Send every case to both targets, one after the other (round robin needs a stable order). pub async fn run_corpus(ianitor: &Target, caddy: &Target, roots: Arc) -> Report { + run_cases(ianitor, caddy, roots, |_| true).await +} + +/// Like [`run_corpus`], for the cases `keep` selects. +pub async fn run_cases( + ianitor: &Target, + caddy: &Target, + roots: Arc, + keep: impl Fn(&Case) -> bool, +) -> Report { let mut outcomes = Vec::new(); - for case in corpus() { + for case in corpus().into_iter().filter(|c| keep(c)) { let i = run_case(&case, ianitor, roots.clone()).await; let c = run_case(&case, caddy, roots.clone()).await; outcomes.push(Outcome { diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs new file mode 100644 index 0000000..945ea38 --- /dev/null +++ b/tests/diff/tests/apply_sequence.rs @@ -0,0 +1,238 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The differential suite after every apply (ROADMAP ยง6 phase 2, "Done"): control applies a +//! sequence of changes to a routes repository; after each one, Ianitor runs the edge config +//! control wrote and Caddy runs the Caddy JSON control wrote, and the corpus (the cases for +//! hosts that exist at that point) must get the same answers from both. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy); run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::net::SocketAddr; + use std::path::PathBuf; + use std::time::{Duration, Instant}; + + use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes}; + use ianitor_control::engine::{Change, Control}; + use ianitor_control::hostspec::HostSpec; + use ianitor_control::repo::{Repo, RouteTree}; + use ianitor_diff::{Env, case_host, run_cases, settle, start_caddy, start_edge}; + use ianitor_testkit::proc::require_binary; + + fn compile_of(o: &ianitor_core::compile::CompileOptions) -> Compile { + Compile { + http_listen: o.http_listen, + https_listen: o.https_listen, + cert_dir: o.cert_dir.clone(), + state_dir: o.state_dir.clone(), + access_log: o.access_log.clone(), + caddy_credentials_dir: o.caddy_credentials_dir.clone(), + caddy_admin: o.caddy_admin, + } + } + + fn wait_free(addrs: &[SocketAddr]) { + let deadline = Instant::now() + Duration::from_secs(15); + while addrs + .iter() + .any(|a| std::net::TcpStream::connect(a).is_ok()) + && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(50)); + } + } + + async fn apply(ctl: &Control, change: Change) { + let rec = ctl + .submit(change, None, "diff") + .unwrap_or_else(|f| panic!("{f:?}")); + let deadline = Instant::now() + Duration::from_secs(30); + loop { + let r = ctl.record(&rec.id).unwrap(); + if !r.is_active() { + assert_eq!(r.state, "kept", "{} : {:?}", r.summary, r.reason); + return; + } + assert!(Instant::now() < deadline, "apply did not finish"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + + fn spec(env: &Env, name: &str) -> HostSpec { + let (_, text) = env + .hosts + .iter() + .find(|(p, _)| p == &format!("hosts/{name}.toml")) + .unwrap(); + HostSpec::from_toml(text).unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_diff_suite_is_green_after_every_apply() { + let Some(caddy_bin) = require_binary("caddy") else { + return; + }; + let env = Env::start().await; + let edge_opts = env.options("edge"); + let caddy_opts = env.options("caddy"); + let d = |p: &str| env.dir.join(p); + for p in ["ctl-state", "ctl-edge", "ctl-caddy"] { + std::fs::create_dir_all(d(p)).unwrap(); + } + let cfg = Config { + listen: "127.0.0.1:1".parse().unwrap(), + allowed_hosts: Vec::new(), + state_dir: d("ctl-state"), + credentials_dir: Some(d("creds")), + git: PathBuf::from("git"), + watch_secs: 1, + watch_every_secs: 1, + trial_margin_secs: 1, + health_poll_secs: 1, + routes: Routes { + repo: d("routes.git"), + branch: "main".into(), + remote: None, + remote_name: "Gitea".into(), + push_username: "ianitor".into(), + push_credential: None, + }, + // No edge attached: control writes both files, and each file is tested below. + edge: Edge { + config: d("ctl-edge/edge.json"), + trial: None, + admin_socket: None, + share_revocations: d("ctl-edge/share-revocations.json"), + }, + caddy: Caddy { + config: d("ctl-caddy/caddy.json"), + }, + compile: compile_of(&edge_opts), + compile_caddy: Some(compile_of(&caddy_opts)), + }; + + // Start from the site file and every host except three; then a sequence of applies + // ends at the full diff routes. + let later = ["hc.test", "hcdown.test", "rr.test"]; + let repo = Repo::open_seeded( + &cfg.git, + &cfg.routes.repo, + &cfg.state_dir, + "main", + &env.site, + ) + .unwrap(); + let head = repo.head_required().unwrap(); + let mut tree: RouteTree = (*repo.tree(&head).unwrap()).clone(); + for (p, c) in &env.hosts { + if !later.iter().any(|l| p == &format!("hosts/{l}.toml")) { + tree.files.insert(p.clone(), c.clone()); + } + } + let t = repo.write_tree(&tree, None).unwrap(); + let c = repo.commit(&t, &[&head], "Diff routes", "test").unwrap(); + repo.update_ref(&c, Some(&head)).unwrap(); + drop(repo); + + let ctl = Control::open(cfg.clone()).await.unwrap(); + tokio::spawn(ctl.clone().worker()); + + let steps: Vec<(&str, Option)> = vec![ + ("start", None), + ( + "add hc.test", + Some(Change::Put { + spec: spec(&env, "hc.test"), + create: true, + }), + ), + ( + "add hcdown.test", + Some(Change::Put { + spec: spec(&env, "hcdown.test"), + create: true, + }), + ), + ( + "remove nows.test", + Some(Change::Delete { + hostname: "nows.test".into(), + }), + ), + ( + "add rr.test", + Some(Change::Put { + spec: spec(&env, "rr.test"), + create: true, + }), + ), + ( + "restore nows.test", + Some(Change::Put { + spec: spec(&env, "nows.test"), + create: true, + }), + ), + ]; + let all_hosts: Vec = env + .model + .hosts() + .iter() + .map(|h| h.hostname.to_string()) + .collect(); + let mut ran = 0; + for (label, change) in steps { + if let Some(ch) = change { + apply(&ctl, ch).await; + } + let edge_text = std::fs::read_to_string(&cfg.edge.config).unwrap(); + let caddy_text = std::fs::read_to_string(&cfg.caddy.config).unwrap(); + let present: Vec = { + let v: serde_json::Value = serde_json::from_str(&edge_text).unwrap(); + v["hosts"] + .as_array() + .unwrap() + .iter() + .map(|h| h["hostname"].as_str().unwrap().to_owned()) + .collect() + }; + { + let ianitor = start_edge(&env, "ianitor", &edge_text); + let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_text); + settle().await; + // Cases for hosts that exist now, plus the ones about unknown hosts. + let report = run_cases(&ianitor, &caddy, env.roots(), |c| { + let h = case_host(c); + present.contains(&h) || !all_hosts.contains(&h) + }) + .await; + println!("{}", report.render(&format!("after: {label}"))); + assert!(report.outcomes.len() >= 5, "{label}: too few cases"); + assert!(report.mismatches().is_empty(), "{}", report.render(label)); + ran += report.outcomes.len(); + } + wait_free(&[ + edge_opts.https_listen, + edge_opts.http_listen, + caddy_opts.https_listen, + caddy_opts.http_listen, + ]); + } + // The last step is the full routes: every corpus case ran there. + assert!(ran > ianitor_diff::corpus().len()); + let records = ctl.records(); + assert_eq!(records.iter().filter(|r| r.state == "kept").count(), 5); + } +}