use alloc::vec::Vec;
use alloc::{fmt, format};
use pki_types::{CertificateDer, TrustAnchor};
use webpki::anchor_from_trusted_cert;
use super::pki_error;
use crate::log::{debug, trace};
use crate::{DistinguishedName, Error};
#[derive(Clone)]
pub struct RootCertStore {
pub roots: Vec<TrustAnchor<'static>>,
}
impl RootCertStore {
pub fn empty() -> Self {
Self { roots: Vec::new() }
}
pub fn add_parsable_certificates<'a>(
&mut self,
der_certs: impl IntoIterator<Item = CertificateDer<'a>>,
) -> (usize, usize) {
let mut valid_count = 0;
let mut invalid_count = 0;
for der_cert in der_certs {
#[cfg_attr(not(feature = "logging"), allow(unused_variables))]
match anchor_from_trusted_cert(&der_cert) {
Ok(anchor) => {
self.roots.push(anchor.to_owned());
valid_count += 1;
}
Err(err) => {
trace!("invalid cert der {:?}", der_cert.as_ref());
debug!("certificate parsing failed: {err:?}");
invalid_count += 1;
}
};
}
debug!(
"add_parsable_certificates processed {valid_count} valid and {invalid_count} invalid certs"
);
(valid_count, invalid_count)
}
pub fn add(&mut self, der: CertificateDer<'_>) -> Result<(), Error> {
self.roots.push(
anchor_from_trusted_cert(&der)
.map_err(pki_error)?
.to_owned(),
);
Ok(())
}
pub fn subjects(&self) -> Vec<DistinguishedName> {
self.roots
.iter()
.map(|ta| DistinguishedName::in_sequence(ta.subject.as_ref()))
.collect()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.roots.len()
}
}
impl FromIterator<TrustAnchor<'static>> for RootCertStore {
fn from_iter<T: IntoIterator<Item = TrustAnchor<'static>>>(iter: T) -> Self {
Self {
roots: iter.into_iter().collect(),
}
}
}
impl Extend<TrustAnchor<'static>> for RootCertStore {
fn extend<T: IntoIterator<Item = TrustAnchor<'static>>>(&mut self, iter: T) {
self.roots.extend(iter);
}
}
impl fmt::Debug for RootCertStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RootCertStore")
.field("roots", &format!("({} roots)", &self.roots.len()))
.finish()
}
}
#[test]
fn root_cert_store_debug() {
use core::iter;
use pki_types::Der;
let ta = TrustAnchor {
subject: Der::from_slice(&[]),
subject_public_key_info: Der::from_slice(&[]),
name_constraints: None,
};
let store = RootCertStore::from_iter(iter::repeat(ta).take(138));
assert_eq!(
format!("{store:?}"),
"RootCertStore { roots: \"(138 roots)\" }"
);
}