422 lines
16 KiB
Rust
422 lines
16 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/.
|
|
|
|
//! The Domi CA through control (ROADMAP §6 phase 3, tests first): the first intermediate is
|
|
//! signed offline from control's CSR and installed; `tls = "domi"` hosts then get server
|
|
//! certificates that chain to the root; device certificates need the match code; the install
|
|
//! file works once; revocation takes the device off the allow list; no root key file is ever
|
|
//! in the state directory, and control refuses to start with one there.
|
|
|
|
#![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; run it in WSL2",
|
|
file!()
|
|
);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
mod unix {
|
|
use std::path::Path;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use crate::common::{Env, EnvSpec};
|
|
use ianitor_core::pki;
|
|
use ianitor_testkit::client::{self, Req};
|
|
use ianitor_testkit::upstream::Echo;
|
|
use serde_json::{Value, json};
|
|
|
|
const PASSWORD: &str = "intermediate-test-password-123";
|
|
|
|
fn now() -> i64 {
|
|
std::time::SystemTime::now()
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_secs() as i64
|
|
}
|
|
|
|
/// The offline side: a root that lives only in this test's memory (and its cert file).
|
|
struct Offline {
|
|
root_pem: String,
|
|
root_key: pki::KeyPair,
|
|
}
|
|
|
|
async fn env_with_pki() -> (Env, Offline) {
|
|
let (root_pem, root_key) = pki::create_root(now()).unwrap();
|
|
// Only the root certificate goes next to control; the key stays in this test.
|
|
let extra = |dir: &Path| {
|
|
format!(
|
|
"\n[pki]\nroot_cert = \"{}\"\npassword_credential = \"pki-password\"\nkdf_iterations = 1000\n",
|
|
dir.join("offline-root.crt").display()
|
|
)
|
|
};
|
|
let mut env = Env::new(EnvSpec::default()).await;
|
|
std::fs::write(env.dir.join("offline-root.crt"), &root_pem).unwrap();
|
|
std::fs::write(env.dir.join("creds/pki-password"), PASSWORD).unwrap();
|
|
let text = std::fs::read_to_string(env.config_path()).unwrap() + &extra(&env.dir.join("."));
|
|
std::fs::write(env.config_path(), text).unwrap();
|
|
env.start_control(None);
|
|
(env, Offline { root_pem, root_key })
|
|
}
|
|
|
|
async fn wait_request(env: &Env, id: &str, want: &str) -> Value {
|
|
let deadline = Instant::now() + Duration::from_secs(20);
|
|
loop {
|
|
let r = env
|
|
.call("GET", &format!("/api/v1/pki-requests/{id}"), None)
|
|
.await;
|
|
assert_eq!(r.status, 200, "{}", r.text);
|
|
if r.json["state"] == want {
|
|
return r.json;
|
|
}
|
|
if Instant::now() > deadline {
|
|
panic!(
|
|
"request {id} is {} not {want}\n{}",
|
|
r.json["state"],
|
|
env.control_log()
|
|
);
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
}
|
|
}
|
|
|
|
fn cli(env: &Env, args: &[&str]) -> std::process::Output {
|
|
env.command()
|
|
.args(args)
|
|
.arg("--config")
|
|
.arg(env.config_path())
|
|
.output()
|
|
.unwrap()
|
|
}
|
|
|
|
/// Renew (first intermediate), sign offline, install with the CLI.
|
|
async fn install_intermediate(env: &Env, off: &Offline) -> Value {
|
|
let r = env
|
|
.call(
|
|
"POST",
|
|
"/api/v1/certs/intermediate/renewal",
|
|
Some(json!({})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 202, "{}", r.text);
|
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
|
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
|
// The code the UI shows is the one the offline signer computes from the CSR.
|
|
assert_eq!(
|
|
r.json["match_code"].as_str().unwrap(),
|
|
pki::match_code(&pki::csr_der(&csr).unwrap())
|
|
);
|
|
let r2 = env
|
|
.call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None)
|
|
.await;
|
|
assert_eq!(r2.status, 200);
|
|
assert_eq!(r2.text, csr);
|
|
let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
|
let f = env.dir.join("signed.crt");
|
|
std::fs::write(&f, &signed).unwrap();
|
|
let out = cli(env, &["pki", "install", f.to_str().unwrap()]);
|
|
assert!(
|
|
out.status.success(),
|
|
"{}",
|
|
String::from_utf8_lossy(&out.stderr)
|
|
);
|
|
wait_request(env, &rid, "approved").await
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn first_intermediate_from_an_offline_signature_then_domi_hosts_chain_to_the_root() {
|
|
let (env, off) = env_with_pki().await;
|
|
let ov = env.call("GET", "/api/v1/overview", None).await;
|
|
assert_eq!(ov.json["intermediate"]["state"], "missing", "{}", ov.text);
|
|
|
|
// Before an intermediate exists a domi host cannot get a certificate.
|
|
let echo = Echo::start("domi").await;
|
|
let host = json!({"host": {"hostname": "fresh.test", "upstreams": [echo.url()], "tls": "domi", "auth": "none"}});
|
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host.clone())).await;
|
|
assert_eq!(rec["state"], "failed", "{rec}");
|
|
assert_eq!(rec["reason"]["code"], "pki.no_intermediate", "{rec}");
|
|
|
|
install_intermediate(&env, &off).await;
|
|
let ov = env.call("GET", "/api/v1/overview", None).await;
|
|
assert_eq!(ov.json["intermediate"]["state"], "ok", "{}", ov.text);
|
|
assert!(ov.json["intermediate"]["days_left"].as_i64().unwrap() >= 364);
|
|
|
|
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
|
|
assert_eq!(rec["state"], "kept", "{rec}\n{}", env.control_log());
|
|
// The served certificate chains to the Domi root (only the root is trusted here).
|
|
let roots = ianitor_testkit::tls::roots_from_pem(&off.root_pem);
|
|
let edge = env.edge.as_ref().unwrap();
|
|
let r = client::https(
|
|
edge.https,
|
|
"fresh.test",
|
|
roots,
|
|
&Req::get("fresh.test", "/"),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(r.status, 200);
|
|
let crt = std::fs::read_to_string(env.dir.join("certs/fresh.test.crt")).unwrap();
|
|
let info = pki::inspect(&crt).unwrap();
|
|
assert_eq!(info.dns_names, vec!["fresh.test".to_owned()]);
|
|
assert_eq!(
|
|
(info.not_after - now()) / 86_400,
|
|
i64::from(pki::SERVER_DAYS) - 1
|
|
);
|
|
|
|
// No root key anywhere control writes.
|
|
let key_pem = off.root_key.serialize_pem();
|
|
let body: String = key_pem
|
|
.lines()
|
|
.filter(|l| !l.starts_with("-----"))
|
|
.collect();
|
|
for d in ["state", "certs", "edge", "caddy", "edge-state"] {
|
|
for f in walk(&env.dir.join(d)) {
|
|
let bytes = std::fs::read(&f).unwrap();
|
|
let text = String::from_utf8_lossy(&bytes);
|
|
assert!(
|
|
!text.contains(&body[..40]),
|
|
"root key material in {}",
|
|
f.display()
|
|
);
|
|
assert!(
|
|
!contains(&bytes, &off.root_key.serialize_der()),
|
|
"root key DER in {}",
|
|
f.display()
|
|
);
|
|
}
|
|
}
|
|
// The intermediate key is only stored encrypted.
|
|
let k = std::fs::read_to_string(env.dir.join("state/pki/intermediate.key")).unwrap();
|
|
assert!(k.contains(concat!("IANITOR ENCRYPTED ", "PRIVATE KEY")));
|
|
assert!(!k.contains(concat!("BEGIN ", "PRIVATE KEY")));
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_wrong_certificate_is_not_installed() {
|
|
let (env, off) = env_with_pki().await;
|
|
let r = env
|
|
.call(
|
|
"POST",
|
|
"/api/v1/certs/intermediate/renewal",
|
|
Some(json!({})),
|
|
)
|
|
.await;
|
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
|
let csr = r.json["csr_pem"].as_str().unwrap().to_owned();
|
|
// Signed by another root.
|
|
let (other, other_key) = pki::create_root(now()).unwrap();
|
|
let wrong = pki::sign_intermediate(&other, &other_key, &csr, now()).unwrap();
|
|
let r = env
|
|
.call(
|
|
"PUT",
|
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
|
Some(json!({"certificate_pem": wrong})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 422, "{}", r.text);
|
|
assert_eq!(r.json["error"]["code"], "pki.not_our_root");
|
|
// For another key.
|
|
let k = pki::generate_key().unwrap();
|
|
let other_csr = pki::intermediate_csr(&k, pki::INTERMEDIATE_CN).unwrap();
|
|
let wrong =
|
|
pki::sign_intermediate(&off.root_pem, &off.root_key, &other_csr, now()).unwrap();
|
|
let r = env
|
|
.call(
|
|
"PUT",
|
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
|
Some(json!({"certificate_pem": wrong})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 422, "{}", r.text);
|
|
assert_eq!(r.json["error"]["code"], "pki.wrong_key");
|
|
// A leaf is not an intermediate.
|
|
let r = env
|
|
.call(
|
|
"PUT",
|
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
|
Some(json!({"certificate_pem": "garbage"})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 422, "{}", r.text);
|
|
let st = env
|
|
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
|
.await;
|
|
assert_eq!(st.json["state"], "waiting");
|
|
// The right one through the API works too.
|
|
let good = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap();
|
|
let r = env
|
|
.call(
|
|
"PUT",
|
|
&format!("/api/v1/pki-requests/{rid}/certificate"),
|
|
Some(json!({"certificate_pem": good})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 200, "{}", r.text);
|
|
assert_eq!(r.json["state"], "approved");
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn device_certificate_needs_the_match_code_and_installs_once() {
|
|
let (env, off) = env_with_pki().await;
|
|
install_intermediate(&env, &off).await;
|
|
let r = env
|
|
.call(
|
|
"POST",
|
|
"/api/v1/certs/devices",
|
|
Some(json!({"name": "Mark's phone", "kind": "phone"})),
|
|
)
|
|
.await;
|
|
assert_eq!(r.status, 202, "{}", r.text);
|
|
let rid = r.json["request_id"].as_str().unwrap().to_owned();
|
|
let code = r.json["match_code"].as_str().unwrap().to_owned();
|
|
assert_eq!(code.len(), 8, "{code}");
|
|
// The same name again while it waits: refused.
|
|
let again = env
|
|
.call(
|
|
"POST",
|
|
"/api/v1/certs/devices",
|
|
Some(json!({"name": "mark's PHONE", "kind": "phone"})),
|
|
)
|
|
.await;
|
|
assert_eq!(again.status, 409, "{}", again.text);
|
|
assert_eq!(again.json["error"]["code"], "pki.device_name_taken");
|
|
|
|
// A wrong code does nothing.
|
|
let wrong = if code.starts_with('0') {
|
|
"11 11 11"
|
|
} else {
|
|
"00 00 00"
|
|
};
|
|
let out = cli(&env, &["pki", "approve", wrong]);
|
|
assert!(!out.status.success());
|
|
tokio::time::sleep(Duration::from_millis(2500)).await;
|
|
let st = env
|
|
.call("GET", &format!("/api/v1/pki-requests/{rid}"), None)
|
|
.await;
|
|
assert_eq!(st.json["state"], "waiting");
|
|
|
|
let out = cli(&env, &["pki", "approve", &code]);
|
|
assert!(
|
|
out.status.success(),
|
|
"{}",
|
|
String::from_utf8_lossy(&out.stderr)
|
|
);
|
|
let done = wait_request(&env, &rid, "approved").await;
|
|
let did = done["device_id"].as_str().unwrap().to_owned();
|
|
|
|
let certs = env.call("GET", "/api/v1/certs", None).await;
|
|
assert_eq!(certs.status, 200, "{}", certs.text);
|
|
assert_eq!(certs.json["root"]["offline"], true);
|
|
let dev = certs.json["devices"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|d| d["id"] == did.as_str())
|
|
.unwrap()
|
|
.clone();
|
|
assert_eq!(dev["state"], "valid");
|
|
assert_eq!(dev["name"], "Mark's phone");
|
|
|
|
// The allow list both engines read has it.
|
|
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
|
assert!(allow.contains("BEGIN CERTIFICATE"));
|
|
|
|
// One-time install file.
|
|
let b = env
|
|
.call(
|
|
"POST",
|
|
&format!("/api/v1/certs/devices/{did}/bundle"),
|
|
Some(json!({"format": "qr"})),
|
|
)
|
|
.await;
|
|
assert_eq!(b.status, 200, "{}", b.text);
|
|
let url = b.json["download_url"].as_str().unwrap().to_owned();
|
|
let password = b.json["one_time_password"].as_str().unwrap().to_owned();
|
|
assert!(b.json["qr_svg"].as_str().unwrap().starts_with("<?xml"));
|
|
let path = url
|
|
.split_once("/api/v1/")
|
|
.map(|(_, p)| format!("/api/v1/{p}"))
|
|
.unwrap();
|
|
// No token needed for the download itself (the link is the secret) ...
|
|
let d = env.call_with("GET", &path, &[], None).await;
|
|
assert_eq!(d.status, 200, "{}", d.text);
|
|
assert_eq!(d.header("content-type"), Some("application/x-pkcs12"));
|
|
let ks = p12_keystore::KeyStore::from_pkcs12(
|
|
&d.body,
|
|
&password,
|
|
p12_keystore::Pkcs12ImportPolicy::Strict,
|
|
)
|
|
.unwrap();
|
|
let (_, chain) = ks.private_key_chain().unwrap();
|
|
assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root");
|
|
// ... and it works only once.
|
|
let d = env.call_with("GET", &path, &[], None).await;
|
|
assert_eq!(d.status, 410, "{}", d.text);
|
|
assert_eq!(d.json["error"]["code"], "pki.bundle_used");
|
|
|
|
// Revoke: off the allow list, no new install file.
|
|
let r = env
|
|
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
|
|
.await;
|
|
assert_eq!(r.status, 204, "{}", r.text);
|
|
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
|
|
assert!(!allow.contains("BEGIN CERTIFICATE"), "{allow}");
|
|
let b = env
|
|
.call(
|
|
"POST",
|
|
&format!("/api/v1/certs/devices/{did}/bundle"),
|
|
Some(json!({"format": "p12"})),
|
|
)
|
|
.await;
|
|
assert_eq!(b.status, 409, "{}", b.text);
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn control_refuses_to_start_with_a_root_key_in_its_state_dir() {
|
|
let (mut env, off) = env_with_pki().await;
|
|
env.kill_control();
|
|
std::fs::write(env.dir.join("state/root.key"), off.root_key.serialize_pem()).unwrap();
|
|
let out = env
|
|
.command()
|
|
.arg("--config")
|
|
.arg(env.config_path())
|
|
.output()
|
|
.unwrap();
|
|
assert!(!out.status.success());
|
|
let err = String::from_utf8_lossy(&out.stderr);
|
|
assert!(err.contains("root"), "{err}");
|
|
// And the message never prints the key.
|
|
assert!(!err.contains("PRIVATE KEY"), "{err}");
|
|
}
|
|
|
|
fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
|
|
let mut out = Vec::new();
|
|
let mut stack = vec![dir.to_path_buf()];
|
|
while let Some(d) = stack.pop() {
|
|
let Ok(rd) = std::fs::read_dir(&d) else {
|
|
continue;
|
|
};
|
|
for e in rd.flatten() {
|
|
let p = e.path();
|
|
if p.is_dir() {
|
|
stack.push(p);
|
|
} else {
|
|
out.push(p);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
|
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
|
}
|
|
}
|