Skip to main content

core_crypto/mls/credential/
x509.rs

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