authly_client/
identity.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use std::borrow::Cow;

use pem::{EncodeConfig, Pem};

use crate::Error;

/// Client identitity.
///
/// All authly clients identifies themselves using mutual TLS.
#[derive(Clone)]
pub struct Identity {
    pub(crate) cert_pem: Vec<u8>,
    pub(crate) key_pem: Vec<u8>,
}

impl Identity {
    /// Load identity from PEM file containing a certificate and private key.
    pub fn from_pem(pem: impl AsRef<[u8]>) -> Result<Self, Error> {
        use rustls_pemfile::Item;
        use std::io::Cursor;

        let mut pem = Cursor::new(pem);
        let mut certs = Vec::<rustls_pki_types::CertificateDer>::new();
        let mut keys = Vec::<rustls_pki_types::PrivateKeyDer>::new();

        for result in rustls_pemfile::read_all(&mut pem) {
            match result {
                Ok(Item::X509Certificate(cert)) => certs.push(cert),
                Ok(Item::Pkcs1Key(key)) => keys.push(key.into()),
                Ok(Item::Pkcs8Key(key)) => keys.push(key.into()),
                Ok(Item::Sec1Key(key)) => keys.push(key.into()),
                Ok(_) => {
                    return Err(Error::Identity("No valid certificate was found"));
                }
                Err(_) => {
                    return Err(Error::Identity("Invalid identity PEM file"));
                }
            }
        }

        let Some(cert) = certs.into_iter().next() else {
            return Err(Error::Identity("Certificate not found"));
        };
        let Some(key) = keys.into_iter().next() else {
            return Err(Error::Identity("Private key not found"));
        };

        Ok(Self {
            cert_pem: pem::encode_config(
                &Pem::new("CERTIFICATE", cert.to_vec()),
                EncodeConfig::new().set_line_ending(pem::LineEnding::LF),
            )
            .into_bytes(),
            key_pem: pem::encode_config(
                &Pem::new("PRIVATE KEY", key.secret_der()),
                EncodeConfig::new().set_line_ending(pem::LineEnding::LF),
            )
            .into_bytes(),
        })
    }

    pub(crate) fn to_pem(&self) -> Result<Cow<[u8]>, Error> {
        let mut identity_pem = self.cert_pem.clone();
        identity_pem.extend(&self.key_pem);
        Ok(Cow::Owned(identity_pem))
    }
}