[edge] Tests first: a Domi device cert is accepted for mTLS, a self-signed one with the same subject, an unlisted one and none are not (red)

This commit is contained in:
2026-11-07 22:46:08 +01:00
parent 18da3f5d5a
commit 4054427b62
5 changed files with 293 additions and 0 deletions
Generated
+1
View File
@@ -1124,6 +1124,7 @@ dependencies = [
"instant-acme",
"log",
"pingora",
"rcgen",
"ring",
"rustls",
"rustls-pki-types",
+1
View File
@@ -36,6 +36,7 @@ form_urlencoded = "1.2"
[dev-dependencies]
ianitor-testkit.workspace = true
ring.workspace = true
rcgen.workspace = true
[lints]
workspace = true
+6
View File
@@ -108,6 +108,8 @@ pub struct EdgeSpec<'a> {
pub extra_args: Vec<String>,
/// Fixed HTTP port (e.g. one Pebble was told to validate against).
pub http_port: Option<u16>,
/// Extra files written into the edge directory before it starts (path relative to it).
pub files: Vec<(String, Vec<u8>)>,
}
impl Default for EdgeSpec<'_> {
@@ -119,6 +121,7 @@ impl Default for EdgeSpec<'_> {
log_level: "info",
extra_args: Vec::new(),
http_port: None,
files: Vec::new(),
}
}
}
@@ -165,6 +168,9 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
}
let ca = TestCa::new("Ianitor Test CA");
std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap();
for (path, value) in &spec.files {
std::fs::write(dir.join(path), value).unwrap();
}
for (name, value) in &spec.secrets {
std::fs::write(dir.join(&format!("creds/{name}")), value).unwrap();
}
+239
View File
@@ -0,0 +1,239 @@
// 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;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner); run it in WSL2, see CLAUDE.md",
file!()
);
}
#[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_a_403_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
.unwrap();
assert_eq!(r.status, 403);
assert!(echo.requests().is_empty());
// The Host header cannot move a certificate-less connection onto the locked host.
let r = client::https(
edge.https,
"open.test",
edge.roots(),
&Req::get("locked.test", "/"),
)
.await
.unwrap();
assert_ne!(r.status, 200);
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()
);
}
}
+46
View File
@@ -265,3 +265,49 @@ pub async fn websocket(
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "websocket timed out"))?
}
/// A client identity for mTLS: a PEM chain (leaf first) and its PEM private key.
#[derive(Debug, Clone)]
pub struct ClientCert {
pub chain_pem: String,
pub key_pem: String,
/// Offer only TLS 1.2 (client certificates take a different path there).
pub tls12_only: bool,
}
/// One request over a fresh TLS connection that presents `cert` if the server asks for one.
pub async fn https_with_cert(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
cert: &ClientCert,
req: &Req,
) -> io::Result<Resp> {
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
crate::tls::install_crypto();
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(cert.chain_pem.as_bytes())
.collect::<Result<_, _>>()
.map_err(other)?;
let key = PrivateKeyDer::from_pem_slice(cert.key_pem.as_bytes()).map_err(other)?;
let versions: &[&rustls::SupportedProtocolVersion] = if cert.tls12_only {
&[&rustls::version::TLS12]
} else {
rustls::DEFAULT_VERSIONS
};
let mut cfg = rustls::ClientConfig::builder_with_protocol_versions(versions)
.with_root_certificates(roots)
.with_client_auth_cert(chain, key)
.map_err(other)?;
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
let connector = TlsConnector::from(Arc::new(cfg));
tokio::time::timeout(TIMEOUT, async {
let tcp = TcpStream::connect(addr).await?;
let name = ServerName::try_from(sni.to_owned()).map_err(other)?;
let s = connector.connect(name, tcp).await?;
send(s, req).await
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}