// 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/. //! A throw-away test CA (stands in for the Domi CA, which arrives in phase 3). use std::sync::Arc; use rcgen::{ BasicConstraints, CertificateParams, DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, KeyUsagePurpose, }; use rustls::RootCertStore; use rustls_pki_types::CertificateDer; use rustls_pki_types::pem::PemObject; pub struct TestCa { pub cert_pem: String, issuer: Issuer<'static, KeyPair>, } pub struct Leaf { pub cert_pem: String, pub key_pem: String, } impl TestCa { pub fn new(common_name: &str) -> Self { let key = KeyPair::generate().unwrap(); let mut params = CertificateParams::new(Vec::::new()).unwrap(); let mut dn = DistinguishedName::new(); dn.push(DnType::CommonName, common_name); params.distinguished_name = dn; params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); params.key_usages = vec![ KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign, KeyUsagePurpose::DigitalSignature, ]; let cert = params.self_signed(&key).unwrap(); TestCa { cert_pem: cert.pem(), issuer: Issuer::new(params, key), } } /// A server certificate for the given DNS names (or IP literals). pub fn issue(&self, names: &[&str]) -> Leaf { let key = KeyPair::generate().unwrap(); let mut params = CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::>()) .unwrap(); let mut dn = DistinguishedName::new(); dn.push(DnType::CommonName, names.first().copied().unwrap_or("test")); params.distinguished_name = dn; params.is_ca = IsCa::NoCa; params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; params.key_usages = vec![KeyUsagePurpose::DigitalSignature]; let cert = params.signed_by(&key, &self.issuer).unwrap(); Leaf { cert_pem: cert.pem(), key_pem: key.serialize_pem(), } } pub fn roots(&self) -> Arc { roots_from_pem(&self.cert_pem) } } pub fn roots_from_pem(pem: &str) -> Arc { let mut roots = RootCertStore::empty(); for c in CertificateDer::pem_slice_iter(pem.as_bytes()) { roots.add(c.unwrap()).unwrap(); } Arc::new(roots) } /// rustls needs a process-wide crypto provider; install ring once. pub fn install_crypto() { let _ = rustls::crypto::ring::default_provider().install_default(); }