// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root. //! End to end over real TLS against a mock Fabrica that uses the reference server logic //! (mandatory, tests first): the enrollment code is single use; expired, replayed and foreign //! certificates are refused in both directions; a deploy runs only with the team's signature. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod common; use common::*; use legatus::client::ClientError; use legatus::state::State; use legatus::{AgentError, Session}; use legatus_protocol::{Roles, Status}; const DEPLOY: Roles = Roles { build: false, deploy: true, }; struct Setup { ca: Ca, key: ReleaseKey, mock: Mock, dir: tempfile::TempDir, } fn setup() -> Setup { let ca = Ca::new(); let key = ReleaseKey::new(); let mock = mock(&ca, server_cert(&ca, now()), vec![key.public()]); Setup { ca, key, mock, dir: tempfile::tempdir().unwrap(), } } impl Setup { fn state(&self, name: &str) -> State { State::new(self.dir.path().join(name)) } fn enrolled(&self) -> State { let st = self.state("agent"); legatus::enroll(&st, &self.mock.code(&self.ca, "web-1", DEPLOY, 3600), false).unwrap(); st } } fn refused_code(e: AgentError) -> String { match e { AgentError::Client(ClientError::Refused { code, .. }) => code, other => panic!("expected a refusal, got {other:?}"), } } #[test] fn enroll_hello_deploy_report() { let s = setup(); let st = s.enrolled(); let e = st.load().unwrap(); assert_eq!( (e.file.team.as_str(), e.file.agent.as_str()), ("acme", "web-1") ); assert_eq!(e.file.release_keys, vec![s.key.public()]); assert!(e.file.roles.deploy); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(st.dir().join("key.pem")) .unwrap() .permissions() .mode(); assert_eq!(mode & 0o777, 0o600); } // A signed release, served by Fabrica. let art = b"the shop, version 1.4.0".to_vec(); let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", &art); let id = job_id(7); { let mut w = s.mock.world.lock().unwrap(); w.jobs .push_back(deploy_job(&id, "1.4.0", &m, &s.key.sign(m.as_bytes()))); w.artifacts .insert((id.clone(), "shop.tar.gz".into()), art.clone()); } let target = FakeTarget::new(); let mut session = Session::open(st.clone()).unwrap(); session.hello(&target).unwrap(); assert!(session.poll_once(&target).unwrap()); assert_eq!(target.calls.borrow().len(), 1); assert_eq!(target.calls.borrow()[0].3, art); let w = s.mock.world.lock().unwrap(); let statuses: Vec = w.reports.iter().map(|r| r.status).collect(); assert_eq!(statuses, vec![Status::Accepted, Status::Succeeded]); drop(w); // Nothing waiting: the poll returns without a job. assert!(!session.poll_once(&target).unwrap()); } #[test] fn a_tampered_artifact_from_the_server_is_refused() { let s = setup(); let st = s.enrolled(); let art = b"the shop, version 1.4.0".to_vec(); let m = manifest("acme", "shop", "1.4.0", "shop.tar.gz", &art); let id = job_id(8); { let mut w = s.mock.world.lock().unwrap(); w.jobs .push_back(deploy_job(&id, "1.4.0", &m, &s.key.sign(m.as_bytes()))); w.artifacts.insert( (id.clone(), "shop.tar.gz".into()), b"the shop, version 6.6.6".to_vec(), ); } let target = FakeTarget::new(); let mut session = Session::open(st).unwrap(); session.poll_once(&target).unwrap(); assert!(target.calls.borrow().is_empty()); let w = s.mock.world.lock().unwrap(); let last = w.reports.last().unwrap(); assert_eq!(last.status, Status::Refused); assert!(last.message.starts_with("tampered: "), "{}", last.message); } #[test] fn the_enrollment_code_is_single_use() { let s = setup(); let code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600); legatus::enroll(&s.state("first"), &code, false).unwrap(); // The same code on a second machine. let e = legatus::enroll(&s.state("second"), &code, false).unwrap_err(); assert_eq!(refused_code(e), "code_used"); assert!(!s.state("second").is_enrolled()); } #[test] fn an_expired_code_is_refused() { let s = setup(); let code = s.mock.code(&s.ca, "web-1", DEPLOY, 1); std::thread::sleep(std::time::Duration::from_millis(2100)); let e = legatus::enroll(&s.state("a"), &code, false).unwrap_err(); assert_eq!(refused_code(e), "code_expired"); } #[test] fn a_server_under_another_root_never_sees_the_secret() { let ours = Ca::new(); let theirs = Ca::new(); // A server that presents a certificate from another Domi root, for the same address. let impostor = mock( &theirs, server_cert(&theirs, now()), vec![ReleaseKey::new().public()], ); let mut secret = [0u8; 16]; secret[0] = 1; let code = legatus_protocol::EnrollmentCode::new(&impostor.url, ours.root_sha256(), secret) .unwrap() .encode(); let dir = tempfile::tempdir().unwrap(); let e = legatus::enroll(&State::new(dir.path()), &code, false).unwrap_err(); assert!( matches!( e, AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(_))) ), "{e:?}" ); assert!( impostor.world.lock().unwrap().requests.is_empty(), "no request reached the impostor" ); } #[test] fn an_expired_server_certificate_is_refused() { let ca = Ca::new(); let old = mock( &ca, server_cert(&ca, now() - 91 * DAY), vec![ReleaseKey::new().public()], ); let code = old.code(&ca, "web-1", DEPLOY, 3600); let dir = tempfile::tempdir().unwrap(); let e = legatus::enroll(&State::new(dir.path()), &code, false).unwrap_err(); match e { AgentError::Client(ClientError::Http(legatus::http::HttpError::Tls(m))) => { assert!(m.to_lowercase().contains("expired"), "{m}") } other => panic!("{other:?}"), } assert!(old.world.lock().unwrap().requests.is_empty()); } /// The server refused our client certificate in the TLS handshake. With TLS 1.3 the client may /// already have sent its request, so it sees either the alert or the reset that follows it. fn handshake_refused(e: &AgentError) -> bool { use legatus::http::HttpError; match e { AgentError::Client(ClientError::Http(HttpError::Tls(_))) => true, AgentError::Client(ClientError::Http(HttpError::Protocol(m))) => { let m = m.to_lowercase(); [ "reset", "forcibly closed", "closed early", "broken pipe", "aborted", ] .iter() .any(|w| m.contains(w)) } _ => false, } } /// Replace the agent's certificate and key in its state (what an attacker with old or foreign /// credentials would present). fn swap_identity(st: &State, chain: &str, key: &str) { st.save_identity(chain, key).unwrap(); } #[test] fn a_foreign_client_certificate_is_refused() { let s = setup(); let st = s.enrolled(); let target = FakeTarget::new(); // An agent certificate from another Domi root, same ids: refused in the TLS handshake. let other = Ca::new(); let (chain, key) = other.agent("acme", "web-1", now()); swap_identity(&st, &chain, &key); let e = Session::open(st.clone()) .unwrap() .hello(&target) .unwrap_err(); assert!(handshake_refused(&e), "{e:?}"); // A phone's device certificate from our own root: through TLS, refused by the registry. let dev = domi_pki::issue_device(&s.ca.ianitor, "phone", now()).unwrap(); swap_identity(&st, &dev.chain_pem, &dev.key_pem); let e = Session::open(st.clone()) .unwrap() .hello(&target) .unwrap_err(); assert_eq!(refused_code(e), "certificate_refused"); // An agent of our root that was never enrolled here. let (chain, key) = s.ca.agent("acme", "web-2", now()); swap_identity(&st, &chain, &key); let e = Session::open(st).unwrap().hello(&target).unwrap_err(); assert_eq!(refused_code(e), "certificate_refused"); } #[test] fn an_expired_client_certificate_is_refused() { let s = setup(); let st = s.enrolled(); let (chain, key) = s.ca.agent("acme", "web-1", now() - 31 * DAY); swap_identity(&st, &chain, &key); let e = Session::open(st) .unwrap() .hello(&FakeTarget::new()) .unwrap_err(); assert!(handshake_refused(&e), "{e:?}"); } #[test] fn a_replayed_client_certificate_is_refused() { let s = setup(); let st = s.enrolled(); let target = FakeTarget::new(); let old = st.load().unwrap(); let mut session = Session::open(st.clone()).unwrap(); session.hello(&target).unwrap(); // Renew: a new key and certificate; once the new one is used, the old one is a replay. assert!(session.renew_if_due(true).unwrap()); session.hello(&target).unwrap(); assert_ne!(st.load().unwrap().chain_pem, old.chain_pem); swap_identity(&st, &old.chain_pem, &old.key_pem); let e = Session::open(st).unwrap().hello(&target).unwrap_err(); assert_eq!(refused_code(e), "certificate_refused"); } #[test] fn no_certificate_no_service() { let s = setup(); // Straight to hello without a client certificate (an enrollment-only TLS config). let cfg = legatus::tls::enroll_config(legatus::tls::PinnedRoot::by_hash(s.ca.root_sha256())).unwrap(); let f = legatus::client::Fabrica::new(&s.mock.url, cfg).unwrap(); let e = f.next_job(0).unwrap_err(); assert_eq!(e.code(), Some("certificate_required")); } #[test] fn enrolling_twice_needs_force() { let s = setup(); let st = s.enrolled(); let code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600); assert!(matches!( legatus::enroll(&st, &code, false), Err(AgentError::AlreadyEnrolled(_)) )); legatus::enroll(&st, &code, true).unwrap(); } #[test] fn a_typo_in_the_code_never_reaches_the_network() { let s = setup(); let mut code = s.mock.code(&s.ca, "web-1", DEPLOY, 3600).into_bytes(); let i = code.len() / 2; code[i] = if code[i] == b'a' { b'b' } else { b'a' }; let e = legatus::enroll(&s.state("x"), &String::from_utf8(code).unwrap(), false).unwrap_err(); assert!(matches!(e, AgentError::Code(_)), "{e:?}"); assert!(s.mock.world.lock().unwrap().requests.is_empty()); }