#[path = "../src/certificate_rotation.rs"] mod certificate_rotation; // Rotation uses the HTTPS implementation too. Run its transport contract in this // harness rather than compiling an untested/unused copy of the channel module. #[path = "https_channel.rs"] mod transport_tests; use certificate_rotation::*; use common::*; use std::{ fs, os::unix::fs::DirBuilderExt, os::unix::fs::PermissionsExt, path::PathBuf, sync::{Arc, Mutex}, }; use transport_tests::{common, https_channel}; use uuid::Uuid; struct Temp(PathBuf); impl Temp { fn new() -> Self { let path = PathBuf::from("/tmp/opencode").join(format!("agent-transport-{}", Uuid::new_v4())); fs::DirBuilder::new().mode(0o700).create(&path).unwrap(); Self(path) } } impl Drop for Temp { fn drop(&mut self) { fs::remove_dir_all(&self.0).unwrap(); } } fn csr_cert(pki: &Pki, csr: &str, cn: &str) -> Vec { let csr = openssl::x509::X509Req::from_pem(csr.as_bytes()).unwrap(); let now = chrono::Utc::now().timestamp(); pki.issue( &csr.public_key().unwrap(), cn, false, now - 60, now + 30 * 86400, ) .to_pem() .unwrap() } fn initialized(pki: &Pki, temp: &Temp, agent: Uuid, now: i64) -> RotationStore { let store = RotationStore::open(&temp.0, &pki.ca.to_pem().unwrap(), agent, 1).unwrap(); let key = key(); let cert = pki.issue( &key, &agent.to_string(), false, now - 21 * 86400, now + 9 * 86400, ); store .initialize( &cert.to_pem().unwrap(), &key.private_key_to_pem_pkcs8().unwrap(), now, ) .unwrap(); store } #[tokio::test] async fn lost_response_reuses_csr_and_atomically_installs_matching_key() { let pki = Pki::new(); let temp = Temp::new(); let agent = Uuid::new_v4(); let now = chrono::Utc::now().timestamp(); let store = initialized(&pki, &temp, agent, now); assert!(store.due(RotationPolicy::default(), now).unwrap()); let original = store.current(now).unwrap(); let cached = Arc::new(Mutex::new(None::<(String, Vec)>)); let cache = cached.clone(); let issuer = Pki { ca: pki.ca.clone(), ca_key: pki.ca_key.clone(), }; let server = Server::start(&pki, "rmm-dev.internal", move |r| { assert_eq!(r.path, "/agent/v1/certificates/renew"); assert_eq!(r.content_type, "application/json"); let json: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); let csr = json["csr_pem"].as_str().unwrap(); let mut cache = cache.lock().unwrap(); if let Some((old, cert)) = cache.as_ref() { assert_eq!(old, csr); return Some(Response { status: 200, media: "application/json", body: serde_json::to_vec(&serde_json::json!({"agent_id":agent,"certificate_pem":String::from_utf8(cert.clone()).unwrap(),"overlap_seconds":300})).unwrap() }); } *cache = Some((csr.into(), csr_cert(&issuer, csr, &agent.to_string()))); None }); assert!(store.renew(server.address, now).await.is_err()); assert_eq!( store.current(now).unwrap().selector.version, original.selector.version ); // Reopen simulates process loss after pending key/CSR and lost response. let reopened = RotationStore::open(&temp.0, &pki.ca.to_pem().unwrap(), agent, 1).unwrap(); let result = reopened.renew(server.address, now).await.unwrap(); assert!(result.needs_reconnect); assert_eq!(result.enrollment_generation, 1); let installed = reopened.current(now).unwrap(); assert_ne!(installed.selector.version, original.selector.version); assert_eq!( installed.selector.previous_version, Some(original.selector.version) ); assert!(installed.selector.previous_until.unwrap() >= now + 300); assert_ne!(installed.private_key_pem, original.private_key_pem); assert!( temp.0 .join("versions") .join(original.selector.version.to_string()) .join("device.key") .exists() ); assert!(!reopened.due(RotationPolicy::default(), now).unwrap()); for entry in fs::read_dir(temp.0.join("versions")).unwrap() { let dir = entry.unwrap().path(); assert_eq!( fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700 ); for file in fs::read_dir(dir).unwrap() { assert_eq!( file.unwrap().metadata().unwrap().permissions().mode() & 0o777, 0o600 ); } } } #[test] fn expired_unknown_issuer_changed_identity_key_mismatch_and_server_eku_block() { let pki = Pki::new(); let agent = Uuid::new_v4(); let now = chrono::Utc::now().timestamp(); for mode in 0..5 { let temp = Temp::new(); let store = RotationStore::open(&temp.0, &pki.ca.to_pem().unwrap(), agent, 1).unwrap(); let key = key(); let wrong_key = common::key(); let other = Pki::new(); let cert = match mode { 0 => pki.issue(&key, &agent.to_string(), false, now - 86400, now - 1), 1 => other.issue(&key, &agent.to_string(), false, now - 60, now + 86400), 2 => pki.issue( &key, &Uuid::new_v4().to_string(), false, now - 60, now + 86400, ), 3 => pki.issue(&wrong_key, &agent.to_string(), false, now - 60, now + 86400), _ => pki.issue(&key, &agent.to_string(), true, now - 60, now + 86400), }; assert!( store .initialize( &cert.to_pem().unwrap(), &key.private_key_to_pem_pkcs8().unwrap(), now ) .is_err() ); assert!(!temp.0.join("current.json").exists()); } } #[tokio::test] async fn orphan_stages_do_not_change_selector_and_expiry_never_reenrolls() { let pki = Pki::new(); let temp = Temp::new(); let agent = Uuid::new_v4(); let now = chrono::Utc::now().timestamp(); let store = initialized(&pki, &temp, agent, now); let original = store.current(now).unwrap().selector.version; let orphan = temp.0.join("versions").join(Uuid::new_v4().to_string()); fs::create_dir(&orphan).unwrap(); fs::set_permissions(&orphan, fs::Permissions::from_mode(0o700)).unwrap(); fs::write(orphan.join("device.key"), b"incomplete crash stage").unwrap(); assert_eq!(store.current(now).unwrap().selector.version, original); assert!( store .renew("127.0.0.1:1".parse().unwrap(), now + 10 * 86400) .await .is_err() ); assert!(!temp.0.join("pending.json").exists()); let changed = RotationStore::open(&temp.0, &pki.ca.to_pem().unwrap(), Uuid::new_v4(), 1).unwrap(); assert!(changed.current(now).is_err()); let generation = RotationStore::open(&temp.0, &pki.ca.to_pem().unwrap(), agent, 2).unwrap(); assert!(generation.current(now).is_err()); }