// 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/. //! Caddy mode end to end (T4: Windows Server runs control with Caddy as the data plane, no //! edge). Control runs with `engine = caddy`, Caddy's admin API on loopback TCP (as on //! Windows), and the Domi CA. A previews-only token opens a branch preview; the apply goes //! through Caddy (trial, watch, confirm); the preview's address then answers through Caddy //! with a Domi certificate; closing it takes it away again. Runs on Windows and on Linux. //! Needs `caddy` on PATH or `$IANITOR_CADDY_BIN` (else it fails, unless IANITOR_ALLOW_SKIP=1). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::net::SocketAddr; use std::process::{Command, Stdio}; use std::sync::Arc; use std::time::{Duration, Instant}; use ianitor_control::Config; use ianitor_control::tokens::{Scope, Tokens}; use ianitor_testkit::client::{self, Req}; use ianitor_testkit::more::{JsonResp, tcp_json}; use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, require_binary, wait_for_port}; use ianitor_testkit::upstream::Echo; use serde_json::{Value, json}; fn s(p: &std::path::Path) -> String { p.to_string_lossy().replace('\\', "/") } async fn call( api: SocketAddr, token: &str, method: &str, path: &str, body: Option, ) -> JsonResp { let auth = format!("Bearer {token}"); tcp_json( api, method, path, &[("Authorization", &auth)], body.as_ref(), ) .await .unwrap() } async fn settle(api: SocketAddr, token: &str, apply: &Value) -> Value { let id = apply["id"].as_str().unwrap().to_owned(); let t = Instant::now(); loop { let r = call(api, token, "GET", &format!("/api/v1/applies/{id}"), None).await; if ["kept", "reverted", "failed"].contains(&r.json["state"].as_str().unwrap_or("")) { return r.json; } assert!( t.elapsed() < Duration::from_secs(90), "apply stuck: {}", r.text ); tokio::time::sleep(Duration::from_millis(700)).await; } } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_branch_preview_answers_through_caddy_without_an_edge() { let Some(caddy) = require_binary("caddy") else { return; }; let dir = TempDir::new("caddy-mode"); for d in [ "state", "edge", "caddy", "certs", "creds", "caddy-state", "root", "xdg", ] { std::fs::create_dir_all(dir.join(d)).unwrap(); } // The offline root (a test one) and the intermediate's password. let now = ianitor_control::util::now(); let (root_pem, root_key) = ianitor_core::pki::create_root(now as i64).unwrap(); std::fs::write(dir.join("root/domi-root.crt"), &root_pem).unwrap(); std::fs::write( dir.join("creds/pki-password"), "caddy-mode-test-password-0123456789", ) .unwrap(); let api = local(free_port()); let admin = local(free_port()); let (http, https) = (free_port(), free_port()); // Caddy starts with only its admin API, as the installer starts it; control loads the rest. let boot = json!({"admin": {"listen": admin.to_string()}}).to_string(); std::fs::write(dir.join("caddy/boot.json"), &boot).unwrap(); let log = std::fs::File::create(dir.join("caddy.log")).unwrap(); let _caddy = ChildGuard( Command::new(&caddy) .args(["run", "--config"]) .arg(dir.join("caddy/boot.json")) .env("HOME", dir.join("xdg")) .env("XDG_CONFIG_HOME", dir.join("xdg")) .env("XDG_DATA_HOME", dir.join("xdg")) .env("APPDATA", dir.join("xdg")) .stdout(Stdio::from(log.try_clone().unwrap())) .stderr(Stdio::from(log)) .spawn() .unwrap(), ); assert!( wait_for_port(admin, Duration::from_secs(20)), "Caddy's admin API did not start" ); std::fs::write(dir.join("state/engine"), "caddy\n").unwrap(); let text = format!( r#"listen = "{api}" state_dir = "{state}" credentials_dir = "{creds}" watch_secs = 2 watch_every_secs = 1 trial_margin_secs = 5 [routes] repo = "{repo}" [edge] config = "{edge}/edge.json" share_revocations = "{edge}/share-revocations.json" [caddy] config = "{caddy_dir}/caddy.json" [compile] http_listen = "127.0.0.1:{http}" https_listen = "127.0.0.1:{https}" cert_dir = "{certs}" state_dir = "{caddy_state}" access_log = "{caddy_state}/access.log" caddy_credentials_dir = "{creds}" caddy_admin = "{admin}" [pki] root_cert = "{root}/domi-root.crt" kdf_iterations = 10000 [engine] file = "{state}/engine" units = "none" [previews] domain = "pv.test" tls = "domi" upstreams = ["127.0.0.1:1024-65535"] min_ttl_secs = 60 "#, state = s(&dir.join("state")), creds = s(&dir.join("creds")), repo = s(&dir.join("routes.git")), edge = s(&dir.join("edge")), caddy_dir = s(&dir.join("caddy")), certs = s(&dir.join("certs")), caddy_state = s(&dir.join("caddy-state")), root = s(&dir.join("root")), ); std::fs::write(dir.join("control.toml"), text).unwrap(); let cfg = Config::load(&dir.join("control.toml")).unwrap(); // The intermediate, signed by the test root (the offline step of docs/pki.md). { let c = ianitor_control::Control::open(cfg.clone()).await.unwrap(); let p = c.pki.as_ref().unwrap(); let r = p.request_renewal(now, "test").unwrap(); let signed = ianitor_core::pki::sign_intermediate( &root_pem, &root_key, r.csr_pem.as_deref().unwrap(), now as i64, ) .unwrap(); p.install_intermediate(&r.id, &signed, now).unwrap(); } let tokens = Tokens::new(&dir.join("state")); let (_, admin_tok) = tokens.create("admin", None, Scope::Full).unwrap(); let (_, fabrica) = tokens.create("fabrica", None, Scope::Previews).unwrap(); let (tx, rx) = tokio::sync::oneshot::channel::<()>(); tokio::spawn(ianitor_control::serve(cfg, async { let _ = rx.await; })); assert!(wait_for_port(api, Duration::from_secs(20))); let r = call(api, &admin_tok, "GET", "/api/v1/overview", None).await; assert_eq!(r.json["engine"]["running"], "caddy", "{}", r.text); assert_eq!(r.json["engine"]["switchable"], false, "{}", r.text); // Fabrica opens the branch's preview. let app = Echo::start("preview-app").await; let r = call( api, &fabrica, "POST", "/api/v1/previews", Some(json!({"project": "shop", "branch": "fix-42", "upstream": app.url(), "ttl": 3600})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let host = r.json["preview"]["hostname"].as_str().unwrap().to_owned(); assert_eq!(host, "fix-42--shop.pv.test"); let done = settle(api, &admin_tok, &r.json["apply"]).await; assert_eq!(done["state"], "kept", "{done}"); let steps: Vec = done["steps"] .as_array() .unwrap() .iter() .map(|s| { format!( "{}={}", s["key"].as_str().unwrap(), s["state"].as_str().unwrap() ) }) .collect(); assert!( steps.contains(&"watch=done".to_owned()), "watched through Caddy: {steps:?}" ); // The preview answers through Caddy, with a certificate from the Domi CA. let mut roots = rustls::RootCertStore::empty(); for der in ianitor_core::pki::chain_der(&root_pem).unwrap() { roots .add(rustls_pki_types::CertificateDer::from(der)) .unwrap(); } let roots = Arc::new(roots); let https_addr = local(https); let resp = client::https(https_addr, &host, roots.clone(), &Req::get(&host, "/hello")) .await .unwrap(); assert_eq!(resp.status, 200); assert_eq!(resp.header("x-robots-tag"), Some("noindex, nofollow")); assert!(String::from_utf8_lossy(&resp.body).contains("preview-app")); let r = call( api, &fabrica, "GET", &format!("/api/v1/previews/{host}"), None, ) .await; assert_eq!(r.json["preview"]["state"], "live", "{}", r.text); // Closed on merge: Caddy stops serving it. let r = call( api, &fabrica, "POST", "/api/v1/previews/close", Some(json!({"project": "shop", "branch": "fix-42"})), ) .await; assert_eq!(r.status, 202, "{}", r.text); assert_eq!( settle(api, &admin_tok, &r.json["apply"]).await["state"], "kept" ); let gone = client::https(https_addr, &host, roots, &Req::get(&host, "/hello")).await; assert!( gone.as_ref() .map_or(true, |r| r.status == 404 || r.status == 421), "{:?}", gone.map(|r| r.status) ); let _ = tx.send(()); }