diff --git a/Cargo.lock b/Cargo.lock index baa1c57..09ac86f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1005,6 +1005,15 @@ dependencies = [ [[package]] name = "ianitor-control" version = "0.1.0" +dependencies = [ + "ianitor-core", + "ianitor-edge", + "ianitor-testkit", + "ring", + "rustls", + "serde_json", + "tokio", +] [[package]] name = "ianitor-core" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 8b31672..1b60032 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -13,3 +13,12 @@ path = "src/main.rs" [lints] workspace = true + +[dev-dependencies] +ianitor-core.workspace = true +ianitor-edge.workspace = true +ianitor-testkit.workspace = true +tokio.workspace = true +serde_json.workspace = true +rustls.workspace = true +ring.workspace = true diff --git a/crates/control/tests/api.rs b/crates/control/tests/api.rs new file mode 100644 index 0000000..2f5b3d8 --- /dev/null +++ b/crates/control/tests/api.rs @@ -0,0 +1,523 @@ +// 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 API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are +//! rejected on every route and tokens never reach a log, an error or a state file; request +//! bodies are hostile input; the routes repository holds only host files; control only +//! listens on loopback; the OpenAPI document covers the API. + +#![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 (edge admin socket); run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::Duration; + + use crate::common::{Env, EnvSpec, host}; + use ianitor_testkit::more::tcp_raw; + use ianitor_testkit::upstream::Echo; + use serde_json::{Value, json}; + + /// Every (method, path) in the OpenAPI document, with path parameters filled in. + fn routes(doc: &Value) -> Vec<(String, String)> { + let mut out = Vec::new(); + for (path, item) in doc["paths"].as_object().unwrap() { + for method in ["get", "post", "put", "patch", "delete"] { + if item.get(method).is_some() { + let p = path + .replace("{hostname}", "a.test") + .replace("{id}", "x") + .replace("{change_id}", "x"); + out.push((method.to_uppercase(), p)); + } + } + } + out + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let doc = env.call("GET", "/api/v1/openapi.json", None).await; + assert_eq!(doc.status, 200, "{}", doc.text); + let routes = routes(&doc.json); + assert!(routes.len() >= 25, "{routes:?}"); + + // Make a second token through the API and revoke it, to test a revoked one too. + let made = env + .call("POST", "/api/v1/tokens", Some(json!({ "name": "script" }))) + .await; + assert_eq!(made.status, 201, "{}", made.text); + let revoked = made.json["token"].as_str().unwrap().to_owned(); + let rid = made.json["id"].as_str().unwrap().to_owned(); + assert_eq!( + env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None) + .await + .status, + 204 + ); + // A listing never shows values or hashes. + let list = env.call("GET", "/api/v1/tokens", None).await; + assert!( + !list.text.contains(&revoked) && !list.text.contains("sha256"), + "{}", + list.text + ); + assert!(!list.text.contains(&env.token)); + + let mut wrong = env.token.clone(); + wrong.pop(); + wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' }); + type Case = (String, Vec<(String, String)>, &'static str); + let cases: Vec = vec![ + ("no header".into(), vec![], "token.missing"), + ( + "not bearer".into(), + vec![("Authorization".into(), env.token.clone())], + "token.unknown", + ), + ( + "basic".into(), + vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())], + "token.unknown", + ), + ( + "one char off".into(), + vec![("Authorization".into(), format!("Bearer {wrong}"))], + "token.unknown", + ), + ( + "made up".into(), + vec![( + "Authorization".into(), + "Bearer ian_0000000000000000_xxxxxxxx".into(), + )], + "token.unknown", + ), + ( + "revoked".into(), + vec![("Authorization".into(), format!("Bearer {revoked}"))], + "token.revoked", + ), + ( + "empty bearer".into(), + vec![("Authorization".into(), "Bearer ".into())], + "token.unknown", + ), + // Identity headers do not authenticate (docs/ui-api.md G14). + ( + "remote-user".into(), + vec![ + ("Remote-User".into(), "mark".into()), + ("Remote-Groups".into(), "admins".into()), + ], + "token.missing", + ), + ]; + for (what, headers, code) in &cases { + let hs: Vec<(&str, &str)> = headers + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(); + for (method, path) in &routes { + let body = (method != "GET" && method != "DELETE").then(|| json!({})); + let r = env.call_with(method, path, &hs, body).await; + assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text); + assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}"); + assert!(r.json["error"]["message"].as_str().unwrap().len() > 10); + assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string()); + } + } + // Unknown paths are refused the same way, before anything else. + assert_eq!( + env.call_with("GET", "/api/v1/nope", &[], None).await.status, + 401 + ); + assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401); + + // A wrong Host header (DNS rebinding) is refused even with a good token. + let auth = format!("Bearer {}", env.token); + let raw = format!( + "GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n" + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 403, "{}", r.text()); + // A browser write without the UI header is refused (CSRF). + let r = env + .call_with( + "POST", + "/api/v1/hosts", + &[("Authorization", &auth), ("Origin", "https://evil.example")], + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let r = env + .call_with( + "POST", + "/api/v1/hosts", + &[ + ("Authorization", &auth), + ("Origin", "http://127.0.0.1"), + ("X-Ianitor-UI", "1"), + ], + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + env.wait_apply(r.json["apply"]["id"].as_str().unwrap()) + .await; + + // Exercise the rest with the good token, then look for any token anywhere. + for (method, path) in &routes { + if method == "GET" { + env.call(method, path, None).await; + } + } + tokio::time::sleep(Duration::from_millis(300)).await; + env.kill_control(); + let mut everything = env.control_log(); + for f in [ + "applies.json", + "push.json", + "share-links.json", + "journal.json", + ] { + everything.push_str(&env.file(&format!("state/{f}"))); + } + everything.push_str(&env.file("edge/edge.json")); + everything.push_str(&env.git(&["log", "-p", "--all"])); + let secret_part = |t: &str| t.rsplit('_').next().unwrap().to_owned(); + for t in [&env.token, &revoked] { + assert!( + !everything.contains(secret_part(t).as_str()), + "a token leaked" + ); + } + let stored = env.file("state/tokens.json"); + for t in [&env.token, &revoked] { + assert!( + !stored.contains(secret_part(t).as_str()), + "tokens.json holds a value, not a hash" + ); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(env.dir.join("state/tokens.json")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o077, 0, "tokens.json is private"); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn bodies_are_hostile_input() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let auth = format!("Bearer {}", env.token); + + // Unknown fields, at the top and inside the host. + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.body_unknown_field"); + assert_eq!(r.json["error"]["field"], "colour"); + let mut h = host("a.test", &good.url(), false); + h["upstream"] = json!("typo"); + let r = env + .call("POST", "/api/v1/hosts", Some(json!({ "host": h }))) + .await; + assert_eq!( + r.json["error"]["code"], "request.body_unknown_field", + "{}", + r.text + ); + // Wrong types never echo the value sent. + let r = env + .call( + "POST", + "/api/v1/tokens", + Some(json!({ "name": ["secret-ish-value"] })), + ) + .await; + assert_eq!(r.status, 400, "{}", r.text); + assert!(!r.text.contains("secret-ish-value"), "{}", r.text); + // Not JSON, wrong content type, too large. + let raw = format!( + "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{", + env.api + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 400, "{}", r.text()); + let raw = format!( + "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}", + env.api + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 415, "{}", r.text()); + let big = "x".repeat(70 * 1024); + let r = env + .call("POST", "/api/v1/tokens", Some(json!({ "name": big }))) + .await; + assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]); + + // Field errors come back as one envelope with codes and field paths. + let mut bad = host("a.test", "ftp://x", true); + bad["health_check"]["interval_secs"] = json!(0); + let r = env + .call("POST", "/api/v1/hosts", Some(json!({ "host": bad }))) + .await; + assert_eq!(r.status, 422, "{}", r.text); + let fields: Vec<&str> = r.json["errors"] + .as_array() + .unwrap() + .iter() + .filter_map(|e| e["field"].as_str()) + .collect(); + assert!(fields.contains(&"upstreams[0]"), "{fields:?}"); + assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}"); + assert_eq!(r.json["error"]["code"], "apply.failed.validation"); + let codes: Vec<&str> = r.json["errors"] + .as_array() + .unwrap() + .iter() + .filter_map(|e| e["code"].as_str()) + .collect(); + assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}"); + let msg = r.json["errors"][0]["message"].as_str().unwrap(); + assert!( + !msg.contains("TOML") && !msg.contains("hosts/"), + "plain English: {msg}" + ); + // Validate without applying. + let r = env + .call( + "POST", + "/api/v1/hosts/validate?mode=create", + Some(host("a.test", &good.url(), false)), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + // A hostname that does not match the path, a host that does not exist. + let r = env + .call( + "PUT", + "/api/v1/hosts/b.test", + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!( + r.json["error"]["code"], "host.hostname.mismatch", + "{}", + r.text + ); + let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await; + assert_eq!(r.status, 404); + let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await; + assert_eq!(r.status, 404); + // base_rev must be a commit of the history. + let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await; + assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text); + let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await; + assert_eq!(r.status, 422, "{}", r.text); + + // Idempotency-Key: a retry returns the same apply; another body with it is refused. + let body = json!({ "host": host("a.test", &good.url(), false) }); + let k = [ + ("Authorization", auth.as_str()), + ("Idempotency-Key", "click-1"), + ]; + let first = env + .call_with("POST", "/api/v1/hosts", &k, Some(body.clone())) + .await; + assert_eq!(first.status, 202, "{}", first.text); + let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await; + assert_eq!(again.status, 202, "{}", again.text); + assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]); + let other = env + .call_with( + "POST", + "/api/v1/hosts", + &k, + Some(json!({ "host": host("b.test", &good.url(), false) })), + ) + .await; + assert_eq!(other.status, 422); + assert_eq!(other.json["error"]["code"], "request.idempotency"); + env.wait_apply(first.json["apply"]["id"].as_str().unwrap()) + .await; + // Taken hostname. + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text); + assert_eq!(r.json["error"]["field"], "hostname"); + // The overview answers 304 to its own ETag. + let o = env.call("GET", "/api/v1/overview", None).await; + let etag = o.header("etag").unwrap().to_owned(); + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("Authorization", &auth), ("If-None-Match", &etag)], + None, + ) + .await; + assert_eq!(r.status, 304); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_routes_repository_holds_only_host_files() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), false)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + env.kill_control(); + // Someone pushes a stray file and a nested folder straight into the repository. + let work = env.dir.join("work"); + let git = |args: &[&str], cwd: &std::path::Path| { + let o = std::process::Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .current_dir(cwd) + .output() + .unwrap(); + assert!( + o.status.success(), + "{args:?} {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + git( + &[ + "clone", + "--quiet", + &env.repo().to_string_lossy(), + &work.to_string_lossy(), + ], + &env.dir.join("."), + ); + std::fs::create_dir_all(work.join("hosts/sub")).unwrap(); + std::fs::write(work.join("README.md"), "hello").unwrap(); + std::fs::write( + work.join("hosts/sub/b.test.toml"), + "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + ) + .unwrap(); + git(&["add", "-A"], &work); + git(&["commit", "--quiet", "-m", "stray"], &work); + git(&["push", "--quiet", "origin", "HEAD:main"], &work); + + env.start_control(None); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("c.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "control.paused"); + // Edge keeps the last good config; nothing stray was compiled. + assert_eq!(env.file("edge/edge.json"), good_edge); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn control_only_listens_on_loopback() { + let env = Env::new(EnvSpec::default()).await; + let text = std::fs::read_to_string(env.config_path()).unwrap(); + let open = text.replace( + &format!("listen = \"{}\"", env.api), + "listen = \"0.0.0.0:7979\"", + ); + std::fs::write(env.config_path(), open).unwrap(); + let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) + .arg("--config") + .arg(env.config_path()) + .output() + .unwrap(); + assert!(!out.status.success()); + assert!( + String::from_utf8_lossy(&out.stderr).contains("loopback"), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_overview_has_everything_the_main_screen_needs() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + env.add_host(host("a.test", &good.url(), true)).await; + tokio::time::sleep(Duration::from_secs(2)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.status, 200, "{}", o.text); + for k in [ + "counts", + "hosts", + "engine", + "last_apply", + "undo", + "repo", + "site", + "server_time", + "rev", + ] { + assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text); + } + assert_eq!(o.json["counts"]["hosts"], 1); + assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text); + let h = &o.json["hosts"][0]; + assert_eq!(h["health"]["state"], "healthy"); + assert!(h["health"]["latency_ms"].is_u64()); + assert_eq!(h["certificate"]["state"], "ok"); + assert_eq!(o.json["engine"]["running"], "pingora"); + assert_eq!(o.json["engine"]["state"], "running"); + assert_eq!(o.json["last_apply"]["state"], "kept"); + assert_eq!(o.json["undo"]["available"], true); + assert!(o.json["intermediate"].is_null()); + // The CLI lists tokens without values. + let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) + .args(["token", "list", "--config"]) + .arg(env.config_path()) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains("test") && !text.contains(env.token.rsplit('_').next().unwrap())); + } +} diff --git a/crates/control/tests/apply.rs b/crates/control/tests/apply.rs new file mode 100644 index 0000000..4ada10c --- /dev/null +++ b/crates/control/tests/apply.rs @@ -0,0 +1,808 @@ +// 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 apply pipeline (ROADMAP §6 phase 2, tests first): a failed health check reverts the +//! commit and restores the previous edge config; a control crash at any stage leaves edge on +//! the last good config and recovery makes repository, files and edge agree; concurrent +//! applies are serialised; Undo names its target; kept changes are pushed, and a failed push +//! keeps the change. + +#![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 (edge admin socket); run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::Duration; + + use crate::common::{Env, EnvSpec, host, sha256}; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + use serde_json::json; + + async fn get(env: &Env, hostname: &str) -> ianitor_testkit::client::Resp { + client::https( + env.opts.https_listen, + hostname, + env.roots(), + &Req::get(hostname, "/"), + ) + .await + .unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_failed_health_check_reverts_the_commit_and_restores_the_previous_edge_config() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + + let r = env.add_host(host("a.test", &good.url(), true)).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["reason"]["code"], "apply.kept"); + let kept_head = env.head(); + let kept_edge = env.file("edge/edge.json"); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&kept_edge)); + let body: serde_json::Value = + serde_json::from_slice(&get(&env, "a.test").await.body).unwrap(); + assert_eq!(body["upstream"], "good"); + + // Point it at an upstream whose health check fails: reverted, with the reason. + let r = env + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": host("a.test", &sick.url(), true), "base_rev": kept_head })), + ) + .await; + assert_eq!(r["state"], "reverted", "{r}"); + assert_eq!(r["reason"]["code"], "apply.reverted.server_error", "{r}"); + assert_eq!(r["reason"]["hostname"], "a.test"); + assert!( + r["reason"]["message"] + .as_str() + .unwrap() + .contains("a.test was not changed") + ); + assert_eq!(r["attempted_host"]["upstreams"][0], sick.url()); + + // The commit is reverted in git (history keeps both), and the tree is the kept one. + let log = env.git(&["log", "--format=%s", "refs/heads/main"]); + let subjects: Vec<&str> = log.lines().collect(); + assert!( + subjects[0].starts_with("Revert \"Changed a.test\""), + "{log}" + ); + assert_eq!(subjects[1], "Changed a.test"); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{kept_head}^{{tree}}")]) + ); + // Edge serves the previous config again; the files never left it. + assert_eq!(env.file("edge/edge.json"), kept_edge); + env.assert_consistent().await; + let body: serde_json::Value = + serde_json::from_slice(&get(&env, "a.test").await.body).unwrap(); + assert_eq!(body["upstream"], "good"); + + // History shows the attempt as one entry. + let h = env.call("GET", "/api/v1/history", None).await; + let entries = h.json["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{}", h.text); + assert_eq!(entries[0]["state"], "reverted"); + assert_eq!(entries[1]["state"], "kept"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn only_touched_hosts_are_judged_and_a_host_already_down_never_reverts() { + let good = Echo::start("good").await; + let flaky = Echo::start("flaky").await; + let sick = Echo::start("sick").await; + sick.health.store(503, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + // Without a health check, the watch only checks that the host answers. + let r = env.add_host(host("b.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["reason"]["code"], "apply.kept.no_watch", "{r}"); + // A host that is up when added and goes down later... + assert_eq!( + env.add_host(host("c.test", &flaky.url(), true)).await["state"], + "kept" + ); + flaky.health.store(500, std::sync::atomic::Ordering::SeqCst); + tokio::time::sleep(Duration::from_secs(3)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + let c = o.json["hosts"] + .as_array() + .unwrap() + .iter() + .find(|h| h["hostname"] == "c.test") + .unwrap() + .clone(); + assert_eq!(c["health"]["state"], "down", "{}", o.text); + assert_eq!(c["health"]["failure"]["kind"], "server_error"); + // ...does not stop other changes (only touched hosts are judged), + assert_eq!( + env.add_host(host("d.test", &good.url(), true)).await["state"], + "kept" + ); + // and an edit of the host that was already down is not reverted for it. + let mut edited = host("c.test", &flaky.url(), true); + edited["websockets"] = json!(false); + let r = env + .apply( + "PUT", + "/api/v1/hosts/c.test", + Some(json!({ "host": edited })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + // A new host that fails its check is reverted. + let r = env.add_host(host("e.test", &sick.url(), true)).await; + assert_eq!(r["state"], "reverted", "{r}"); + // Removing a host has nothing to watch and is kept. + let r = env.apply("DELETE", "/api/v1/hosts/b.test", None).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["steps"][4]["state"], "skipped"); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn edge_refusing_a_config_fails_the_apply_and_nothing_changes() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), false)).await["state"], + "kept" + ); + let before = env.head(); + // No certificate for this name: edge refuses the config. + std::fs::remove_file(env.dir.join("certs/d.test.crt")).unwrap(); + let r = env.add_host(host("d.test", &good.url(), false)).await; + assert_eq!(r["state"], "failed", "{r}"); + assert_eq!(r["reason"]["code"], "apply.failed.reload"); + assert!( + r["reason"]["detail"].as_str().unwrap().contains("d.test"), + "{r}" + ); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{before}^{{tree}}")]) + ); + env.assert_consistent().await; + assert_eq!(get(&env, "a.test").await.status, 200); + } + + // ------------------------------------------------------------ crash safety + + /// Kill control at `stage` during an apply; edge must be on the last good config, and a + /// restarted control must bring repository, files and edge back in line. + async fn crash_at(stage: &str) { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), true)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + let good_head = env.head(); + env.kill_control(); + + env.start_control(Some(stage)); + // The reverting stage is reached by a change that fails its watch. + let upstream = if stage == "reverting" { + sick.url() + } else { + good.url() + }; + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &upstream, true) })), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + let exit = env.wait_control_exit(Duration::from_secs(30)); + assert!( + exit.is_some(), + "control did not stop at {stage}:\n{}", + env.control_log() + ); + + let confirmed = matches!(stage, "confirmed" | "promoted"); + // edge.json on disk is always the last good config: the old one, unless edge had + // already confirmed the new one. + if !confirmed { + assert_eq!( + env.file("edge/edge.json"), + good_edge, + "{stage}: edge.json untouched" + ); + } + // A trial edge was serving reverts by itself at its deadline (watch 2 s + margin 2 s). + tokio::time::sleep(Duration::from_secs(5)).await; + let st = env.edge_status().await; + assert!(st["trial"].is_null(), "{stage}: trial still running: {st}"); + if !confirmed { + assert_eq!( + st["config_sha256"], + sha256(&good_edge), + "{stage}: edge back on the last good config" + ); + assert_eq!(get(&env, "a.test").await.status, 200); + } + + // Recovery. + env.start_control(None); + let rec = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(rec.status, 200, "{}", rec.text); + if confirmed { + assert_eq!(rec.json["state"], "kept", "{stage}: {}", rec.text); + } else if stage == "prepared" { + assert_eq!(rec.json["state"], "failed", "{stage}: {}", rec.text); + assert_eq!(env.head(), good_head, "{stage}: branch never moved"); + } else { + assert_eq!(rec.json["state"], "reverted", "{stage}: {}", rec.text); + assert_eq!( + rec.json["reason"]["code"], + if stage == "reverting" { + "apply.reverted.server_error" + } else { + "apply.interrupted" + }, + "{stage}: {}", + rec.text + ); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{good_head}^{{tree}}")]), + "{stage}: the change is reverted in git" + ); + } + env.assert_consistent().await; + // And applies work again afterwards. + let r = env.add_host(host("c.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{stage}: {r}"); + env.assert_consistent().await; + } + + macro_rules! crash_tests { + ($($name:ident => $stage:literal),* $(,)?) => {$( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn $name() { + crash_at($stage).await; + } + )*}; + } + + crash_tests! { + crash_after_the_commit_object_is_made => "prepared", + crash_after_the_branch_moved => "committed", + crash_after_the_trial_files_are_written => "trial_written", + crash_after_edge_loaded_the_trial => "trial_loaded", + crash_during_the_watch => "watching", + crash_after_the_watch => "watched", + crash_after_edge_confirmed => "confirmed", + crash_after_the_files_were_promoted => "promoted", + crash_while_reverting => "reverting", + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn an_edge_restart_during_the_watch_reverts_and_edge_starts_from_the_last_good_config() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 6, + ..Default::default() + }) + .await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), true)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &good.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + tokio::time::sleep(Duration::from_secs(2)).await; + env.stop_edge(); + env.start_edge(); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "reverted", "{rec}"); + assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost"); + env.assert_consistent().await; + } + + // ------------------------------------------------------------ serialisation + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_applies_are_serialised() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 1, + ..Default::default() + }) + .await; + env.start_control(None); + let names = ["a.test", "b.test", "c.test", "d.test", "e.test"]; + let env_ref = &env; + let posts = names.iter().map(|n| { + let body = json!({ "host": host(n, &good.url(), true) }); + async move { env_ref.call("POST", "/api/v1/hosts", Some(body)).await } + }); + let answers = futures_join(posts).await; + let mut ids = Vec::new(); + for a in &answers { + assert_eq!(a.status, 202, "{}", a.text); + ids.push(a.json["apply"]["id"].as_str().unwrap().to_owned()); + } + // While one runs, the others say they are queued behind it. + let queued = env + .call("GET", &format!("/api/v1/applies/{}", ids[4]), None) + .await; + let st = queued.json["state"].as_str().unwrap().to_owned(); + if st == "queued" { + assert!( + queued.json["queue"]["position"].as_u64().unwrap() >= 1, + "{}", + queued.text + ); + } + let mut spans = Vec::new(); + for id in &ids { + let r = env.wait_apply(id).await; + assert_eq!(r["state"], "kept", "{r}"); + spans.push(( + r["started_at"].as_str().unwrap().to_owned(), + r["finished_at"].as_str().unwrap().to_owned(), + r["commit"].as_str().unwrap().to_owned(), + )); + } + // One after another: each starts after the previous finished, and each commit's + // parent is the previous commit (a linear history, nothing lost). + spans.sort(); + for w in spans.windows(2) { + assert!(w[1].0 >= w[0].1, "overlap: {w:?}"); + assert_eq!( + env.git(&["rev-parse", &format!("{}^", w[1].2)]), + w[0].2, + "linear" + ); + } + let files = env.head_files(); + for n in names { + assert!( + files.iter().any(|(p, _)| p == &format!("hosts/{n}.toml")), + "{n} missing" + ); + } + env.assert_consistent().await; + } + + async fn futures_join(fs: impl Iterator) -> Vec { + let mut out = Vec::new(); + let handles: Vec<_> = fs.collect(); + // Start all at once: poll them together. + let mut pinned: Vec>> = handles.into_iter().map(Box::pin).collect(); + let mut results: Vec> = (0..pinned.len()).map(|_| None).collect(); + std::future::poll_fn(|cx| { + let mut pending = false; + for (i, f) in pinned.iter_mut().enumerate() { + if results[i].is_none() { + match f.as_mut().poll(cx) { + std::task::Poll::Ready(v) => results[i] = Some(v), + std::task::Poll::Pending => pending = true, + } + } + } + if pending { + std::task::Poll::Pending + } else { + std::task::Poll::Ready(()) + } + }) + .await; + for r in results { + out.push(r.unwrap()); + } + out + } + + // ------------------------------------------------------------ undo, restore, conflicts + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn undo_names_its_target_and_undo_after_undo_is_a_redo() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["blocked"]["code"], "undo.nothing", "{}", u.text); + + let a = env.add_host(host("a.test", &good.url(), false)).await; + let b = env.add_host(host("b.test", &good.url(), false)).await; + // A reverted attempt does not become the Undo target. + let failed = env.add_host(host("c.test", &sick.url(), true)).await; + assert_eq!(failed["state"], "reverted"); + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["target"]["change_id"], b["id"], "{}", u.text); + assert_eq!(u.json["target"]["summary"], "Added b.test"); + assert_eq!(u.json["effect"], "Removes b.test"); + + // Undo refuses a target that is not the latest kept change. + let r = env + .call( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": a["id"] })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "undo.target_moved"); + assert!( + r.json["error"]["message"] + .as_str() + .unwrap() + .contains("Added b.test") + ); + + let undo = env + .apply( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": b["id"] })), + ) + .await; + assert_eq!(undo["state"], "kept", "{undo}"); + assert_eq!(undo["summary"], "Undid: Added b.test"); + assert_eq!(undo["undo_of"], b["id"]); + assert!( + !env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + + // Undo again: a redo, and it says so. + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["target"]["change_id"], undo["id"]); + assert_eq!(u.json["effect"], "Adds b.test back", "{}", u.text); + let redo = env + .apply( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": undo["id"] })), + ) + .await; + assert_eq!(redo["state"], "kept"); + assert!( + env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + + // Restore the version after the first change, as a new change. + let p = env + .call( + "GET", + &format!( + "/api/v1/history/{}/restore-preview", + a["id"].as_str().unwrap() + ), + None, + ) + .await; + assert_eq!(p.json["restorable"], true, "{}", p.text); + assert_eq!(p.json["changes"][0]["hostname"], "b.test"); + assert_eq!(p.json["changes"][0]["effect"], "removed"); + let head = env.head(); + let r = env + .apply( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": a["id"], "base_rev": head })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["kind"], "restore"); + assert_eq!(r["restore_of"], a["id"]); + let names: Vec = env.head_files().into_iter().map(|(p, _)| p).collect(); + assert_eq!(names, ["hosts/a.test.toml", "ianitor.toml"]); + // Restoring the same version again: nothing to do. + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": r["id"] })), + ) + .await; + assert_eq!(r.json["error"]["code"], "restore.same", "{}", r.text); + // A reverted change cannot be restored. + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": failed["id"] })), + ) + .await; + assert_eq!(r.json["error"]["code"], "restore.not_kept", "{}", r.text); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn an_edit_from_an_old_form_is_refused_only_if_the_same_host_changed() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + env.add_host(host("a.test", &good.url(), false)).await; + let form = env.call("GET", "/api/v1/hosts/a.test", None).await; + let rev = form.json["rev"].as_str().unwrap().to_owned(); + // Another host changes: no conflict. + env.add_host(host("b.test", &good.url(), false)).await; + let mut edited = host("a.test", &good.url(), false); + edited["websockets"] = json!(false); + let r = env + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": edited.clone(), "base_rev": rev })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + // The same host changed since the form was loaded: refused, with who and when. + edited["access_log"] = json!("truncated"); + let r = env + .call( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": edited, "base_rev": rev })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "change.conflict"); + assert_eq!(r.json["error"]["params"]["summary"], "Changed a.test"); + } + + // ------------------------------------------------------------ push + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn kept_changes_are_pushed_and_a_failed_push_keeps_the_change() { + let good = Echo::start("good").await; + let remote_dir = ianitor_testkit::proc::TempDir::new("remote"); + let remote = remote_dir.join("routes-remote.git"); + let mut env = Env::new(EnvSpec { + remote: Some(remote.to_string_lossy().into_owned()), + ..Default::default() + }) + .await; + // The remote does not exist yet: the push fails, the change is still kept. + env.start_control(None); + let r = env.add_host(host("a.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{r}"); + tokio::time::sleep(Duration::from_secs(1)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!( + o.json["repo"]["push_error_code"], "push.failed.unreachable", + "{}", + o.text + ); + assert!(o.json["repo"]["unpushed"].as_u64().unwrap() >= 1); + assert!( + env.head_files() + .iter() + .any(|(p, _)| p == "hosts/a.test.toml") + ); + env.assert_consistent().await; + + // Create the remote and push now. + let st = std::process::Command::new("git") + .args(["init", "--bare", "--quiet"]) + .arg(&remote) + .status() + .unwrap(); + assert!(st.success()); + let r = env.call("POST", "/api/v1/repo/push", None).await; + assert_eq!(r.status, 200, "{}", r.text); + assert!(r.json["push_error_code"].is_null(), "{}", r.text); + assert_eq!(r.json["unpushed"], 0); + let remote_head = std::process::Command::new("git") + .env("GIT_DIR", &remote) + .args(["rev-parse", "refs/heads/main"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&remote_head.stdout).trim(), + env.head() + ); + // The next kept change is pushed by itself. + env.add_host(host("b.test", &good.url(), false)).await; + tokio::time::sleep(Duration::from_secs(2)).await; + let remote_head = std::process::Command::new("git") + .env("GIT_DIR", &remote) + .args(["rev-parse", "refs/heads/main"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&remote_head.stdout).trim(), + env.head() + ); + } + + // ------------------------------------------------------------ share links end to end + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn share_links_end_to_end() { + let good = Echo::start("good").await; + let auth = ianitor_testkit::authelia::MockAuthelia::start().await; + let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url()); + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + env.start_control(None); + let mut h = host("share.test", &good.url(), false); + h["auth"] = json!("forward-auth"); + assert_eq!(env.add_host(h).await["state"], "kept"); + // Links off: refused with the plain-English reason. + let r = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 409); + assert_eq!(r.json["error"]["code"], "share.disabled"); + let r = env + .apply( + "PATCH", + "/api/v1/hosts/share.test", + Some(json!({ "share_links": true })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["kind"], "share_links"); + + let r = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({ "path_prefix": "/albums", "expires_in_s": 3600 })), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + let url = r.json["url"].as_str().unwrap().to_owned(); + let id = r.json["id"].as_str().unwrap().to_owned(); + assert!( + url.starts_with(&format!( + "https://share.test:{}/albums?share=ish1.", + env.opts.https_listen.port() + )), + "{url}" + ); + let path = url + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + + let visit = |p: String, cookie: Option| { + let mut req = Req::get("share.test", &p); + if let Some(c) = cookie { + req = req.header("cookie", &c); + } + let (addr, roots) = (env.opts.https_listen, env.roots()); + async move { + client::https(addr, "share.test", roots, &req) + .await + .unwrap() + } + }; + let r = visit(path.clone(), None).await; + assert_eq!(r.status, 303, "{}", r.text()); + let cookie = r + .header("set-cookie") + .unwrap() + .split(';') + .next() + .unwrap() + .to_owned(); + assert_eq!( + visit("/albums/x".into(), Some(cookie.clone())).await.status, + 200 + ); + assert_eq!( + visit("/private".into(), Some(cookie.clone())).await.status, + 302, + "outside the prefix: sign-in" + ); + + let list = env.call("GET", "/api/v1/share-links", None).await; + assert_eq!(list.json["items"][0]["state"], "active"); + assert!(!list.text.contains("ish1."), "no tokens in the list"); + + // Stop: refused within seconds. + let r = env + .call("DELETE", &format!("/api/v1/share-links/{id}"), None) + .await; + assert_eq!(r.status, 204); + assert_eq!( + visit("/albums/x".into(), Some(cookie.clone())).await.status, + 302 + ); + let r = visit(path.clone(), None).await; + assert_eq!(r.status, 403); + + // replaces: the new link works, the replaced one stops. + let r1 = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({})), + ) + .await; + let p1 = r1.json["url"] + .as_str() + .unwrap() + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + let r2 = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({ "replaces": r1.json["id"], "password": "correct horse" })), + ) + .await; + assert_eq!(r2.status, 201, "{}", r2.text); + assert_eq!(r2.json["has_password"], true); + assert_eq!(visit(p1, None).await.status, 403, "replaced link stopped"); + // Stop all. + let r = env.call("POST", "/api/v1/share-links/stop-all", None).await; + assert_eq!(r.status, 200); + let p2 = r2.json["url"] + .as_str() + .unwrap() + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + let r = visit(p2, None).await; + // A password link shows its page before anything is proven; the POST is refused. + assert_eq!(r.status, 401); + // Tokens and passwords are not in control's log. + let log = env.control_log(); + assert!(!log.contains("ish1."), "token in the control log"); + assert!(!log.contains("correct horse")); + } +} diff --git a/crates/control/tests/common/mod.rs b/crates/control/tests/common/mod.rs new file mode 100644 index 0000000..2f2568d --- /dev/null +++ b/crates/control/tests/common/mod.rs @@ -0,0 +1,556 @@ +// 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/. + +//! A control-plane test environment on 127.0.0.1: an edge running in this process (with its +//! admin socket), the real `ianitor-control` binary as a child process (so a test can kill it +//! or make it abort at a crash point), a bare routes repository, test upstreams and a test CA. +//! The first API token comes from `ianitor-control token create`, as in production. + +#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use ianitor_core::compile::{self, CompileOptions}; +use ianitor_core::{SourceFile, load}; +use ianitor_testkit::more::{JsonResp, tcp_json, unix_json}; +use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port}; +use ianitor_testkit::tls::TestCa; +use rustls::RootCertStore; +use serde_json::{Value, json}; + +pub const HOSTS: [&str; 7] = [ + "a.test", + "b.test", + "c.test", + "d.test", + "e.test", + "f.test", + "share.test", +]; +pub const SHARE_KEY: &str = "control-test-share-key-0123456789abcdef0123456789"; + +pub struct Edge { + stop: Option>, + pub http: SocketAddr, + pub https: SocketAddr, + pub admin: PathBuf, +} + +impl Drop for Edge { + fn drop(&mut self) { + if let Some(s) = self.stop.take() { + let _ = s.send(()); + } + } +} + +pub struct Env { + pub dir: TempDir, + pub ca: TestCa, + pub edge: Option, + pub control: Option, + pub api: SocketAddr, + pub token: String, + pub opts: CompileOptions, + pub watch_secs: u64, + pub remote: Option, + log_n: u32, +} + +pub struct EnvSpec { + pub watch_secs: u64, + pub site: String, + pub remote: Option, +} + +impl Default for EnvSpec { + fn default() -> Self { + EnvSpec { + watch_secs: 2, + site: String::new(), + remote: None, + } + } +} + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +impl Env { + pub async fn new(spec: EnvSpec) -> Env { + let dir = TempDir::new("ctl"); + for d in [ + "state", + "edge", + "caddy", + "certs", + "creds", + "logs", + "edge-state", + ] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let ca = TestCa::new("Ianitor Control Test CA"); + for h in HOSTS { + let leaf = ca.issue(&[h]); + std::fs::write(dir.join(&format!("certs/{h}.crt")), leaf.cert_pem).unwrap(); + std::fs::write(dir.join(&format!("certs/{h}.key")), leaf.key_pem).unwrap(); + } + std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap(); + let opts = CompileOptions { + http_listen: local(free_port()), + https_listen: local(free_port()), + cert_dir: dir.str("certs"), + state_dir: dir.str("edge-state"), + access_log: dir.str("logs/access.log"), + caddy_credentials_dir: dir.str("creds"), + caddy_admin: None, + }; + // Edge starts from an empty config; control brings it in line on its first start. + let empty = load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[], + ) + .unwrap(); + std::fs::write( + dir.join("edge/edge.json"), + compile::edge(&empty, &opts).unwrap(), + ) + .unwrap(); + std::fs::write( + dir.join("edge/share-revocations.json"), + "{\"epoch\":0,\"deny\":[]}", + ) + .unwrap(); + + let api = local(free_port()); + let mut env = Env { + edge: None, + control: None, + api, + token: String::new(), + opts, + watch_secs: spec.watch_secs, + remote: spec.remote.clone(), + ca, + dir, + log_n: 0, + }; + env.write_config(&spec); + env.start_edge(); + // Seed the routes repository with the site file, then make the first token. + if !spec.site.is_empty() { + env.seed_site(&spec.site); + } + env.token = env.cli_token("test"); + env + } + + fn write_config(&self, spec: &EnvSpec) { + let d = |p: &str| s(&self.dir.join(p)); + let remote = spec + .remote + .as_ref() + .map(|r| format!("remote = \"{r}\"\n")) + .unwrap_or_default(); + let text = format!( + r#"listen = "{api}" +state_dir = "{state}" +credentials_dir = "{creds}" +watch_secs = {watch} +watch_every_secs = 1 +trial_margin_secs = 2 +health_poll_secs = 1 + +[routes] +repo = "{repo}" +{remote} +[edge] +config = "{edge}/edge.json" +admin_socket = "{edge}/admin.sock" +share_revocations = "{edge}/share-revocations.json" + +[caddy] +config = "{caddy}/caddy.json" + +[compile] +http_listen = "{http}" +https_listen = "{https}" +cert_dir = "{certs}" +state_dir = "{edge_state}" +access_log = "{log}" +caddy_credentials_dir = "{creds}" +"#, + api = self.api, + state = d("state"), + creds = d("creds"), + watch = spec.watch_secs, + repo = d("routes.git"), + edge = d("edge"), + caddy = d("caddy"), + http = self.opts.http_listen, + https = self.opts.https_listen, + certs = d("certs"), + edge_state = d("edge-state"), + log = d("logs/access.log"), + ); + std::fs::write(self.dir.join("control.toml"), text).unwrap(); + } + + pub fn config_path(&self) -> PathBuf { + self.dir.join("control.toml") + } + + pub fn repo(&self) -> PathBuf { + self.dir.join("routes.git") + } + + pub fn start_edge(&mut self) { + let opts = ianitor_edge::Options { + config: self.dir.join("edge/edge.json"), + admin_socket: Some(self.dir.join("edge/admin.sock")), + share_revocations: Some(self.dir.join("edge/share-revocations.json")), + credentials_dir: Some(self.dir.join("creds")), + ..Default::default() + }; + let shared = ianitor_edge::prepare(&opts).expect("edge config"); + let server = ianitor_edge::server(shared, &opts).expect("edge server"); + let (tx, rx) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || ianitor_edge::run_until(server, rx)); + assert!(wait_for_port( + self.opts.https_listen, + Duration::from_secs(20) + )); + let deadline = Instant::now() + Duration::from_secs(5); + while !self.dir.join("edge/admin.sock").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + self.edge = Some(Edge { + stop: Some(tx), + http: self.opts.http_listen, + https: self.opts.https_listen, + admin: self.dir.join("edge/admin.sock"), + }); + } + + /// Stop the in-process edge (and wait until its listeners are gone). + pub fn stop_edge(&mut self) { + self.edge = None; + let deadline = Instant::now() + Duration::from_secs(15); + while std::net::TcpStream::connect(self.opts.https_listen).is_ok() + && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(50)); + } + std::thread::sleep(Duration::from_millis(200)); + } + + fn command(&self) -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control")); + c.env_remove("IANITOR_TEST_CRASH_AT"); + c + } + + pub fn cli_token(&self, name: &str) -> String { + let out = self + .command() + .args(["token", "create", "--name", name, "--config"]) + .arg(self.config_path()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let t = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + assert!(t.starts_with("ian_"), "{t}"); + t + } + + /// Put an `ianitor.toml` into a fresh repository (before control first starts). + fn seed_site(&self, site: &str) { + let work = self.dir.join("seed"); + std::fs::create_dir_all(&work).unwrap(); + let git = |args: &[&str], cwd: &Path| { + let o = Command::new("git") + .args([ + "-c", + "user.name=test", + "-c", + "user.email=t@t", + "-c", + "init.defaultBranch=main", + ]) + .args(args) + .current_dir(cwd) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + git( + &["init", "--bare", "--quiet", &s(&self.repo())], + &self.dir.join("."), + ); + git(&["init", "--quiet"], &work); + std::fs::write(work.join("ianitor.toml"), site).unwrap(); + git(&["add", "ianitor.toml"], &work); + git(&["commit", "--quiet", "-m", "Site settings"], &work); + git( + &["push", "--quiet", &s(&self.repo()), "HEAD:refs/heads/main"], + &work, + ); + let _ = std::fs::remove_dir_all(&work); + } + + pub fn control_log(&self) -> String { + let mut out = String::new(); + for i in 0..=self.log_n { + out.push_str( + &std::fs::read_to_string(self.dir.join(&format!("logs/control-{i}.log"))) + .unwrap_or_default(), + ); + } + out + } + + /// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage. + pub fn start_control(&mut self, crash_at: Option<&str>) { + self.log_n += 1; + let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n))) + .unwrap(); + let mut c = self.command(); + c.arg("--config").arg(self.config_path()); + c.env("IANITOR_LOG", "debug"); + if let Some(stage) = crash_at { + c.env("IANITOR_TEST_CRASH_AT", stage); + } + c.stdout(Stdio::from(log.try_clone().unwrap())) + .stderr(Stdio::from(log)); + self.control = Some(ChildGuard(c.spawn().unwrap())); + if !wait_for_port(self.api, Duration::from_secs(30)) { + panic!("control did not start:\n{}", self.control_log()); + } + } + + pub fn kill_control(&mut self) { + self.control = None; + let deadline = Instant::now() + Duration::from_secs(10); + while std::net::TcpStream::connect(self.api).is_ok() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + } + + /// Wait for control to exit by itself (a crash point). + pub fn wait_control_exit(&mut self, timeout: Duration) -> Option { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + if let Some(c) = &mut self.control + && let Some(st) = c.0.try_wait().unwrap() + { + self.control = None; + return Some(st); + } + std::thread::sleep(Duration::from_millis(50)); + } + None + } + + pub async fn call(&self, method: &str, path: &str, body: Option) -> JsonResp { + let auth = format!("Bearer {}", self.token); + self.call_with(method, path, &[("Authorization", &auth)], body) + .await + } + + pub async fn call_with( + &self, + method: &str, + path: &str, + headers: &[(&str, &str)], + body: Option, + ) -> JsonResp { + tcp_json(self.api, method, path, headers, body.as_ref()) + .await + .unwrap_or_else(|e| panic!("{method} {path}: {e}\n{}", self.control_log())) + } + + /// Wait for an apply to end; returns its record. + pub async fn wait_apply(&self, id: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(90); + loop { + let r = self + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let st = r.json["state"].as_str().unwrap_or("").to_owned(); + if ["kept", "reverted", "failed", "needs_attention"].contains(&st.as_str()) { + return r.json; + } + if Instant::now() > deadline { + panic!("apply {id} still {st}:\n{}", self.control_log()); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + + /// Submit and wait. + pub async fn apply(&self, method: &str, path: &str, body: Option) -> Value { + let r = self.call(method, path, body).await; + assert_eq!(r.status, 202, "{method} {path}: {}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + self.wait_apply(&id).await + } + + pub async fn add_host(&self, host: Value) -> Value { + self.apply("POST", "/api/v1/hosts", Some(json!({ "host": host }))) + .await + } + + pub async fn edge_status(&self) -> Value { + let r = unix_json(&self.dir.join("edge/admin.sock"), "GET", "/v1/status", None) + .await + .unwrap(); + r.json + } + + pub fn roots(&self) -> Arc { + self.ca.roots() + } + + pub fn git(&self, args: &[&str]) -> String { + let o = Command::new("git") + .env("GIT_DIR", self.repo()) + .args(args) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + String::from_utf8_lossy(&o.stdout).trim().to_owned() + } + + pub fn head(&self) -> String { + self.git(&["rev-parse", "refs/heads/main"]) + } + + /// The routes files at the branch head. + pub fn head_files(&self) -> Vec<(String, String)> { + let list = self.git(&["ls-tree", "-r", "--name-only", "refs/heads/main"]); + list.lines() + .map(|p| { + ( + p.to_owned(), + self.git(&["show", &format!("refs/heads/main:{p}")]) + "\n", + ) + }) + .collect() + } + + /// What edge.json and caddy.json must hold for the branch head. + pub fn expected_configs(&self) -> (String, String) { + let files = self.head_files(); + let site = files + .iter() + .find(|(p, _)| p == "ianitor.toml") + .map(|(_, c)| c.clone()) + .unwrap_or_default(); + let hosts: Vec = files + .iter() + .filter(|(p, _)| p != "ianitor.toml") + .map(|(p, c)| SourceFile { + name: p, + contents: c, + }) + .collect(); + let model = load( + &SourceFile { + name: "ianitor.toml", + contents: &site, + }, + &hosts, + ) + .expect("head validates"); + ( + compile::edge(&model, &self.opts).unwrap(), + compile::caddy(&model, &self.opts).unwrap(), + ) + } + + pub fn file(&self, p: &str) -> String { + std::fs::read_to_string(self.dir.join(p)).unwrap_or_default() + } + + /// The repository, both files and edge agree, and nothing is left half done. + pub async fn assert_consistent(&self) { + let (edge_text, caddy_text) = self.expected_configs(); + assert_eq!( + self.file("edge/edge.json"), + edge_text, + "edge.json matches the branch head" + ); + assert_eq!( + self.file("caddy/caddy.json"), + caddy_text, + "caddy.json matches the branch head" + ); + let st = self.edge_status().await; + assert!(st["trial"].is_null(), "no trial left running: {st}"); + assert_eq!( + st["config_sha256"], + sha256(&edge_text), + "edge runs edge.json" + ); + assert!( + !self.dir.join("edge/edge.json.trial").exists(), + "no trial file left" + ); + assert!( + !self.dir.join("caddy/caddy.json.trial").exists(), + "no Caddy trial file left" + ); + assert!( + !self.dir.join("state/journal.json").exists(), + "no journal left" + ); + } +} + +pub fn sha256(text: &str) -> String { + ring::digest::digest(&ring::digest::SHA256, text.as_bytes()) + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// A host body for the API. +pub fn host(name: &str, upstream: &str, health: bool) -> Value { + let mut h = json!({ + "hostname": name, + "upstreams": [upstream], + "tls": "domi", + "auth": "none", + "websockets": true, + "share_links": false, + "access_log": "off", + }); + if health { + h["health_check"] = json!({ "path": "/healthz", "interval_secs": 1 }); + } + h +}