Files

338 lines
13 KiB
Rust

// 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/.
//! Device certificates (ROADMAP §6 phase 3, tests first): on a host with `device_certs`, a
//! Domi device certificate on the allow list gets in; a self-signed certificate with the same
//! subject, a Domi certificate that is not (or no longer) on the list, and no certificate at
//! all do not. Hosts without `device_certs` never ask for a certificate.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
// On Windows this target has nothing to run: it shows as one *ignored* test, never as a
// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md).
#[cfg(not(unix))]
#[test]
#[ignore = "needs Linux (Pingora runner): run it in WSL2, see CLAUDE.md"]
fn needs_linux() {}
#[cfg(unix)]
mod unix {
use crate::common::{Edge, EdgeSpec, host_file, start};
use ianitor_core::pki::{self, Intermediate};
use ianitor_testkit::client::{self, ClientCert, Req};
use ianitor_testkit::upstream::Echo;
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64
}
struct Pki {
int: Intermediate,
}
fn pki() -> Pki {
let (root, root_key) = pki::create_root(now()).unwrap();
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let int_pem = pki::sign_intermediate(&root, &root_key, &csr, now()).unwrap();
Pki {
int: Intermediate::new(&int_pem, k).unwrap(),
}
}
fn device(p: &Pki, name: &str) -> (ClientCert, String) {
let d = pki::issue_device(&p.int, name, now()).unwrap();
(
ClientCert {
chain_pem: d.chain_pem,
key_pem: d.key_pem,
tls12_only: false,
},
d.cert_pem,
)
}
/// Same subject as a Domi device certificate, but self-signed.
fn self_signed(name: &str) -> ClientCert {
use rcgen::{
CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, KeyPair,
};
let key = KeyPair::generate().unwrap();
let mut p = CertificateParams::default();
let mut dn = DistinguishedName::new();
dn.push(DnType::CommonName, name);
dn.push(DnType::OrganizationName, pki::ORG);
dn.push(DnType::OrganizationalUnitName, "Domi devices");
p.distinguished_name = dn;
p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
let cert = p.self_signed(&key).unwrap();
ClientCert {
chain_pem: cert.pem(),
key_pem: key.serialize_pem(),
tls12_only: false,
}
}
fn tls12(c: &ClientCert) -> ClientCert {
ClientCert {
tls12_only: true,
..c.clone()
}
}
async fn setup(echo: &Echo, p: &Pki, allowed: &[&str]) -> Edge {
let up = format!("upstreams = [\"{}\"]\n", echo.url());
start(EdgeSpec {
hosts: vec![
host_file("locked.test", &format!("{up}device_certs = true\n")),
host_file("open.test", &up),
],
files: vec![
(
"certs/domi-devices-ca.pem".into(),
p.int.cert_pem().as_bytes().to_vec(),
),
(
"certs/domi-devices.pem".into(),
allowed.concat().into_bytes(),
),
],
..Default::default()
})
}
#[tokio::test(flavor = "multi_thread")]
async fn domi_device_cert_is_accepted_and_a_self_signed_one_with_the_same_subject_is_not() {
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "Mark's phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let req = Req::get("locked.test", "/");
for c in [phone.clone(), tls12(&phone)] {
let r = client::https_with_cert(edge.https, "locked.test", edge.roots(), &c, &req)
.await
.unwrap_or_else(|e| panic!("tls12 {}: {e}\n{}", c.tls12_only, edge.stderr()));
assert_eq!(r.status, 200, "{}", edge.stderr());
}
echo.clear();
let fake = self_signed("Mark's phone");
for c in [fake.clone(), tls12(&fake)] {
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &c, &req).await;
assert!(
r.is_err(),
"self-signed lookalike got in (tls12 {}): {r:?}",
c.tls12_only
);
}
assert!(echo.requests().is_empty(), "nothing reached the upstream");
}
#[tokio::test(flavor = "multi_thread")]
async fn no_certificate_is_refused_and_never_reaches_the_upstream() {
let echo = Echo::start("app").await;
let p = pki();
let (_, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let r = client::https(
edge.https,
"locked.test",
edge.roots(),
&Req::get("locked.test", "/"),
)
.await;
assert!(r.is_err(), "no certificate got in: {r:?}");
assert!(echo.requests().is_empty());
// The Host header cannot move a certificate-less connection onto the locked host:
// 421, as Caddy answers once client certificates are configured.
let r = client::https(
edge.https,
"open.test",
edge.roots(),
&Req::get("locked.test", "/"),
)
.await
.unwrap();
assert_eq!(r.status, 421);
assert!(echo.requests().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_domi_cert_not_on_the_allow_list_is_refused_and_revocation_takes_effect_on_reload() {
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let (laptop, _) = device(&p, "laptop");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let req = Req::get("locked.test", "/");
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &laptop, &req).await;
assert!(r.is_err(), "unlisted device got in: {r:?}");
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await;
assert_eq!(r.unwrap().status, 200);
// Revoke the phone: control rewrites the list and reloads edge.
std::fs::write(edge.dir.join("certs/domi-devices.pem"), "").unwrap();
let r = edge.admin("POST", "/v1/reload", None).await;
assert_eq!(r.status, 200, "{}\n{}", r.text, edge.stderr());
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await;
assert!(r.is_err(), "revoked device got in: {r:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_without_device_certs_never_ask_for_one() {
let echo = Echo::start("app").await;
let p = pki();
let (_, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
// A client holding an untrusted certificate is not asked for it on the open host,
// so the handshake succeeds.
let fake = self_signed("someone");
for c in [fake.clone(), tls12(&fake)] {
let r = client::https_with_cert(
edge.https,
"open.test",
edge.roots(),
&c,
&Req::get("open.test", "/"),
)
.await
.unwrap_or_else(|e| panic!("tls12 {}: {e}\n{}", c.tls12_only, edge.stderr()));
assert_eq!(r.status, 200);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_missing_allow_list_refuses_the_config() {
// edge never serves a device host it cannot check.
let echo = Echo::start("app").await;
let mut e = crate::common::spawn(EdgeSpec {
hosts: vec![host_file(
"locked.test",
&format!("upstreams = [\"{}\"]\ndevice_certs = true\n", echo.url()),
)],
..Default::default()
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while e.exited().is_none() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(50));
}
assert!(
e.exited().is_some_and(|s| !s.success()),
"edge must refuse to start: {}",
e.stderr()
);
}
/// QC M2: a revocation must not depend on control's nudge reaching edge. Edge re-reads the
/// allow list by itself (like the share deny list), within 5 s.
#[tokio::test(flavor = "multi_thread")]
async fn edge_rereads_the_allow_list_by_itself() {
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let req = Req::get("locked.test", "/");
let r =
client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req).await;
assert_eq!(r.unwrap().status, 200);
std::fs::write(edge.dir.join("certs/domi-devices.pem"), "").unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
loop {
let r = client::https_with_cert(edge.https, "locked.test", edge.roots(), &phone, &req)
.await;
if r.is_err() {
break;
}
assert!(
std::time::Instant::now() < deadline,
"edge still accepts a revoked device"
);
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
}
/// QC r2: end to end through Pingora (2 worker threads, pre-TLS hook): a handshake that
/// fails after the resolver (bad ALPN) must not break the next TLS 1.2 device handshake.
#[tokio::test(flavor = "multi_thread")]
async fn qc_tls12_device_after_bad_alpn_handshakes_end_to_end() {
use std::sync::Arc;
let echo = Echo::start("app").await;
let p = pki();
let (phone, phone_pem) = device(&p, "phone");
let edge = setup(&echo, &p, &[&phone_pem]).await;
let roots = edge.roots();
let req = Req::get("locked.test", "/");
let mut failures = Vec::new();
let mut poisoned = 0;
for i in 0..40 {
let addr = edge.https;
let r2 = roots.clone();
let failed = tokio::task::spawn_blocking(move || {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(r2)
.with_no_client_auth();
cfg.alpn_protocols = vec![b"foo".to_vec()];
let mut conn = rustls::ClientConnection::new(
Arc::new(cfg),
rustls_pki_types::ServerName::try_from("open.test".to_owned()).unwrap(),
)
.unwrap();
let mut sock = std::net::TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(std::time::Duration::from_secs(5)))
.unwrap();
let mut r = Ok((0, 0));
for _ in 0..5 {
r = conn.complete_io(&mut sock);
if r.is_err() || !conn.is_handshaking() {
break;
}
}
r.is_err()
})
.await
.unwrap();
if failed {
poisoned += 1;
}
match client::https_with_cert(
edge.https,
"locked.test",
roots.clone(),
&tls12(&phone),
&req,
)
.await
{
Ok(r) if r.status == 200 => {}
other => failures.push(format!("{i}: {other:?}")),
}
}
eprintln!(
"QC poison handshakes that failed: {poisoned}/40; device failures: {}",
failures.len()
);
assert_eq!(poisoned, 40, "the poison handshake must fail");
assert!(
failures.is_empty(),
"{} of 40 TLS 1.2 device handshakes failed: {:?}",
failures.len(),
failures.first()
);
}
}