Skip to main content

vault_core/
certinfo.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! What a certificate says about itself: when it is valid and for which names.
4//!
5//! A certificate entry's `issued_at` and `expires_at` come from here, not from the clock of the
6//! machine that fetched it, so a renewal check reads the dates the CA signed.
7
8use x509_parser::extensions::GeneralName;
9use x509_parser::pem::Pem;
10
11/// The leaf of a PEM chain.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct CertInfo {
14    /// `YYYY-MM-DDTHH:MM:SSZ`.
15    pub not_before: String,
16    pub not_after: String,
17    /// Seconds since the epoch, for comparisons.
18    pub not_after_epoch: i64,
19    /// DNS names from the subject alternative names, lower case.
20    pub dns_names: Vec<String>,
21}
22
23/// Reads the first certificate in `pem`, which for a chain written by an ACME client is the leaf.
24pub fn leaf(pem: &str) -> Result<CertInfo, String> {
25    let block = Pem::iter_from_buffer(pem.as_bytes())
26        .filter_map(Result::ok)
27        .find(|p| p.label == "CERTIFICATE")
28        .ok_or("no certificate in the PEM text")?;
29    let cert = block
30        .parse_x509()
31        .map_err(|e| format!("not a valid certificate: {e}"))?;
32    let validity = cert.validity();
33    let mut dns_names: Vec<String> = cert
34        .subject_alternative_name()
35        .ok()
36        .flatten()
37        .map(|san| {
38            san.value
39                .general_names
40                .iter()
41                .filter_map(|n| match n {
42                    GeneralName::DNSName(d) => Some(d.to_ascii_lowercase()),
43                    _ => None,
44                })
45                .collect()
46        })
47        .unwrap_or_default();
48    dns_names.sort();
49    Ok(CertInfo {
50        not_before: crate::pgp::iso(validity.not_before.timestamp()),
51        not_after: crate::pgp::iso(validity.not_after.timestamp()),
52        not_after_epoch: validity.not_after.timestamp(),
53        dns_names,
54    })
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn reads_the_dates_and_names_the_ca_signed() {
63        let key = rcgen::KeyPair::generate().unwrap();
64        let mut params =
65            rcgen::CertificateParams::new(vec!["B.Example.test".into(), "a.example.test".into()])
66                .unwrap();
67        params.not_before = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).unwrap();
68        params.not_after = time::OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
69        let pem = params.self_signed(&key).unwrap().pem();
70        let info = leaf(&pem).unwrap();
71        assert_eq!(info.not_before, "2023-11-14T22:13:20Z");
72        assert_eq!(info.not_after, "2027-01-15T08:00:00Z");
73        assert_eq!(info.not_after_epoch, 1_800_000_000);
74        assert_eq!(info.dns_names, ["a.example.test", "b.example.test"]);
75    }
76
77    #[test]
78    fn text_without_a_certificate_is_refused() {
79        assert!(leaf("hello").unwrap_err().contains("no certificate"));
80        let key_only = rcgen::KeyPair::generate().unwrap().serialize_pem();
81        assert!(leaf(&key_only).is_err(), "a key is not a certificate");
82    }
83
84    #[test]
85    fn a_certificate_block_that_is_not_one_is_refused() {
86        let bad = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
87        assert!(leaf(bad).unwrap_err().contains("not a valid certificate"));
88    }
89}