// 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, /// Appended to control.toml (extra sections such as [pki]). pub extra_config: String, } impl Default for EnvSpec { fn default() -> Self { EnvSpec { watch_secs: 2, site: String::new(), remote: None, extra_config: String::new(), } } } 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, caddy_admin_socket: 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"), ) + &spec.extra_config; 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)); } pub fn command(&self) -> Command { let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control")); c.env_remove("IANITOR_TEST_CRASH_AT"); c.env_remove("IANITOR_TEST_FAIL_WRITE"); 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.start_control_env(crash_at, &[]); } /// Like [`Env::start_control`], with extra environment (fault injection). pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &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); } for (k, v) in envs { c.env(k, v); } 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 }