From cde0c3ea3b7e750be9a39f476a1cd2a8b7ceb337 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 22:40:56 +0100 Subject: [PATCH] [core] Tests first: the Domi CA chains to the root, a leaf cannot sign, expired and wrong-name certs are rejected (red) --- Cargo.lock | 5 + crates/core/Cargo.toml | 7 + crates/core/src/lib.rs | 1 + crates/core/src/pki.rs | 75 +++++++++ crates/core/tests/pki.rs | 317 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 405 insertions(+) create mode 100644 crates/core/src/pki.rs create mode 100644 crates/core/tests/pki.rs diff --git a/Cargo.lock b/Cargo.lock index 76ea7d2..a037d97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1080,13 +1080,18 @@ name = "ianitor-core" version = "0.1.0" dependencies = [ "base64 0.22.1", + "rcgen", "ring", + "rustls-pki-types", + "rustls-webpki", "serde", "serde_json", "thiserror 2.0.21", + "time", "toml", "unicode-normalization", "url", + "x509-parser 0.18.1", ] [[package]] diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 4c526bc..ff25605 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -16,6 +16,13 @@ url.workspace = true ring.workspace = true base64.workspace = true unicode-normalization = "0.1.24" +rcgen = { workspace = true, features = ["x509-parser"] } +x509-parser = { version = "0.18", features = ["verify"] } +time = { version = "0.3", default-features = false } + +[dev-dependencies] +rustls-pki-types.workspace = true +webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = ["ring", "std"] } [lints] workspace = true diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c3536b0..743c483 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,6 +10,7 @@ pub mod compile; pub mod edge_config; +pub mod pki; mod error; mod model; pub mod routes; diff --git a/crates/core/src/pki.rs b/crates/core/src/pki.rs new file mode 100644 index 0000000..7b85f42 --- /dev/null +++ b/crates/core/src/pki.rs @@ -0,0 +1,75 @@ +// 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. Interface only; the implementation follows the tests (red commit). + +pub const ROOT_DAYS: u32 = 3653; +pub const INTERMEDIATE_DAYS: u32 = 365; +pub const SERVER_DAYS: u32 = 90; +pub const SERVER_RENEW_DAYS: u32 = 30; +pub const DEVICE_DAYS: u32 = 365; +pub const ROOT_CN: &str = "Domi PKI Root"; +pub const INTERMEDIATE_CN: &str = "Ianitor Domi Intermediate"; +pub const KEY_KDF_ITERATIONS: u32 = 0; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PkiError { + #[error("not built yet")] + NotBuilt, + #[error("bad certificate")] + BadCertificate(String), + #[error("bad csr")] + BadCsr, + #[error("csr subject")] + CsrSubject, + #[error("bad key")] + BadKey, + #[error("not a ca")] + NotCa, + #[error("key mismatch")] + KeyMismatch, + #[error("issuer expired")] + IssuerExpired, + #[error("wrong password")] + WrongPassword, +} + +#[derive(Debug)] +pub struct KeyPair; +impl KeyPair { + pub fn serialize_pem(&self) -> String { String::new() } + pub fn from_pem(_: &str) -> Result { Err(PkiError::NotBuilt) } + pub fn public_key_der(&self) -> Vec { Vec::new() } +} +pub fn generate_key() -> Result { Err(PkiError::NotBuilt) } +pub fn create_root(_: i64) -> Result<(String, KeyPair), PkiError> { Err(PkiError::NotBuilt) } +pub fn intermediate_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn sign_intermediate(_: &str, _: &KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +#[derive(Debug)] +pub struct Intermediate; +impl Intermediate { + pub fn new(_: &str, _: KeyPair) -> Result { Err(PkiError::NotBuilt) } + pub fn cert_pem(&self) -> &str { "" } + pub fn not_after(&self) -> i64 { 0 } +} +#[derive(Debug)] +pub struct Issued { pub cert_pem: String, pub chain_pem: String, pub key_pem: String } +pub fn issue_server(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +pub fn issue_device(_: &Intermediate, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } +#[derive(Debug)] +pub struct CertInfo { pub subject_cn: String, pub not_after: i64, pub is_ca: bool, pub path_len: Option, pub dns_names: Vec } +pub fn inspect(_: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn public_key_der(_: &str) -> Result, PkiError> { Err(PkiError::NotBuilt) } +pub fn issued_by(_: &str, _: &str) -> Result { Err(PkiError::NotBuilt) } +pub fn match_code(_: &[u8]) -> String { String::new() } +pub fn encrypt_key_with(_: &KeyPair, _: &[u8], _: u32) -> Result { Err(PkiError::NotBuilt) } +pub fn decrypt_key(_: &str, _: &[u8]) -> Result { Err(PkiError::NotBuilt) } +#[doc(hidden)] +pub mod testing { + use super::*; + pub fn sign_as(_: &str, _: KeyPair, _: &str, _: i64) -> Result { Err(PkiError::NotBuilt) } + pub fn sub_ca(_: &Intermediate, _: &KeyPair, _: i64) -> Result { Err(PkiError::NotBuilt) } + pub fn greedy_csr(_: &KeyPair, _: &str) -> Result { Err(PkiError::NotBuilt) } + pub fn tamper_csr(s: &str) -> String { s.to_owned() } +} diff --git a/crates/core/tests/pki.rs b/crates/core/tests/pki.rs new file mode 100644 index 0000000..df4baf0 --- /dev/null +++ b/crates/core/tests/pki.rs @@ -0,0 +1,317 @@ +// 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 (ROADMAP §6 phase 3, tests first): issued chains validate to the root, a leaf +//! cannot sign, expired and wrong-name certificates are rejected, an intermediate is never +//! made from a CSR's own wishes, and encrypted keys need their password. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::pki::{ + self, DEVICE_DAYS, INTERMEDIATE_DAYS, Intermediate, PkiError, ROOT_DAYS, SERVER_DAYS, +}; +use rustls_pki_types::{CertificateDer, ServerName, UnixTime}; +use webpki::{EndEntityCert, KeyUsage, anchor_from_trusted_cert}; + +const NOW: i64 = 1_800_000_000; +const DAY: i64 = 86_400; + +fn der(pem: &str) -> CertificateDer<'static> { + use rustls_pki_types::pem::PemObject; + CertificateDer::pem_slice_iter(pem.as_bytes()) + .next() + .unwrap() + .unwrap() +} + +fn all_der(pem: &str) -> Vec> { + use rustls_pki_types::pem::PemObject; + CertificateDer::pem_slice_iter(pem.as_bytes()) + .collect::>() + .unwrap() +} + +fn at(t: i64) -> UnixTime { + UnixTime::since_unix_epoch(std::time::Duration::from_secs(t as u64)) +} + +struct Ca { + root_pem: String, + root_key: pki::KeyPair, + int: Intermediate, +} + +fn ca() -> Ca { + let (root_pem, root_key) = pki::create_root(NOW).unwrap(); + let int_key = pki::generate_key().unwrap(); + let csr = pki::intermediate_csr(&int_key, pki::INTERMEDIATE_CN).unwrap(); + let int_pem = pki::sign_intermediate(&root_pem, &root_key, &csr, NOW).unwrap(); + let int = Intermediate::new(&int_pem, int_key).unwrap(); + Ca { + root_pem, + root_key, + int, + } +} + +/// Verify `leaf_chain` (leaf first, then intermediates) against `root` at time `t`. +fn verify( + root_pem: &str, + leaf_chain: &str, + t: i64, + usage: KeyUsage, +) -> Result<(), webpki::Error> { + let root = der(root_pem); + let anchor = anchor_from_trusted_cert(&root).unwrap().to_owned(); + let chain = all_der(leaf_chain); + let ee = EndEntityCert::try_from(&chain[0]).unwrap(); + ee.verify_for_usage( + webpki::ALL_VERIFICATION_ALGS, + &[anchor], + &chain[1..], + at(t), + usage, + None, + None, + ) + .map(|_| ()) +} + +#[test] +fn root_is_a_ten_year_ca_with_path_length_one() { + let (root_pem, _) = pki::create_root(NOW).unwrap(); + let info = pki::inspect(&root_pem).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(1)); + assert!(info.path_len.unwrap() >= 1, "ROADMAP §3: pathLenConstraint >= 1"); + assert_eq!(info.subject_cn, pki::ROOT_CN); + let days = (info.not_after - NOW) / DAY; + assert!((ROOT_DAYS as i64 - 1..=ROOT_DAYS as i64).contains(&days), "{days}"); + assert!(days >= 3650); +} + +#[test] +fn intermediate_is_one_year_path_length_zero_and_signed_by_the_root() { + let c = ca(); + let info = pki::inspect(c.int.cert_pem()).unwrap(); + assert!(info.is_ca); + assert_eq!(info.path_len, Some(0)); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + assert!(pki::issued_by(c.int.cert_pem(), &c.root_pem).unwrap()); + assert!(!pki::issued_by(&c.root_pem, c.int.cert_pem()).unwrap()); +} + +#[test] +fn server_chain_validates_to_the_root() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap(); + let info = pki::inspect(&leaf.cert_pem).unwrap(); + assert!(!info.is_ca); + assert_eq!(info.dns_names, vec!["wiki.home.test".to_owned()]); + assert_eq!((info.not_after - NOW) / DAY, SERVER_DAYS as i64); + // The key belongs to the certificate. + let k = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + assert_eq!(pki::public_key_der(&leaf.cert_pem).unwrap(), k.public_key_der()); +} + +#[test] +fn device_chain_validates_for_client_auth_only() { + let c = ca(); + let dev = pki::issue_device(&c.int, "Mark's phone", NOW).unwrap(); + verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::client_auth()).unwrap(); + assert!( + verify(&c.root_pem, &dev.chain_pem, NOW + DAY, KeyUsage::server_auth()).is_err(), + "a device certificate cannot serve a site" + ); + let info = pki::inspect(&dev.cert_pem).unwrap(); + assert_eq!(info.subject_cn, "Mark's phone"); + assert_eq!((info.not_after - NOW) / DAY, DEVICE_DAYS as i64); +} + +#[test] +fn a_leaf_cannot_sign() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + // Ianitor refuses to use a leaf as an issuer. + assert!(matches!( + Intermediate::new(&leaf.cert_pem, leaf_key), + Err(PkiError::NotCa) + )); + // And a certificate forged with the leaf key as issuer does not validate. + let leaf_key = pki::KeyPair::from_pem(&leaf.key_pem).unwrap(); + let forged = pki::testing::sign_as(&leaf.cert_pem, leaf_key, "evil.home.test", NOW).unwrap(); + let chain = format!("{forged}{}", leaf.chain_pem); + let e = verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).unwrap_err(); + assert!( + matches!( + e, + webpki::Error::EndEntityUsedAsCa + | webpki::Error::CaUsedAsEndEntity + | webpki::Error::UnknownIssuer + ), + "{e:?}" + ); +} + +#[test] +fn intermediate_cannot_make_another_ca() { + // pathLen 0: a CA below the intermediate is not trusted. + let c = ca(); + let sub_key = pki::generate_key().unwrap(); + let sub = pki::testing::sub_ca(&c.int, &sub_key, NOW).unwrap(); + let leaf = pki::testing::sign_as(&sub, sub_key, "deep.home.test", NOW).unwrap(); + let chain = format!("{leaf}{sub}{}", c.int.cert_pem()); + assert!(verify(&c.root_pem, &chain, NOW + DAY, KeyUsage::server_auth()).is_err()); +} + +#[test] +fn expired_certificates_are_rejected() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let after = NOW + (SERVER_DAYS as i64 + 1) * DAY; + assert!(matches!( + verify(&c.root_pem, &leaf.chain_pem, after, KeyUsage::server_auth()), + Err(webpki::Error::CertExpired { .. }) + )); + let before = NOW - DAY; + assert!(verify(&c.root_pem, &leaf.chain_pem, before, KeyUsage::server_auth()).is_err()); +} + +#[test] +fn wrong_name_is_rejected() { + let c = ca(); + let leaf = pki::issue_server(&c.int, "wiki.home.test", NOW).unwrap(); + let ee_der = der(&leaf.cert_pem); + let ee = EndEntityCert::try_from(&ee_der).unwrap(); + ee.verify_is_valid_for_subject_name(&ServerName::try_from("wiki.home.test").unwrap()) + .unwrap(); + assert!( + ee.verify_is_valid_for_subject_name(&ServerName::try_from("photos.home.test").unwrap()) + .is_err() + ); + assert!( + ee.verify_is_valid_for_subject_name(&ServerName::try_from("home.test").unwrap()) + .is_err() + ); +} + +#[test] +fn a_certificate_from_another_root_is_rejected() { + let c = ca(); + let other = ca(); + let leaf = pki::issue_server(&other.int, "wiki.home.test", NOW).unwrap(); + // Both CAs have the same names, so webpki finds the issuer by name and then the + // signature check fails. + let e = verify(&c.root_pem, &leaf.chain_pem, NOW + DAY, KeyUsage::server_auth()).unwrap_err(); + assert!( + matches!( + e, + webpki::Error::UnknownIssuer + | webpki::Error::InvalidSignatureForPublicKey + ), + "{e:?}" + ); +} + +#[test] +fn leaves_never_outlive_the_intermediate() { + let c = ca(); + let late = NOW + (INTERMEDIATE_DAYS as i64 - 10) * DAY; + let leaf = pki::issue_device(&c.int, "tablet", late).unwrap(); + let info = pki::inspect(&leaf.cert_pem).unwrap(); + assert!(info.not_after <= c.int.not_after()); + // An expired intermediate issues nothing. + let gone = NOW + (INTERMEDIATE_DAYS as i64 + 1) * DAY; + assert!(matches!( + pki::issue_server(&c.int, "wiki.home.test", gone), + Err(PkiError::IssuerExpired) + )); +} + +#[test] +fn the_intermediate_ignores_what_the_csr_asks_for() { + let (root_pem, root_key) = pki::create_root(NOW).unwrap(); + let key = pki::generate_key().unwrap(); + // A CSR asking to be a CA with no path limit, for 50 years, for a web name. + let greedy = pki::testing::greedy_csr(&key, pki::INTERMEDIATE_CN).unwrap(); + let pem = pki::sign_intermediate(&root_pem, &root_key, &greedy, NOW).unwrap(); + let info = pki::inspect(&pem).unwrap(); + assert_eq!(info.path_len, Some(0)); + assert!(info.dns_names.is_empty()); + assert_eq!((info.not_after - NOW) / DAY, INTERMEDIATE_DAYS as i64); + // The wrong subject is refused. + let wrong = pki::intermediate_csr(&key, "Some Other CA").unwrap(); + assert!(matches!( + pki::sign_intermediate(&root_pem, &root_key, &wrong, NOW), + Err(PkiError::CsrSubject) + )); + // A tampered CSR (signature does not match) is refused. + let csr = pki::intermediate_csr(&key, pki::INTERMEDIATE_CN).unwrap(); + let tampered = pki::testing::tamper_csr(&csr); + assert!(pki::sign_intermediate(&root_pem, &root_key, &tampered, NOW).is_err()); + // Garbage is refused, never a panic. + assert!(pki::sign_intermediate(&root_pem, &root_key, "not a csr", NOW).is_err()); +} + +#[test] +fn intermediate_must_match_its_key_and_be_a_ca() { + let c = ca(); + let other_key = pki::generate_key().unwrap(); + assert!(matches!( + Intermediate::new(c.int.cert_pem(), other_key), + Err(PkiError::KeyMismatch) + )); + let _ = c.root_key; +} + +#[test] +fn match_code_is_three_two_digit_groups_and_stable() { + let a = pki::match_code(b"some csr"); + assert_eq!(a, pki::match_code(b"some csr")); + assert_ne!(a, pki::match_code(b"other csr")); + let parts: Vec<&str> = a.split(' ').collect(); + assert_eq!(parts.len(), 3); + assert!(parts.iter().all(|p| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit()))); +} + +#[test] +fn encrypted_key_needs_its_password() { + let key = pki::generate_key().unwrap(); + let sealed = pki::encrypt_key_with(&key, b"correct horse battery", 1000).unwrap(); + // Armoured so that the pre-commit hook would block it like any private key. + // (Split so that this file does not match the hook itself.) + assert!(sealed.starts_with(concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----\n"))); + // The plain key is not inside. + assert!(!sealed.contains(&key.serialize_pem())); + let back = pki::decrypt_key(&sealed, b"correct horse battery").unwrap(); + assert_eq!(back.public_key_der(), key.public_key_der()); + assert!(matches!( + pki::decrypt_key(&sealed, b"wrong"), + Err(PkiError::WrongPassword) + )); + // A changed byte is caught. + let mut bad = sealed.clone().into_bytes(); + let i = bad.len() / 2; + bad[i] = if bad[i] == b'A' { b'B' } else { b'A' }; + assert!(pki::decrypt_key(&String::from_utf8(bad).unwrap(), b"correct horse battery").is_err()); + assert!(pki::decrypt_key("garbage", b"x").is_err()); + // Default strength. + assert!(pki::KEY_KDF_ITERATIONS >= 600_000); +} + +#[test] +fn hostile_pem_input_is_an_error_not_a_panic() { + for bad in [ + "", + "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", + "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n", + "\u{0}\u{1}", + ] { + assert!(pki::inspect(bad).is_err()); + assert!(pki::issued_by(bad, bad).is_err()); + assert!(pki::public_key_der(bad).is_err()); + } +}