core_crypto/mls/credential/
x509.rs

1#[cfg(test)]
2use std::collections::HashMap;
3use std::fmt;
4
5use derive_more::derive;
6use openmls::prelude::Credential as MlsCredential;
7use openmls_traits::types::SignatureScheme;
8use openmls_x509_credential::CertificateKeyPair;
9use wire_e2e_identity::{HashAlgorithm, WireIdentityReader, legacy::id::WireQualifiedClientId};
10#[cfg(test)]
11use x509_cert::der::Encode;
12use zeroize::Zeroize;
13
14use super::{Error, Result};
15#[cfg(test)]
16use crate::mls_provider::PkiKeypair;
17#[cfg(test)]
18use crate::test_utils::x509::X509Certificate;
19use crate::{Ciphersuite, ClientId, Credential, CredentialType, MlsError, RecursiveError};
20
21#[derive(core_crypto_macros::Debug, Clone, Zeroize, derive::Constructor)]
22#[zeroize(drop)]
23pub struct CertificatePrivateKey {
24    #[sensitive]
25    value: Vec<u8>,
26}
27
28impl CertificatePrivateKey {
29    pub(crate) fn into_inner(mut self) -> Vec<u8> {
30        std::mem::take(&mut self.value)
31    }
32}
33
34/// Represents a x509 certificate chain supplied by the client
35/// It can fetch it after an end-to-end identity process where it can get back a certificate
36/// from the Authentication Service
37#[derive(Clone)]
38pub struct CertificateBundle {
39    /// x509 certificate chain
40    /// First entry is the leaf certificate and each subsequent is its issuer
41    pub certificate_chain: Vec<Vec<u8>>,
42    /// Leaf certificate private key
43    pub private_key: CertificatePrivateKey,
44    /// Signature scheme of private key
45    pub signature_scheme: SignatureScheme,
46}
47
48impl fmt::Debug for CertificateBundle {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        use base64::prelude::*;
51
52        #[derive(derive_more::Debug)]
53        #[debug("{}", BASE64_STANDARD.encode(_0))]
54        // this only exists for the debug impl, which is ignored by the dead code check
55        #[expect(dead_code)]
56        struct CertificateDebugHelper<'a>(&'a Vec<u8>);
57
58        let certificates = self
59            .certificate_chain
60            .iter()
61            .map(CertificateDebugHelper)
62            .collect::<Vec<_>>();
63        f.debug_struct("CertificateBundle")
64            .field("certificate_chain", &certificates)
65            .field("private_key", &self.private_key)
66            .finish()
67    }
68}
69
70impl CertificateBundle {
71    /// Reads the client_id from the leaf certificate
72    pub fn get_client_id(&self) -> Result<ClientId> {
73        let leaf = self.certificate_chain.first().ok_or(Error::InvalidIdentity)?;
74
75        let hash_alg = match self.signature_scheme {
76            SignatureScheme::ECDSA_SECP256R1_SHA256 | SignatureScheme::ED25519 => HashAlgorithm::SHA256,
77            SignatureScheme::ECDSA_SECP384R1_SHA384 => HashAlgorithm::SHA384,
78            SignatureScheme::ED448 | SignatureScheme::ECDSA_SECP521R1_SHA512 => HashAlgorithm::SHA512,
79        };
80
81        let identity = leaf
82            .extract_identity(None, hash_alg)
83            .map_err(|_| Error::InvalidIdentity)?;
84
85        use wire_e2e_identity::legacy::id as legacy_id;
86
87        let client_id: legacy_id::ClientId = identity
88            .client_id
89            .parse::<WireQualifiedClientId>()
90            .map_err(RecursiveError::e2e_identity("parsing wire qualified client id"))?
91            .into();
92        let client_id: Vec<u8> = client_id.into();
93        Ok(client_id.into())
94    }
95
96    /// Reads the 'Not Before' claim from the leaf certificate
97    pub fn get_created_at(&self) -> Result<u64> {
98        let leaf = self.certificate_chain.first().ok_or(Error::InvalidIdentity)?;
99        leaf.extract_created_at().map_err(|_| Error::InvalidIdentity)
100    }
101}
102
103impl Credential {
104    /// Create a new x509 credential from a certificate bundle.
105    pub fn x509(ciphersuite: Ciphersuite, cert: CertificateBundle) -> Result<Self> {
106        let earliest_validity = cert.get_created_at().map_err(RecursiveError::mls_credential(
107            "getting credential 'not before' claim from leaf cert in Credential::x509",
108        ))?;
109        let sk = cert.private_key.into_inner();
110        let chain = cert.certificate_chain;
111
112        let kp = CertificateKeyPair::new(sk, chain.clone()).map_err(MlsError::wrap("creating certificate key pair"))?;
113
114        let credential = MlsCredential::new_x509(chain).map_err(MlsError::wrap("creating x509 credential"))?;
115
116        let cb = Credential {
117            ciphersuite,
118            credential_type: CredentialType::X509,
119            mls_credential: credential,
120            signature_key_pair: kp.0,
121            earliest_validity,
122        };
123        Ok(cb)
124    }
125}
126
127#[cfg(test)]
128fn new_rand_client(domain: Option<String>) -> (String, String) {
129    let rand_str = |n: usize| {
130        use rand::distributions::{Alphanumeric, DistString as _};
131        Alphanumeric.sample_string(&mut rand::thread_rng(), n)
132    };
133    let user_id = uuid::Uuid::new_v4().to_string();
134    let domain = domain.unwrap_or_else(|| format!("{}.com", rand_str(6)));
135    let client_id = wire_e2e_identity::E2eiClientId::try_new(user_id, rand::random::<u64>(), &domain)
136        .unwrap()
137        .to_qualified();
138    (client_id, domain)
139}
140
141#[cfg(test)]
142impl CertificateBundle {
143    // test functions are not held to the same standard as real functions
144    #![allow(missing_docs)]
145
146    /// Generates a certificate that is later turned into a [Credential]
147    ///
148    /// `name` is not known to be a qualified e2ei client id so we invent a new one
149    pub fn rand(name: &ClientId, signer: &crate::test_utils::x509::X509Certificate) -> Self {
150        // here in our tests client_id is generally just "alice" or "bob"
151        // so we will use it to augment handle & display_name
152        // and not a real client_id, instead we'll generate a random one
153        let handle = format!("{name}_wire");
154        let display_name = format!("{name} Smith");
155        Self::new(&handle, &display_name, None, None, signer)
156    }
157
158    pub fn new_with_exact_client_id(client_id: &ClientId, signer: &crate::test_utils::x509::X509Certificate) -> Self {
159        // Unlike Self::rand() above, this uses the provided client ID and does not generate a new
160        // one.
161        // TODO: this should all be reworked by the time WPB-19540 is done.
162        let rand_str = |n: usize| {
163            use rand::distributions::{Alphanumeric, DistString as _};
164            Alphanumeric.sample_string(&mut rand::thread_rng(), n)
165        };
166        let name = rand_str(10);
167        let handle = format!("{name}_wire");
168        let display_name = format!("{name} Smith");
169        let client_id = wire_e2e_identity::legacy::id::ClientId::from(client_id.clone());
170        let client_id = wire_e2e_identity::legacy::id::QualifiedE2eiClientId::from(client_id);
171        Self::new(&handle, &display_name, Some(&client_id), None, signer)
172    }
173
174    /// Generates a certificate that is later turned into a [Credential]
175    pub fn new(
176        handle: &str,
177        display_name: &str,
178        client_id: Option<&wire_e2e_identity::legacy::id::QualifiedE2eiClientId>,
179        cert_keypair: Option<PkiKeypair>,
180        signer: &crate::test_utils::x509::X509Certificate,
181    ) -> Self {
182        Self::new_with_expiration(handle, display_name, client_id, cert_keypair, signer, None)
183    }
184
185    pub fn new_with_expiration(
186        handle: &str,
187        display_name: &str,
188        client_id: Option<&wire_e2e_identity::legacy::id::QualifiedE2eiClientId>,
189        cert_keypair: Option<PkiKeypair>,
190        signer: &crate::test_utils::x509::X509Certificate,
191        expiration: Option<std::time::Duration>,
192    ) -> Self {
193        // here in our tests client_id is generally just "alice" or "bob"
194        // so we will use it to augment handle & display_name
195        // and not a real client_id, instead we'll generate a random one
196        let domain = "world.com";
197        let (client_id, domain) = client_id
198            .map(|cid| {
199                let cid = String::from_utf8(cid.to_vec()).unwrap();
200                (cid, domain.to_string())
201            })
202            .unwrap_or_else(|| new_rand_client(Some(domain.to_string())));
203
204        let mut cert_params = crate::test_utils::x509::CertificateParams {
205            domain: domain.into(),
206            common_name: Some(display_name.to_string()),
207            handle: Some(handle.to_string()),
208            client_id: Some(client_id.to_string()),
209            cert_keypair,
210            ..Default::default()
211        };
212
213        if let Some(expiration) = expiration {
214            cert_params.expiration = expiration;
215        }
216
217        let cert = signer.create_and_sign_end_identity(cert_params);
218        Self::from_certificate_and_issuer(&cert, signer)
219    }
220
221    pub fn new_with_default_values(
222        signer: &crate::test_utils::x509::X509Certificate,
223        expiration: Option<std::time::Duration>,
224    ) -> Self {
225        Self::new_with_expiration("alice_wire@world.com", "Alice Smith", None, None, signer, expiration)
226    }
227
228    pub fn from_self_signed_certificate(cert: &X509Certificate) -> Self {
229        Self::from_certificate_and_issuer(cert, cert)
230    }
231
232    pub fn from_certificate_and_issuer(cert: &X509Certificate, issuer: &X509Certificate) -> Self {
233        Self {
234            certificate_chain: vec![cert.certificate.to_der().unwrap(), issuer.certificate.to_der().unwrap()],
235            private_key: CertificatePrivateKey::new(cert.pki_keypair.signing_key_bytes()),
236            signature_scheme: cert.signature_scheme,
237        }
238    }
239
240    pub fn rand_identifier_certs(
241        client_id: &ClientId,
242        signers: &[&crate::test_utils::x509::X509Certificate],
243    ) -> HashMap<SignatureScheme, CertificateBundle> {
244        signers
245            .iter()
246            .map(|signer| (signer.signature_scheme, Self::rand(client_id, signer)))
247            .collect()
248    }
249
250    pub fn rand_identifier(
251        client_id: &ClientId,
252        signers: &[&crate::test_utils::x509::X509Certificate],
253    ) -> crate::ClientIdentifier {
254        crate::ClientIdentifier::X509(Self::rand_identifier_certs(client_id, signers))
255    }
256}