diff --git a/tests/tls.rs b/tests/tls.rs index 5a8c9ab..aca7722 100644 --- a/tests/tls.rs +++ b/tests/tls.rs @@ -117,7 +117,7 @@ fn start(pair: &Pair) -> Server { .args(["serve", "--config"]) .arg(&cfg) .env_clear() - .stderr(Stdio::null()) + .stderr(std::fs::File::create(dir.0.join("log.txt")).unwrap()) .spawn() .unwrap(); let s = Server { @@ -319,6 +319,95 @@ async fn mcp_initialize_over_https() { assert_eq!(r.status, 403); } +/// Certificate verifier that accepts anything: used only to read which +/// certificate the server presents while rotation is in flight. +#[derive(Debug)] +struct NoVerify(rustls::crypto::WebPkiSupportedAlgorithms); + +impl rustls::client::danger::ServerCertVerifier for NoVerify { + fn verify_server_cert( + &self, + _: &CertificateDer<'_>, + _: &[CertificateDer<'_>], + _: &ServerName<'_>, + _: &[u8], + _: rustls::pki_types::UnixTime, + ) -> Result { + Ok(rustls::client::danger::ServerCertVerified::assertion()) + } + fn verify_tls12_signature( + &self, + m: &[u8], + c: &CertificateDer<'_>, + d: &rustls::DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature(m, c, d, &self.0) + } + fn verify_tls13_signature( + &self, + m: &[u8], + c: &CertificateDer<'_>, + d: &rustls::DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature(m, c, d, &self.0) + } + fn supported_verify_schemes(&self) -> Vec { + self.0.supported_schemes() + } +} + +/// Fingerprint of the certificate currently served, without trusting it. +/// `None` on any connection error (treated by callers as "not yet"). +async fn probe_fp(port: u16) -> Option { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let algs = provider.signature_verification_algorithms; + let cfg = rustls::ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(NoVerify(algs))) + .with_no_client_auth(); + let tcp = TcpStream::connect(("127.0.0.1", port)).await.ok()?; + let tls = TlsConnector::from(Arc::new(cfg)) + .connect(ServerName::try_from("localhost").unwrap(), tcp) + .await + .ok()?; + let (_, conn) = tls.get_ref(); + let der = conn.peer_certificates()?.first()?.clone(); + Some(hex(&Sha256::digest(der.as_ref()))) +} + +fn log_count(dir: &Path, needle: &str) -> usize { + std::fs::read_to_string(dir.join("log.txt")) + .unwrap_or_default() + .matches(needle) + .count() +} + +/// Wait (bounded) until the server log holds at least `n` lines with `needle`. +async fn wait_log(dir: &Path, needle: &str, n: usize) { + for _ in 0..100 { + if log_count(dir, needle) >= n { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("server log never showed {n} x {needle:?}"); +} + +/// Poll until the served certificate fingerprint satisfies `want`. +async fn wait_fp(port: u16, want: impl Fn(&str) -> bool) -> String { + for _ in 0..50 { + if let Some(fp) = probe_fp(port).await { + if want(&fp) { + return fp; + } + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("served certificate never reached the expected state"); +} + #[tokio::test] async fn sighup_serves_new_cert_and_bad_cert_keeps_old() { let a = gen_pair(); @@ -340,10 +429,10 @@ async fn sighup_serves_new_cert_and_bad_cert_keeps_old() { let mut buf = [0u8; 1024]; assert!(held.read(&mut buf).await.unwrap() > 0); - // Corrupt cert: reload fails, old cert still served. + // Corrupt cert: reload fails (wait for the log), old cert still served. std::fs::write(s.dir.0.join("cert.pem"), "not a certificate").unwrap(); signal(&s.child, "-HUP"); - tokio::time::sleep(Duration::from_millis(500)).await; + wait_log(&s.dir.0, "TLS reload failed", 1).await; let r = https(s.port, &a, "GET", "/healthz", &[], None).await; assert_eq!(r.status, 200); assert_eq!(r.peer_fp, fp_a, "bad reload must keep the old certificate"); @@ -351,16 +440,8 @@ async fn sighup_serves_new_cert_and_bad_cert_keeps_old() { // Valid new pair: SIGHUP swaps it. write_pair(&s.dir.0, &b); signal(&s.child, "-HUP"); - let mut fp_b = String::new(); - for _ in 0..30 { - tokio::time::sleep(Duration::from_millis(200)).await; - fp_b = https(s.port, &b, "GET", "/healthz", &[], None) - .await - .peer_fp; - if fp_b != fp_a { - break; - } - } + wait_log(&s.dir.0, "TLS certificate reloaded", 1).await; + let fp_b = wait_fp(s.port, |fp| fp != fp_a).await; assert_ne!(fp_b, fp_a, "SIGHUP should serve the new certificate"); // The pre-reload connection survived. @@ -645,21 +726,13 @@ async fn mismatched_pair_on_sighup_keeps_old_cert() { // New cert B with old key A: mismatch, old pair kept. std::fs::write(s.dir.0.join("cert.pem"), &b.cert_pem).unwrap(); signal(&s.child, "-HUP"); - tokio::time::sleep(Duration::from_millis(500)).await; + wait_log(&s.dir.0, "TLS reload failed", 1).await; let r = https(s.port, &a, "GET", "/healthz", &[], None).await; assert_eq!(r.peer_fp, fp_a); // Completing the rotation (key B) and sending HUP again works. std::fs::write(s.dir.0.join("key.pem"), &b.key_pem).unwrap(); signal(&s.child, "-HUP"); - let mut fp = String::new(); - for _ in 0..30 { - tokio::time::sleep(Duration::from_millis(200)).await; - fp = https(s.port, &b, "GET", "/healthz", &[], None) - .await - .peer_fp; - if fp != fp_a { - break; - } - } + wait_log(&s.dir.0, "TLS certificate reloaded", 1).await; + let fp = wait_fp(s.port, |fp| fp != fp_a).await; assert_ne!(fp, fp_a); }