[tests] Tests first, fix round 3: a revocation during a watch is in force at once (Pingora) or when the apply ends (Caddy), a device revoked under Caddy is refused, caddy-revert with Pingora serving clears a stale deadline (red)

This commit is contained in:
2026-11-08 12:21:36 +01:00
parent 057abbc954
commit 09b8313a04
+334
View File
@@ -758,4 +758,338 @@ esac
);
assert_eq!(visit(&ce.env, ce.https, "a.test").await, 200);
}
/// QC r3: a device revoked while Caddy serves. Control rewrites the allow list and loads
/// caddy.json (must-revalidate); the revoked device must no longer get in, the newly
/// allowed one must.
#[tokio::test(flavor = "multi_thread")]
async fn qc_device_revoked_under_caddy_is_refused() {
use ianitor_core::pki;
use ianitor_testkit::client::{self, ClientCert, Req};
let Some(ce) = env_with_caddy().await else {
return;
};
let env = &ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root, rk) = pki::create_root(now).unwrap();
let k = pki::generate_key().unwrap();
let csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
let int =
pki::Intermediate::new(&pki::sign_intermediate(&root, &rk, &csr, now).unwrap(), k)
.unwrap();
let phone = pki::issue_device(&int, "phone", now).unwrap();
let laptop = pki::issue_device(&int, "laptop", now).unwrap();
std::fs::write(env.dir.join("certs/domi-devices-ca.pem"), int.cert_pem()).unwrap();
std::fs::write(env.dir.join("certs/domi-devices.pem"), &phone.cert_pem).unwrap();
let cc = |d: &pki::Issued| ClientCert {
chain_pem: d.chain_pem.clone(),
key_pem: d.key_pem.clone(),
tls12_only: false,
};
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply("POST", "/api/v1/hosts", Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})))
.await;
assert_eq!(rec["state"], "kept", "{rec}");
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202);
wait_engine(env, "caddy").await;
let visit_as = |d: &pki::Issued| {
let c = cc(d);
let roots = env.ca.roots();
async move {
match client::https_with_cert(
ce.https,
"d.test",
roots,
&c,
&Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
};
let before = visit_as(&phone).await;
eprintln!("QC phone under Caddy before revocation: {before}");
assert_eq!(before, 200);
// Revoke the phone, allow the laptop; tell Caddy the way control does.
std::fs::write(env.dir.join("certs/domi-devices.pem"), &laptop.cert_pem).unwrap();
let sock = env.dir.join("caddy/admin.sock");
let text = std::fs::read(env.dir.join("caddy/caddy.json")).unwrap();
ianitor_control::caddy_link::load(&sock, &text)
.await
.unwrap();
assert!(
ianitor_control::caddy_link::runs(&sock, &text)
.await
.unwrap()
);
let phone_after = visit_as(&phone).await;
let laptop_after = visit_as(&laptop).await;
eprintln!("QC after revocation under Caddy: phone {phone_after}, laptop {laptop_after}");
assert_ne!(phone_after, 200, "revoked phone still gets in under Caddy");
assert_eq!(
laptop_after, 200,
"newly allowed laptop is not let in under Caddy"
);
}
// ---------------------------------------------------------------- fix round 3
/// A control with the Domi CA, an intermediate signed by a test root, one device issued
/// and approved, and `d.test` asking for device certificates. With `caddy`, Caddy serves.
struct PkiEnv {
ce: CaddyEnv,
roots: std::sync::Arc<rustls::RootCertStore>,
device_id: String,
device: ianitor_testkit::client::ClientCert,
}
async fn pki_env(watch_secs: u64, caddy: bool) -> Option<PkiEnv> {
use ianitor_core::pki;
let ce = caddy_env(watch_secs, true).await?;
let mut ce = ce;
let env = &mut ce.env;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let (root_pem, root_key) = pki::create_root(now).unwrap();
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
std::fs::write(
env.dir.join("creds/pki-password"),
"round-three-password-123",
)
.unwrap();
let text = std::fs::read_to_string(env.config_path()).unwrap()
+ &format!(
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
env.dir.join("offline-root.crt").display()
);
std::fs::write(env.config_path(), text).unwrap();
env.kill_control();
env.start_control(None);
let cli = |env: &Env, args: &[&str]| {
env.command()
.args(args)
.arg("--config")
.arg(env.config_path())
.output()
.unwrap()
};
// The intermediate, signed offline.
let r = env
.call(
"POST",
"/api/v1/certs/intermediate/renewal",
Some(json!({})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
let signed = pki::sign_intermediate(&root_pem, &root_key, &csr, now).unwrap();
std::fs::write(env.dir.join("int.crt"), signed).unwrap();
let int_path = env.dir.join("int.crt").display().to_string();
let out = cli(env, &["pki", "install", &int_path]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
// One device.
let r = env
.call(
"POST",
"/api/v1/certs/devices",
Some(json!({"name": "phone", "kind": "phone"})),
)
.await;
assert_eq!(r.status, 202, "{}", r.text);
let code = r.json["match_code"].as_str().unwrap().to_owned();
let out = cli(env, &["pki", "approve", &code]);
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let devices: Value = serde_json::from_str(
&std::fs::read_to_string(env.dir.join("state/pki/devices.json")).unwrap(),
)
.unwrap();
let d = &devices[0];
let device_id = d["id"].as_str().unwrap().to_owned();
let sealed =
std::fs::read_to_string(env.dir.join(&format!("state/pki/devices/{device_id}.key")))
.unwrap();
let key = pki::decrypt_key(&sealed, b"round-three-password-123").unwrap();
let int_pem = std::fs::read_to_string(env.dir.join("state/pki/intermediate.crt")).unwrap();
let device = ianitor_testkit::client::ClientCert {
chain_pem: format!("{}{int_pem}", d["cert_pem"].as_str().unwrap()),
key_pem: key.serialize_pem(),
tls12_only: false,
};
let mut store = rustls::RootCertStore::empty();
store
.add(rustls_pki_types::CertificateDer::from(
pki::chain_der(&root_pem).unwrap().remove(0),
))
.unwrap();
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let rec = env
.apply(
"POST",
"/api/v1/hosts",
Some(json!({"host": {"hostname": "d.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none", "device_certs": true}})),
)
.await;
assert_eq!(rec["state"], "kept", "{rec}");
// The echo upstream must outlive this function: keep it running in the background.
std::mem::forget(echo);
if caddy {
let r = env
.call("POST", "/api/v1/engine", Some(json!({"target": "caddy"})))
.await;
assert_eq!(r.status, 202, "{}", r.text);
wait_engine(env, "caddy").await;
}
Some(PkiEnv {
ce,
roots: std::sync::Arc::new(store),
device_id,
device,
})
}
impl PkiEnv {
async fn visit_as_device(&self, at: std::net::SocketAddr) -> u16 {
match ianitor_testkit::client::https_with_cert(
at,
"d.test",
self.roots.clone(),
&self.device,
&ianitor_testkit::client::Req::get("d.test", "/"),
)
.await
{
Ok(r) => r.status,
Err(_) => 0,
}
}
fn serving(&self, caddy: bool) -> std::net::SocketAddr {
if caddy {
self.ce.https
} else {
self.ce.env.edge.as_ref().unwrap().https
}
}
}
/// Fix round 3 (QC r3 Major): a revocation never waits for a running apply. The DELETE
/// answers at once, the allow list is on disk at once, and the device is refused within
/// edge's backstop window although an apply is still watching.
async fn revoke_during_a_watch(caddy: bool) {
let Some(p) = pki_env(6, caddy).await else {
return;
};
let env = &p.ce.env;
let at = p.serving(caddy);
assert_eq!(p.visit_as_device(at).await, 200, "the device gets in");
let echo = ianitor_testkit::upstream::Echo::start("app").await;
let r = env.call("POST", "/api/v1/hosts", Some(b_host(&echo))).await;
assert_eq!(r.status, 202, "{}", r.text);
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
wait_state(env, &id, "watching").await;
let t = Instant::now();
let d = env
.call(
"DELETE",
&format!("/api/v1/certs/devices/{}", p.device_id),
None,
)
.await;
let took = t.elapsed();
assert_eq!(d.status, 204, "{}", d.text);
assert!(
took < Duration::from_millis(1500),
"the DELETE waited {took:?}"
);
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
let listed = p
.device
.chain_pem
.split("-----END CERTIFICATE-----")
.next()
.unwrap();
assert!(
!allow.contains(listed.trim()),
"the revoked device is still on the list"
);
if caddy {
// Caddy keeps the trial until the apply ends; then the device is out at once.
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
assert_ne!(
p.visit_as_device(at).await,
200,
"revoked device still gets in under Caddy"
);
} else {
let deadline = Instant::now() + Duration::from_secs(6);
while p.visit_as_device(at).await == 200 {
assert!(
Instant::now() < deadline,
"revoked device still gets in under Pingora"
);
tokio::time::sleep(Duration::from_millis(250)).await;
}
let rec = env.wait_apply(&id).await;
assert_eq!(rec["state"], "kept", "{rec}");
}
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_at_once_under_pingora() {
revoke_during_a_watch(false).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_revocation_during_a_watch_is_in_force_when_the_apply_ends_under_caddy() {
revoke_during_a_watch(true).await;
}
/// Fix round 3, minor 3: with Pingora serving, a deadline file left behind is cleared and
/// caddy-revert succeeds (the unit must not show failed).
#[tokio::test(flavor = "multi_thread")]
async fn caddy_revert_with_pingora_serving_clears_a_stale_deadline() {
let mut env = env().await;
env.kill_control();
std::fs::write(
env.dir.join("state/caddy-trial.json"),
r#"{"apply_id":"ch_x","deadline":1}"#,
)
.unwrap();
let out = env
.command()
.args(["caddy-revert", "--config"])
.arg(env.config_path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(!env.dir.join("state/caddy-trial.json").exists());
}
}