// 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 Domi CA through control (ROADMAP ยง6 phase 3, tests first): the first intermediate is //! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server //! certificates that chain to the root; device certificates need the match code; the install //! file works once; revocation takes the device off the allow list; no root key file is ever //! in the state directory, and control refuses to start with one there. #![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; run it in WSL2", file!() ); } #[cfg(unix)] mod unix { use std::path::Path; use std::time::{Duration, Instant}; use crate::common::{Env, EnvSpec}; use ianitor_core::pki; use ianitor_testkit::client::{self, Req}; use ianitor_testkit::upstream::Echo; use serde_json::{Value, json}; const PASSWORD: &str = "intermediate-test-password-123"; /// Whether an allow list names any device (the placeholder that keeps it from being /// empty is not one). fn lists_a_device(allow: &str) -> bool { pki::chain_der(allow) .unwrap_or_default() .iter() .any(|d| pki::inspect_der(d).is_ok_and(|i| i.subject_cn != pki::NO_DEVICE_CN)) } fn now() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as i64 } /// The offline side: a root that lives only in this test's memory (and its cert file). struct Offline { root_pem: String, root_key: pki::KeyPair, } async fn env_with_pki() -> (Env, Offline) { let (root_pem, root_key) = pki::create_root(now()).unwrap(); let env = env_with_root(&root_pem).await; (env, Offline { root_pem, root_key }) } async fn env_with_root(root_pem: &str) -> Env { // Only the root certificate goes next to control; the key stays in this test. let extra = |dir: &Path| { format!( "\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n", dir.join("offline-root.crt").display() ) }; let mut env = Env::new(EnvSpec::default()).await; std::fs::write(env.dir.join("offline-root.crt"), root_pem).unwrap(); std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap(); let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join(".")); std::fs::write(env.config_path(), text).unwrap(); env.start_control(None); env } async fn wait_request(env: &Env, id: &str, want: &str) -> Value { let deadline = Instant::now() + Duration::from_secs(20); loop { let r = env .call("GET", &format!("/api/v1/pki-requests/{id}"), None) .await; assert_eq!(r.status, 200, "{}", r.text); if r.json["state"] == want { return r.json; } if Instant::now() > deadline { panic!( "request {id} is {} not {want}\n{}", r.json["state"], env.control_log() ); } tokio::time::sleep(Duration::from_millis(200)).await; } } fn cli(env: &Env, args: &[&str]) -> std::process::Output { env.command() .args(args) .arg("--config") .arg(env.config_path()) .output() .unwrap() } /// Renew (first intermediate), sign offline, install with the CLI. async fn install_intermediate(env: &Env, off: &Offline) -> Value { let r = env .call( "POST", "/api/v1/certs/intermediate/renewal", Some(json!({})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let rid = r.json["request_id"].as_str().unwrap().to_owned(); let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); // The code the UI shows is the one the offline signer computes from the CSR. assert_eq!( r.json["match_code"].as_str().unwrap(), pki::match_code(&pki::csr_der(&csr).unwrap()) ); let r2 = env .call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None) .await; assert_eq!( r2.status, 200, "{} {} {}", r.text, r2.text, env.control_log() ); assert_eq!(r2.text, csr); let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); let f = env.dir.join("signed.crt"); std::fs::write(&f, &signed).unwrap(); let out = cli(env, &["pki", "install", f.to_str().unwrap()]); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); wait_request(env, &rid, "approved").await } #[tokio::test(flavor = "multi_thread")] async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() { let (env, off) = env_with_pki().await; let ov = env.call("GET", "/api/v1/overview", None).await; assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text); // Before an intermediate exists a domi host cannot get a certificate. let echo = Echo::start("domi").await; let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}}); let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await; assert_eq!(rec["state"], "failed", "{rec}"); assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}"); install_intermediate(&env, &off).await; let ov = env.call("GET", "/api/v1/overview", None).await; assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text); assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364); let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log()); // The served certificate chains to the Domi root (only the root is trusted here). let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem); let edge = env.edge.as_ref().unwrap(); let r = client::https( edge.https, "fresh.test", roots, &Req::get("fresh.test", "/"), ) .await .unwrap(); assert_eq!(r.status, 200); let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap(); let info = pki::inspect(&crt).unwrap(); assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]); assert_eq!( (info.not_after - now()) / 86_400, i64::from(pki::SERVER_DAYS) - 1 ); // No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same // for every key, so the unique end is compared.) let key_pem = off.root_key.serialize_pem(); let body: String = key_pem .lines() .filter(|l| !l.starts_with("-----")) .collect(); for d in ["state", "certs", "edge", "caddy", "edge-state"] { for f in walk(&env.dir.join(d)) { let bytes = std::fs::read(&f).unwrap(); let text = String::from_utf8_lossy(&bytes); assert!( !text.contains(&body[body.len() - 40..]), "root key material in {}", f.display() ); assert!( !contains(&bytes, &off.root_key.serialize_der()), "root key DER in {}", f.display() ); } } // The intermediate key is only stored encrypted. let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap(); assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY"))); assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY"))); } #[tokio::test(flavor = "multi_thread")] async fn a_wrong_certificate_is_not_installed() { let (env, off) = env_with_pki().await; let r = env .call( "POST", "/api/v1/certs/intermediate/renewal", Some(json!({})), ) .await; let rid = r.json["request_id"].as_str().unwrap().to_owned(); let csr = r.json["csr_pem"].as_str().unwrap().to_owned(); // Signed by another root. let (other, other_key) = pki::create_root(now()).unwrap(); let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap(); let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": wrong})), ) .await; assert_eq!(r.status, 422, "{}", r.text); assert_eq!(r.json["error"]["code"], "pki.not_our_root"); // For another key. let k = pki::generate_key().unwrap(); let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap(); let wrong = pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap(); let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": wrong})), ) .await; assert_eq!(r.status, 422, "{}", r.text); assert_eq!(r.json["error"]["code"], "pki.wrong_key"); // A leaf is not an intermediate. let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": "garbage"})), ) .await; assert_eq!(r.status, 422, "{}", r.text); let st = env .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) .await; assert_eq!(st.json["state"], "waiting"); // The right one through the API works too. let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": good})), ) .await; assert_eq!(r.status, 200, "{}", r.text); assert_eq!(r.json["state"], "approved"); } #[tokio::test(flavor = "multi_thread")] async fn device_certificate_needs_the_match_code_and_installs_once() { let (env, off) = env_with_pki().await; install_intermediate(&env, &off).await; let r = env .call( "POST", "/api/v1/certs/devices", Some(json!({"name": "Mark's phone", "kind": "phone"})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let rid = r.json["request_id"].as_str().unwrap().to_owned(); let code = r.json["match_code"].as_str().unwrap().to_owned(); assert_eq!(code.len(), 8, "{code}"); // The same name again while it waits: refused. let again = env .call( "POST", "/api/v1/certs/devices", Some(json!({"name": "mark's PHONE", "kind": "phone"})), ) .await; assert_eq!(again.status, 409, "{}", again.text); assert_eq!(again.json["error"]["code"], "pki.device_name_taken"); // A wrong code does nothing. let wrong = if code.starts_with('0') { "11 11 11" } else { "00 00 00" }; let out = cli(&env, &["pki", "approve", wrong]); assert!(!out.status.success()); tokio::time::sleep(Duration::from_millis(2500)).await; let st = env .call("GET", &format!("/api/v1/pki-requests/{rid}"), None) .await; assert_eq!(st.json["state"], "waiting"); let out = cli(&env, &["pki", "approve", &code]); assert!( out.status.success(), "{}", String::from_utf8_lossy(&out.stderr) ); let done = wait_request(&env, &rid, "approved").await; let did = done["device_id"].as_str().unwrap().to_owned(); let certs = env.call("GET", "/api/v1/certs", None).await; assert_eq!(certs.status, 200, "{}", certs.text); assert_eq!(certs.json["root"]["offline"], true); let dev = certs.json["devices"] .as_array() .unwrap() .iter() .find(|d| d["id"] == did.as_str()) .unwrap() .clone(); assert_eq!(dev["state"], "valid"); assert_eq!(dev["name"], "Mark's phone"); // The allow list both engines read has it. let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); assert!(lists_a_device(&allow)); // One-time install file. let b = env .call( "POST", &format!("/api/v1/certs/devices/{did}/bundle"), Some(json!({"format": "qr"})), ) .await; assert_eq!(b.status, 200, "{}", b.text); let url = b.json["download_url"].as_str().unwrap().to_owned(); let password = b.json["one_time_password"].as_str().unwrap().to_owned(); assert!(b.json["qr_svg"].as_str().unwrap().starts_with(""), "{}", g.text); assert!(g.text.contains("Mark's phone"), "{}", g.text); } // No token needed for the download itself (the link is the secret) ... let d = env.call_with("POST", &path, &[], None).await; assert_eq!(d.status, 200, "{}", d.text); assert_eq!(d.header("content-type"), Some("application/x-pkcs12")); let ks = p12_keystore::KeyStore::from_pkcs12( &d.body, &password, p12_keystore::Pkcs12ImportPolicy::Strict, ) .unwrap(); let (_, chain) = ks.private_key_chain().unwrap(); assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root"); // ... and it works only once. let d = env.call_with("POST", &path, &[], None).await; assert_eq!(d.status, 410, "{}", d.text); assert_eq!(d.json["error"]["code"], "pki.bundle_used"); let g = env.call_with("GET", &path, &[], None).await; assert_eq!(g.status, 410, "{}", g.text); // Revoke: off the allow list, no new install file. let r = env .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) .await; assert_eq!(r.status, 204, "{}", r.text); let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap(); assert!(!lists_a_device(&allow), "{allow}"); assert!( allow.contains("BEGIN CERTIFICATE"), "never empty (Caddy refuses that)" ); let b = env .call( "POST", &format!("/api/v1/certs/devices/{did}/bundle"), Some(json!({"format": "p12"})), ) .await; assert_eq!(b.status, 409, "{}", b.text); } #[tokio::test(flavor = "multi_thread")] async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() { let (mut env, off) = env_with_pki().await; env.kill_control(); std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap(); // A control that does not refuse would serve forever: give it 20 s, then kill it. let mut child = env .command() .arg("--config") .arg(env.config_path()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let deadline = Instant::now() + Duration::from_secs(20); let status = loop { if let Some(s) = child.try_wait().unwrap() { break Some(s); } if Instant::now() > deadline { let _ = child.kill(); let _ = child.wait(); break None; } std::thread::sleep(Duration::from_millis(50)); }; assert!( status.is_some_and(|s| !s.success()), "control started with a root key in its state dir" ); let mut err = String::new(); std::io::Read::read_to_string(&mut child.stderr.take().unwrap(), &mut err).unwrap(); assert!(err.contains("root"), "{err}"); // And the message never prints the key. assert!(!err.contains("PRIVATE KEY"), "{err}"); } /// The accepted manual step (Mark, 2026-11-07, Q6): the offline machine runs openssl. /// A root made with openssl signs control's CSR with the extensions file control serves, /// and control installs the result. #[tokio::test(flavor = "multi_thread")] async fn an_intermediate_signed_with_openssl_is_installed() { let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else { return; }; let off = ianitor_testkit::proc::TempDir::new("openssl-root"); let run = |args: &[&str]| { let o = std::process::Command::new(&openssl) .args(args) .current_dir(off.join(".")) .output() .unwrap(); assert!( o.status.success(), "openssl {args:?}: {}", String::from_utf8_lossy(&o.stderr) ); }; run(&[ "req", "-x509", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-keyout", "domi-root.key", "-out", "domi-root.crt", "-days", "3653", "-subj", "/CN=Domi PKI Root/O=Fabrica Domi", "-addext", "basicConstraints=critical,CA:TRUE,pathlen:1", "-addext", "keyUsage=critical,keyCertSign,cRLSign", ]); let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap(); let env = env_with_root(&root_pem).await; let r = env .call( "POST", "/api/v1/certs/intermediate/renewal", Some(json!({})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let rid = r.json["request_id"].as_str().unwrap().to_owned(); let base = r.json["file_base"].as_str().unwrap().to_owned(); let cmd = r.json["approve_command"].as_str().unwrap().to_owned(); assert!(cmd.starts_with("openssl x509 -req"), "{cmd}"); std::fs::write( off.join(&format!("{base}.csr")), r.json["csr_pem"].as_str().unwrap(), ) .unwrap(); let ext = env .call("GET", &format!("/api/v1/pki-requests/{rid}/ext"), None) .await; assert_eq!(ext.status, 200, "{}", ext.text); std::fs::write(off.join(&format!("{base}.ext")), &ext.text).unwrap(); // Exactly the command control shows. let args: Vec<&str> = cmd.split_whitespace().skip(1).collect(); run(&args); let signed = std::fs::read_to_string(off.join(&format!("{base}.crt"))).unwrap(); let info = pki::inspect(&signed).unwrap(); assert_eq!(info.path_len, Some(0)); let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": signed})), ) .await; assert_eq!(r.status, 200, "{}", r.text); assert_eq!(r.json["state"], "approved"); } fn walk(dir: &Path) -> Vec { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { let Ok(rd) = std::fs::read_dir(&d) else { continue; }; for e in rd.flatten() { let p = e.path(); if p.is_dir() { stack.push(p); } else if p.is_file() { out.push(p); } } } out } fn contains(hay: &[u8], needle: &[u8]) -> bool { !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) } /// QC: the openssl step can produce intermediates that are CA + pathlen 0 but cannot /// issue what control issues. Control installs them and reissues every Domi host. #[tokio::test(flavor = "multi_thread")] async fn qc_install_refuses_intermediates_that_cannot_issue() { let Some(openssl) = ianitor_testkit::proc::require_binary("openssl") else { return; }; let off = ianitor_testkit::proc::TempDir::new("qc-openssl-root"); let run = |args: &[&str]| { let o = std::process::Command::new(&openssl) .args(args) .current_dir(off.join(".")) .output() .unwrap(); assert!( o.status.success(), "openssl {args:?}: {}", String::from_utf8_lossy(&o.stderr) ); }; run(&[ "req", "-x509", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-keyout", "domi-root.key", "-out", "domi-root.crt", "-days", "3653", "-subj", "/CN=Domi PKI Root/O=Fabrica Domi", "-addext", "basicConstraints=critical,CA:TRUE,pathlen:1", "-addext", "keyUsage=critical,keyCertSign,cRLSign", ]); let root_pem = std::fs::read_to_string(off.join("domi-root.crt")).unwrap(); let env = env_with_root(&root_pem).await; let good = "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\n"; let cases = [ ( "keyUsage without keyCertSign", "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, digitalSignature\n", "365", ), ( "EKU serverAuth only (devices cannot chain)", "basicConstraints = critical, CA:TRUE, pathlen:0\nkeyUsage = critical, keyCertSign, cRLSign\nextendedKeyUsage = serverAuth\n", "365", ), ("valid past the root (-days 4000)", good, "4000"), ]; let mut accepted = Vec::new(); for (label, ext, days) in cases { let r = env .call( "POST", "/api/v1/certs/intermediate/renewal", Some(json!({})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let rid = r.json["request_id"].as_str().unwrap().to_owned(); std::fs::write(off.join("q.csr"), r.json["csr_pem"].as_str().unwrap()).unwrap(); std::fs::write(off.join("q.ext"), ext).unwrap(); run(&[ "x509", "-req", "-in", "q.csr", "-CA", "domi-root.crt", "-CAkey", "domi-root.key", "-days", days, "-sha256", "-extfile", "q.ext", "-out", "q.crt", ]); let signed = std::fs::read_to_string(off.join("q.crt")).unwrap(); let r = env .call( "PUT", &format!("/api/v1/pki-requests/{rid}/certificate"), Some(json!({"certificate_pem": signed})), ) .await; eprintln!("QC {label}: {} {}", r.status, r.json["state"]); if r.status == 200 { accepted.push(label); } } assert!( accepted.is_empty(), "control installed unusable intermediates: {accepted:?}" ); } /// QC: the root key name that `ianitor-control ca init` and docs/pki.md's openssl /// command write is `domi-root.key`. #[test] fn qc_root_key_check_finds_the_names_ianitor_itself_uses() { let d = ianitor_testkit::proc::TempDir::new("qc-rootkey"); let mut missed = Vec::new(); for name in [ "domi-root.key", "offline/domi-root.key", "Domi_Root_CA.pem", "ca.key", ] { let p = d.join(name); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write( &p, // (Split so that this file does not match the pre-commit hook itself.) concat!( "-----BEGIN ", "PRIVATE KEY-----\nx\n-----END ", "PRIVATE KEY-----\n" ), ) .unwrap(); if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() { missed.push(name); } std::fs::remove_file(&p).unwrap(); } assert!(missed.is_empty(), "root_key_files missed: {missed:?}"); } /// QC M2: a revocation that cannot be written (or not told to edge) must not answer 204 and /// be forgotten. It answers an error, the certificates screen says so, and once the disk /// works again (here: a restart without the fault) the allow list catches up; a repeated /// DELETE nudges again. #[tokio::test(flavor = "multi_thread")] async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() { let (mut env, off) = env_with_pki().await; install_intermediate(&env, &off).await; let r = env .call( "POST", "/api/v1/certs/devices", Some(json!({"name": "tablet", "kind": "phone"})), ) .await; assert_eq!(r.status, 202, "{}", r.text); let rid = r.json["request_id"].as_str().unwrap().to_owned(); let code = r.json["match_code"].as_str().unwrap().to_owned(); assert!(cli(&env, &["pki", "approve", &code]).status.success()); let done = wait_request(&env, &rid, "approved").await; let did = done["device_id"].as_str().unwrap().to_owned(); let allow_file = env.dir.join("certs/domi-devices.pem"); let on_list = || lists_a_device(&std::fs::read_to_string(&allow_file).unwrap_or_default()); let deadline = Instant::now() + Duration::from_secs(10); while !on_list() { assert!( Instant::now() < deadline, "the device never reached the allow list" ); tokio::time::sleep(Duration::from_millis(200)).await; } // From now on the allow list cannot be written. env.kill_control(); env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]); let d = env .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) .await; assert_eq!(d.status, 503, "{}", d.text); assert_eq!( d.json["error"]["code"], "pki.devices_unwritten", "{}", d.text ); // The certificates screen keeps saying so; the device is still on the list. let c = env.call("GET", "/api/v1/certs", None).await; assert_eq!( c.json["devices_problem"]["code"], "pki.devices_unwritten", "{}", c.text ); assert!(on_list()); // The disk works again: the list catches up by itself, without another Revoke. env.kill_control(); env.start_control(None); let deadline = Instant::now() + Duration::from_secs(10); while on_list() { assert!(Instant::now() < deadline, "the revocation never caught up"); tokio::time::sleep(Duration::from_millis(200)).await; } // A repeated Revoke is fine and nudges the engine again. let d = env .call("DELETE", &format!("/api/v1/certs/devices/{did}"), None) .await; assert_eq!(d.status, 204, "{}", d.text); let c = env.call("GET", "/api/v1/certs", None).await; assert!(c.json["devices_problem"].is_null(), "{}", c.text); } }