1
//! Helpers for parsing certificates.
2

            
3
use std::path::PathBuf;
4

            
5
use tor_error::internal;
6
use tor_key_forge::{CertType, ParsedEd25519Cert};
7

            
8
use crate::keystore::arti::err::ArtiNativeKeystoreError;
9
use crate::{ErasedKey, Result};
10

            
11
/// An unparsed key certificate.
12
pub(super) struct UnparsedCert {
13
    /// The contents of the cert file.
14
    inner: Vec<u8>,
15
    /// The path of the file (for error reporting).
16
    path: PathBuf,
17
}
18

            
19
impl UnparsedCert {
20
    /// Create a new [`UnparsedCert`].
21
2
    pub(super) fn new(inner: Vec<u8>, path: PathBuf) -> Self {
22
2
        Self { inner, path }
23
2
    }
24

            
25
    /// Parse a key certificate, converting the key material into a known type,
26
    /// and return the type-erased value.
27
    ///
28
    /// The caller is expected to downcast the value returned to a concrete type.
29
2
    pub(super) fn parse_certificate_erased(self, cert_type: &CertType) -> Result<ErasedKey> {
30
2
        match cert_type {
31
            CertType::Ed25519TorCert => {
32
2
                let cert = ParsedEd25519Cert::decode(self.inner).map_err(|e| {
33
                    ArtiNativeKeystoreError::CertParse {
34
                        path: self.path,
35
                        cert_type: cert_type.clone(),
36
                        err: e.clone(),
37
                    }
38
                })?;
39

            
40
2
                Ok(Box::new(cert))
41
            }
42
            _ => Err(
43
                ArtiNativeKeystoreError::Bug(internal!("Unknown cert type {cert_type:?}")).into(),
44
            ),
45
        }
46
2
    }
47
}