Skip to main content

core_crypto/mls/credential/
mod.rs

1//! This module focuses on [`Credential`]s: cryptographic assertions of identity.
2//!
3//! Credentials can be basic, or based on an x509 certificate chain.
4
5pub(crate) mod credential_ref;
6pub(crate) mod credential_type;
7pub(crate) mod crl;
8mod error;
9mod export_pem;
10pub(crate) mod ext;
11mod persistence;
12pub(crate) mod x509;
13
14use std::sync::Arc;
15
16use core_crypto_keystore::entities::StoredCredential;
17use openmls::prelude::{Credential as MlsCredential, CredentialWithKey, KeyPackage, SignatureScheme};
18use openmls_basic_credential::SignatureKeyPair;
19use openmls_traits::crypto::OpenMlsCrypto;
20use tls_codec::Deserialize as _;
21
22pub(crate) use self::error::Result;
23pub use self::{
24    credential_ref::{CredentialRef, FindFilters, FindFiltersBuilder},
25    credential_type::CredentialType,
26    error::Error,
27};
28use crate::{CipherSuite, ClientId, ClientIdRef, OpenMlsError, RecursiveError, TlsCodecError, mls_provider::CRYPTO};
29
30/// A cryptographic credential.
31///
32/// This is tied to a particular client via either its client id or certificate bundle,
33/// depending on its credential type, but is independent of any client instance or storage.
34///
35/// To attach to a particular client instance and store, see
36/// [`TransactionContext::add_credential`][crate::transaction_context::TransactionContext::add_credential].
37#[derive(core_crypto_macros::Debug, Clone, serde::Serialize, serde::Deserialize)]
38pub struct Credential {
39    /// Ciphersuite used by this credential
40    pub(crate) cipher_suite: CipherSuite,
41    /// Credential type
42    pub(crate) credential_type: CredentialType,
43    /// MLS internal credential. Stores the MLS credential
44    pub(crate) mls_credential: MlsCredential,
45    /// Public and private keys, and the signature scheme.
46    #[sensitive]
47    pub(crate) signature_key_pair: SignatureKeyPair,
48    /// Earliest point at which this credential is valid, in seconds since the unix epoch.
49    ///
50    /// For an X509 credential this is the leaf certificate's `not_before` claim. A basic credential has
51    /// no such claim: it reads 0 until the credential is persisted, and the insertion time thereafter.
52    pub(crate) earliest_validity: u64,
53}
54
55impl TryFrom<Arc<StoredCredential>> for Credential {
56    type Error = Error;
57
58    fn try_from(stored_credential: Arc<StoredCredential>) -> Result<Credential> {
59        let mls_credential = MlsCredential::tls_deserialize(&mut stored_credential.credential.as_slice())
60            .map_err(TlsCodecError::deserialize("mls credential"))?;
61        let cipher_suite = CipherSuite::try_from(stored_credential.ciphersuite)?;
62        let signature_key_pair = openmls_basic_credential::SignatureKeyPair::from_raw(
63            cipher_suite.signature_algorithm(),
64            stored_credential.private_key.to_owned(),
65            stored_credential.public_key.to_owned(),
66        );
67        let credential_type = mls_credential
68            .credential_type()
69            .try_into()
70            .map_err(RecursiveError::context("loading credential from db"))?;
71        // An X509 credential's earliest validity is its leaf certificate's `not_before`, which the keystore keeps in a
72        // column of its own. `created_at` may not match it: releases before v11.0.0 stored the insertion time there.
73        let earliest_validity = match credential_type {
74            CredentialType::X509 => stored_credential.not_before,
75            CredentialType::Basic => stored_credential.created_at,
76        };
77        Ok(Credential {
78            cipher_suite,
79            signature_key_pair,
80            credential_type,
81            mls_credential,
82            earliest_validity,
83        })
84    }
85}
86
87impl Credential {
88    /// Generate a basic credential.
89    ///
90    /// The result is independent of any client instance and the database; it lives in memory only.
91    ///
92    /// The earliest validity of this credential is always 0. It will be updated once the credential is added to a
93    /// session.
94    pub fn basic(cipher_suite: CipherSuite, client_id: ClientId) -> Result<Self> {
95        let signature_scheme = cipher_suite.signature_algorithm();
96        let (private_key, public_key) = CRYPTO
97            .signature_key_gen(signature_scheme)
98            .map_err(OpenMlsError::wrap("generating signature key"))?;
99        let signature_key_pair = SignatureKeyPair::from_raw(signature_scheme, private_key, public_key);
100
101        Ok(Self {
102            cipher_suite,
103            credential_type: CredentialType::Basic,
104            mls_credential: MlsCredential::new_basic(client_id.into_inner()),
105            signature_key_pair,
106            earliest_validity: 0,
107        })
108    }
109
110    /// Recover the public half of the credential which produced a key package.
111    ///
112    /// The result carries no private signature key, so it can be persisted and it identifies its
113    /// client, but it can never sign. That is all a history client ever has: the private key of its
114    /// credential is discarded as soon as the history secret is generated, which is what makes
115    /// such a client incapable of producing messages of its own.
116    pub(crate) fn public_only(key_package: &KeyPackage) -> Result<Self> {
117        let cipher_suite = CipherSuite::from(key_package.ciphersuite());
118        let leaf_node = key_package.leaf_node();
119        let mls_credential = leaf_node.credential().clone();
120        let credential_type = mls_credential.credential_type().try_into()?;
121        let signature_key_pair = SignatureKeyPair::from_raw(
122            cipher_suite.signature_algorithm(),
123            Vec::new(),
124            leaf_node.signature_key().as_slice().to_vec(),
125        );
126
127        Ok(Self {
128            cipher_suite,
129            credential_type,
130            mls_credential,
131            signature_key_pair,
132            earliest_validity: 0,
133        })
134    }
135
136    /// Get the Openmls Credential type.
137    ///
138    /// This stores the credential type (basic/x509).
139    pub fn mls_credential(&self) -> &MlsCredential {
140        &self.mls_credential
141    }
142
143    /// Get the credential type
144    pub fn credential_type(&self) -> CredentialType {
145        self.credential_type
146    }
147
148    /// Get a reference to the `SignatureKeyPair`.
149    pub(crate) fn signature_key(&self) -> &SignatureKeyPair {
150        &self.signature_key_pair
151    }
152
153    /// The **private** half of this credential's signature key.
154    pub fn signature_key_bytes(&self) -> &[u8] {
155        self.signature_key_pair.private()
156    }
157
158    /// Get the signature scheme
159    pub fn signature_scheme(&self) -> SignatureScheme {
160        self.signature_key_pair.signature_scheme()
161    }
162
163    /// Get the cipher suite
164    pub fn cipher_suite(&self) -> CipherSuite {
165        self.cipher_suite
166    }
167
168    /// Generate a `CredentialWithKey`, which combines the credential type with the public portion of the keypair.
169    pub fn to_mls_credential_with_key(&self) -> CredentialWithKey {
170        CredentialWithKey {
171            credential: self.mls_credential.clone(),
172            signature_key: self.signature_key_pair.to_public_vec().into(),
173        }
174    }
175
176    /// Earliest point at which this credential is valid, in seconds since the unix epoch.
177    ///
178    /// For an X509 credential this is the leaf certificate's `not_before` claim. A basic credential has
179    /// no such claim: it reads 0 until the credential is persisted, and the insertion time thereafter.
180    pub fn earliest_validity(&self) -> u64 {
181        self.earliest_validity
182    }
183
184    /// Get the client ID associated with this credential
185    pub fn client_id(&self) -> &ClientIdRef {
186        self.mls_credential.identity().into()
187    }
188}
189
190impl From<Credential> for CredentialWithKey {
191    fn from(cb: Credential) -> Self {
192        Self {
193            credential: cb.mls_credential,
194            signature_key: cb.signature_key_pair.public().into(),
195        }
196    }
197}
198
199impl Eq for Credential {}
200impl PartialEq for Credential {
201    fn eq(&self, other: &Self) -> bool {
202        self.mls_credential == other.mls_credential && self.earliest_validity == other.earliest_validity && {
203            let sk = &self.signature_key_pair;
204            let ok = &other.signature_key_pair;
205            sk.signature_scheme() == ok.signature_scheme() && sk.public() == ok.public()
206            // public key equality implies private key equality
207        }
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use openmls_traits::OpenMlsCryptoProvider as _;
214    use rusty_jwt_tools::jsonwebtoken::DecodingKey;
215    use wire_e2e_identity::{CiphersuiteExt as _, pki_env::PkiEnvironment};
216    use x509_cert::der::Encode as _;
217
218    use super::{x509::CertificateBundle, *};
219    use crate::{
220        CredentialType, E2eiConversationState, MlsCiphersuite,
221        mls::credential::x509::CertificatePrivateKey,
222        test_utils::{
223            x509::{CertificateParams, PkiKeypair, X509TestChain},
224            *,
225        },
226    };
227
228    #[apply(all_cred_cipher)]
229    async fn basic_clients_can_send_messages(case: TestContext) {
230        if !case.is_basic() {
231            return;
232        }
233        let [alice, bob] = case.sessions_basic().await;
234        let conversation = case.create_conversation([&alice, &bob]).await;
235        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
236    }
237
238    #[apply(all_cred_cipher)]
239    async fn certificate_clients_can_send_messages(case: TestContext) {
240        if !case.is_x509() {
241            return;
242        }
243        let [alice, bob] = case.sessions_x509().await;
244        let conversation = case.create_conversation([&alice, &bob]).await;
245        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
246    }
247
248    /// Certificate acquisition converts the raw private keys of our MLS provider to PEM with rusty-jwt-tools.
249    #[apply(all_cred_cipher)]
250    async fn signature_key_should_convert_to_pem(case: TestContext) {
251        if !case.is_basic() {
252            return;
253        }
254        // ciphersuites without a JWS algorithm don't support certificate acquisition
255        let Some(alg) = MlsCiphersuite::from(case.cipher_suite()).jws_algorithm() else {
256            return;
257        };
258        let [client_id] = case.client_ids();
259        let credential = Credential::basic(case.cipher_suite(), client_id).unwrap();
260
261        let pem = alg.keypair_from_bytes(credential.signature_key_bytes()).unwrap();
262        let jwk = alg.public_jwk(&pem).unwrap();
263        let public_key = DecodingKey::from_jwk(&jwk).unwrap();
264        assert_eq!(
265            public_key.try_get_as_bytes().unwrap(),
266            credential.signature_key().public()
267        );
268    }
269
270    #[apply(all_cred_cipher)]
271    async fn heterogeneous_clients_can_send_messages(case: TestContext) {
272        if !case.supports_x509() {
273            return;
274        }
275
276        // check that both credentials can initiate/join a group
277        let ([x509_session], [basic_session]) = case.sessions_mixed_credential_types().await;
278
279        // That way the conversation creator (Alice) will have a different credential type than Bob
280        let (alice, bob) = match case.credential_type {
281            CredentialType::Basic => (x509_session, basic_session),
282            CredentialType::X509 => (basic_session, x509_session),
283        };
284
285        let conversation = case.create_conversation([&alice, &bob]).await;
286        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
287    }
288
289    #[apply(all_cred_cipher)]
290    async fn should_fail_when_certificate_chain_is_empty(case: TestContext) {
291        if !case.supports_x509() {
292            return;
293        }
294        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
295
296        let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
297
298        let mut cert = CertificateBundle::rand(&"alice".into(), x509_intermediate);
299        cert.certificate_chain = vec![];
300        let err = Credential::x509(case.cipher_suite(), cert).unwrap_err();
301
302        assert!(innermost_source_matches!(err, Error::InvalidIdentity));
303    }
304
305    #[apply(all_cred_cipher)]
306    async fn should_fail_when_signature_key_doesnt_match_certificate_public_key(case: TestContext) {
307        if !case.is_x509() {
308            return;
309        }
310        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
311        let x509_intermediate = x509_test_chain.find_local_intermediate_ca();
312
313        let certs = CertificateBundle::rand(&"alice".into(), x509_intermediate);
314        let new_keypair = CRYPTO.signature_key_gen(case.signature_scheme()).unwrap();
315        let new_pki_kp = PkiKeypair::new(case.signature_scheme(), new_keypair.0).unwrap();
316
317        let eve_key = CertificatePrivateKey::new(new_pki_kp.signing_key_bytes());
318        let cb = CertificateBundle {
319            certificate_chain: certs.certificate_chain,
320            private_key: eve_key,
321            signature_scheme: case.cipher_suite().signature_algorithm(),
322        };
323        let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
324
325        assert!(innermost_source_matches!(
326            err,
327            crate::OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::MismatchKeypair),
328        ));
329    }
330
331    #[apply(all_cred_cipher)]
332    async fn should_fail_when_certificate_signature_doesnt_match_ciphersuite(case: TestContext) {
333        use openmls::prelude::Ciphersuite;
334        if !case.is_x509() {
335            return;
336        }
337
338        let [alice] = case.sessions_x509().await;
339        let conversation = case.create_conversation([&alice]).await;
340
341        let other_cipher_suite = match case.cipher_suite() {
342            CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519) => {
343                CipherSuite(Ciphersuite::MLS_128_DHKEMP256_AES128GCM_SHA256_P256)
344            }
345            _ => CipherSuite(Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519),
346        };
347
348        let mixed_cipher_suite_case = TestContext::new(CredentialType::X509, *other_cipher_suite);
349        let [bob] = mixed_cipher_suite_case.sessions_x509().await;
350
351        let bob_kp = bob
352            .transaction
353            .generate_key_package(&bob.initial_credential, None)
354            .await
355            .unwrap()
356            .into();
357
358        assert!(conversation.guard().await.add_members(vec![bob_kp]).await.is_err());
359    }
360
361    #[apply(all_cred_cipher)]
362    async fn should_not_fail_but_degrade_when_certificate_expired(case: TestContext) {
363        if !case.is_x509() {
364            return;
365        }
366        let mut x509_test_chain = case.set_test_chain(&[], &[], None).await;
367        let expiration_time = core::time::Duration::from_secs(8);
368        let start = web_time::Instant::now();
369
370        let alice_cert = x509_test_chain.issue_simple_certificate_bundle("alice", None);
371        let alice_cred = Credential::x509(case.cipher_suite(), alice_cert).unwrap();
372        let bob_cert = x509_test_chain.issue_simple_certificate_bundle("bob", Some(expiration_time));
373        let bob_cred = Credential::x509(case.cipher_suite(), bob_cert).unwrap();
374        let alice = SessionContext::new_with_credential(&case, alice_cred, case.sessions_in_memory)
375            .await
376            .unwrap();
377        let bob = SessionContext::new_with_credential(&case, bob_cred, case.sessions_in_memory)
378            .await
379            .unwrap();
380
381        let conversation = case.create_conversation([&alice, &bob]).await;
382        // this should work since the certificate is not yet expired
383        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
384
385        assert_eq!(
386            conversation.guard().await.e2ei_conversation_state().await.unwrap(),
387            E2eiConversationState::Verified
388        );
389
390        let elapsed = start.elapsed();
391        // Give time to the certificate to expire
392        if expiration_time > elapsed {
393            smol::Timer::after(expiration_time - elapsed + core::time::Duration::from_secs(1)).await;
394        }
395
396        assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
397        assert_eq!(
398            conversation.guard().await.e2ei_conversation_state().await.unwrap(),
399            E2eiConversationState::NotVerified
400        );
401    }
402
403    #[apply(all_cred_cipher)]
404    async fn should_not_fail_but_degrade_when_basic_joins(case: TestContext) {
405        if !case.is_x509() {
406            return;
407        }
408        Box::pin(async {
409            let ([alice, bob], [charlie]) = case.sessions_mixed_credential_types().await;
410            let conversation = case.create_conversation([&alice, &bob]).await;
411
412            // this should work since the certificate is not yet expired
413            assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
414            assert_eq!(
415                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
416                E2eiConversationState::Verified
417            );
418            assert_eq!(
419                conversation
420                    .guard_of(&bob)
421                    .await
422                    .e2ei_conversation_state()
423                    .await
424                    .unwrap(),
425                E2eiConversationState::Verified
426            );
427
428            // Charlie is a basic client that tries to join (i.e. emulates guest links in Wire)
429            let conversation = conversation
430                .invite_with_credential_notify([(&charlie, &charlie.initial_credential)])
431                .await;
432
433            assert_eq!(
434                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
435                E2eiConversationState::NotVerified
436            );
437            assert!(conversation.is_functional_and_contains([&alice, &bob, &charlie]).await);
438            assert_eq!(
439                conversation.guard().await.e2ei_conversation_state().await.unwrap(),
440                E2eiConversationState::NotVerified
441            );
442        })
443        .await;
444    }
445
446    /// Persisting an X509 credential must not overwrite the certificate's `not_before` claim.
447    ///
448    /// `Credential::save` used to stamp every credential with the insertion time, which discarded
449    /// the claim `Credential::x509` had just computed and made `FindFilters::earliest_validity`
450    /// -- documented as "point of earliest validity" -- match nothing.
451    #[apply(all_cred_cipher)]
452    async fn saving_an_x509_credential_keeps_the_certificate_validity(case: TestContext) {
453        if !case.is_x509() {
454            return;
455        }
456        let [alice] = case.sessions().await;
457        Box::pin(async move {
458            let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
459            let local_ca = x509_test_chain.find_local_intermediate_ca();
460
461            // An hour in the past, so a stamp of "now" is unmistakably different.
462            let an_hour_ago = now_std() - core::time::Duration::from_secs(3600);
463            // Must be alice's own client id: `add_credential` rejects a credential belonging to
464            // anyone else.
465            let client_id = alice.get_client_id().await;
466            let cert = local_ca.create_and_sign_end_identity(CertificateParams {
467                common_name: Some("Alice Smith".to_string()),
468                handle: Some("alice_wire".to_string()),
469                client_id: Some(client_id),
470                validity_start: Some(an_hour_ago),
471                ..Default::default()
472            });
473            let bundle = CertificateBundle::from_certificate_and_issuer(&cert, local_ca);
474            let credential = Credential::x509(case.cipher_suite(), bundle).unwrap();
475
476            // The fixture's conversion of `validity_start` can be off by a second, so allow a
477            // little slack here; what matters is that this is an hour ago and not "now".
478            let from_certificate = credential.earliest_validity();
479            assert!(
480                from_certificate.abs_diff(an_hour_ago.as_secs()) <= 5,
481                "the credential must start out carrying the certificate's `not_before`: \
482                 got {from_certificate}, expected about {}",
483                an_hour_ago.as_secs()
484            );
485
486            let credential_ref = alice
487                .add_credential(credential)
488                .await
489                .expect("adding the credential should succeed");
490
491            assert_eq!(
492                credential_ref.earliest_validity(),
493                from_certificate,
494                "persisting must not replace the certificate claim with the insertion time"
495            );
496        })
497        .await;
498    }
499
500    #[apply(all_cred_cipher)]
501    async fn should_fail_when_certificate_not_valid_yet(case: TestContext) {
502        use crate::OpenMlsErrorKind;
503
504        if !case.is_x509() {
505            return;
506        }
507        let x509_test_chain = X509TestChain::init_empty(case.signature_scheme());
508
509        let tomorrow = now_std() + core::time::Duration::from_secs(3600 * 24);
510        let local_ca = x509_test_chain.find_local_intermediate_ca();
511        let alice_cert = {
512            let name = "alice";
513            let common_name = format!("{name} Smith");
514            let handle = format!("{}_wire", name.to_lowercase());
515            let [client_id] = case.client_ids();
516            local_ca.create_and_sign_end_identity(CertificateParams {
517                common_name: Some(common_name.clone()),
518                handle: Some(handle.clone()),
519                client_id: Some(client_id.clone()),
520                validity_start: Some(tomorrow),
521                ..Default::default()
522            })
523        };
524        let cb = CertificateBundle::from_certificate_and_issuer(&alice_cert, local_ca);
525        let err = Credential::x509(case.cipher_suite(), cb).unwrap_err();
526
527        assert!(innermost_source_matches!(
528            err,
529            OpenMlsErrorKind::MlsCryptoError(openmls::prelude::CryptoError::ExpiredCertificate),
530        ))
531    }
532
533    /// In order to be WASM-compatible
534    // pub fn now() -> wire_e2e_identity::OffsetDateTime {
535    //     let now_since_epoch = now_std().as_secs() as i64;
536    //     wire_e2e_identity::OffsetDateTime::from_unix_timestamp(now_since_epoch).unwrap()
537    // }
538    pub(crate) fn now_std() -> std::time::Duration {
539        let now = web_time::SystemTime::now();
540        now.duration_since(web_time::UNIX_EPOCH).unwrap()
541    }
542
543    #[macro_rules_attribute::apply(smol_macros::test)]
544    async fn revoked_cert_should_invalidate_credential() {
545        let case = TestContext::default_x509();
546        let [alice] = case.sessions_x509().await;
547
548        let chain = alice.x509_chain_unchecked();
549        let intermediate = &chain.intermediates[0];
550        let cert = &chain.actors[0].certificate.certificate;
551        let serial = cert.tbs_certificate().serial_number();
552
553        let crl = intermediate
554            .pki_keypair
555            .revoke_certs(&intermediate.certificate, vec![serial.as_bytes().to_vec()])
556            .unwrap();
557        let pki_env = alice
558            .session
559            .read()
560            .await
561            .crypto_provider
562            .authentication_service()
563            .pki_env()
564            .await
565            .unwrap();
566        let dp = &intermediate.crl_dps[0];
567
568        let inner = alice.transaction.inner().unwrap();
569        pki_env
570            .save_crl(inner.transaction(), dp, &crl.to_der().unwrap())
571            .await
572            .unwrap();
573
574        assert!(alice.transaction.check_credentials().await.is_err());
575    }
576
577    #[macro_rules_attribute::apply(smol_macros::test)]
578    async fn revoked_cert_should_stay_revoked_after_recreating_pki_environment() {
579        let case = TestContext::default_x509();
580        let [alice] = case.sessions_x509().await;
581
582        let chain = alice.x509_chain_unchecked();
583        let intermediate = &chain.intermediates[0];
584        let cert = &chain.actors[0].certificate.certificate;
585        let serial = cert.tbs_certificate().serial_number();
586        let crl = intermediate
587            .pki_keypair
588            .revoke_certs(&intermediate.certificate, vec![serial.as_bytes().to_vec()])
589            .unwrap();
590        let pki_env = alice
591            .session
592            .read()
593            .await
594            .crypto_provider
595            .authentication_service()
596            .pki_env()
597            .await
598            .unwrap();
599
600        let inner = alice.transaction.inner().unwrap();
601        pki_env
602            .save_crl(inner.transaction(), &intermediate.crl_dps[0], &crl.to_der().unwrap())
603            .await
604            .unwrap();
605        drop(inner);
606
607        assert!(pki_env.validate_cert(cert).await.is_err());
608        alice.transaction.finish().await.unwrap();
609
610        let restored = PkiEnvironment::new(Arc::new(DummyPkiEnvironmentHooks), pki_env.database_arc())
611            .await
612            .unwrap();
613        let result = restored.validate_cert(cert).await;
614        assert!(
615            result.is_err(),
616            "revoked certificate was accepted after restoration: {result:?}"
617        );
618    }
619}