core_crypto/mls/session/
mod.rs

1pub(crate) mod e2e_identity;
2mod epoch_observer;
3mod error;
4pub(crate) mod id;
5pub(crate) mod identifier;
6pub(crate) mod identities;
7pub(crate) mod key_package;
8pub(crate) mod user_id;
9
10use crate::{
11    CoreCrypto, KeystoreError, LeafError, MlsError, MlsTransport, RecursiveError,
12    group_store::GroupStore,
13    mls::{
14        self, HasSessionAndCrypto,
15        conversation::ImmutableConversation,
16        credential::{CredentialBundle, ext::CredentialExt},
17    },
18    prelude::{
19        CertificateBundle, ClientId, ConversationId, HistorySecret, INITIAL_KEYING_MATERIAL_COUNT, MlsCiphersuite,
20        MlsClientConfiguration, MlsCredentialType, identifier::ClientIdentifier,
21        key_package::KEYPACKAGE_DEFAULT_LIFETIME,
22    },
23};
24use async_lock::RwLock;
25use core_crypto_keystore::{
26    Connection, CryptoKeystoreError,
27    connection::FetchFromDatabase,
28    entities::{EntityFindParams, MlsCredential, MlsSignatureKeyPair},
29};
30pub use epoch_observer::EpochObserver;
31pub(crate) use error::{Error, Result};
32use identities::Identities;
33use log::debug;
34use mls_crypto_provider::{EntropySeed, MlsCryptoProvider, MlsCryptoProviderConfiguration};
35use openmls::prelude::{Credential, CredentialType};
36use openmls_basic_credential::SignatureKeyPair;
37use openmls_traits::{OpenMlsCryptoProvider, crypto::OpenMlsCrypto, types::SignatureScheme};
38use openmls_x509_credential::CertificateKeyPair;
39use std::collections::HashSet;
40use std::ops::Deref;
41use std::sync::Arc;
42use tls_codec::{Deserialize, Serialize};
43
44/// A MLS Session enables a user device to communicate via the MLS protocol.
45///
46/// This closely maps to the `Client` term in [RFC 9720], but we avoid that term to avoid ambiguity;
47/// `Client` is very overloaded with distinct meanings.
48///
49/// There is one `Session` per user per device. A session can contain many MLS groups/conversations.
50///
51/// It is cheap to clone a `Session` because everything heavy is wrapped inside an [Arc].
52///
53/// [RFC 9720]: https://www.rfc-editor.org/rfc/rfc9420.html
54#[derive(Clone, derive_more::Debug)]
55pub struct Session {
56    pub(crate) inner: Arc<RwLock<Option<SessionInner>>>,
57    pub(crate) crypto_provider: MlsCryptoProvider,
58    pub(crate) transport: Arc<RwLock<Option<Arc<dyn MlsTransport + 'static>>>>,
59    #[debug("EpochObserver")]
60    pub(crate) epoch_observer: Arc<RwLock<Option<Arc<dyn EpochObserver + 'static>>>>,
61}
62
63#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
64#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
65impl HasSessionAndCrypto for Session {
66    async fn session(&self) -> mls::Result<Session> {
67        Ok(self.clone())
68    }
69
70    async fn crypto_provider(&self) -> mls::Result<MlsCryptoProvider> {
71        Ok(self.crypto_provider.clone())
72    }
73}
74
75#[derive(Clone, Debug)]
76pub(crate) struct SessionInner {
77    id: ClientId,
78    pub(crate) identities: Identities,
79    keypackage_lifetime: std::time::Duration,
80}
81
82impl Session {
83    /// Creates a new [Session].
84    /// Takes a store path (i.e. Disk location of the embedded database, should be consistent between messaging sessions)
85    /// And a root identity key (i.e. enclaved encryption key for this device)
86    ///
87    /// # Arguments
88    /// * `configuration` - the configuration for the `MlsCentral`
89    ///
90    /// # Errors
91    /// Failures in the initialization of the KeyStore can cause errors, such as IO, the same kind
92    /// of errors can happen when the groups are being restored from the KeyStore or even during
93    /// the client initialization (to fetch the identity signature). Other than that, `MlsError`
94    /// can be caused by group deserialization or during the initialization of the credentials:
95    /// * for x509 Credentials if the certificate chain length is lower than 2
96    /// * for Basic Credentials if the signature key cannot be generated either by not supported
97    ///   scheme or the key generation fails
98    pub async fn try_new(configuration: MlsClientConfiguration) -> crate::mls::Result<Self> {
99        // Init backend (crypto + rand + keystore)
100        let mls_backend = MlsCryptoProvider::try_new_with_configuration(MlsCryptoProviderConfiguration {
101            db_path: &configuration.store_path,
102            db_key: configuration.database_key.clone(),
103            in_memory: false,
104            entropy_seed: configuration.external_entropy.clone(),
105        })
106        .await
107        .map_err(MlsError::wrap("trying to initialize mls crypto provider object"))?;
108        Self::new_with_backend(mls_backend, configuration).await
109    }
110
111    /// Same as the [Self::try_new] but instead, it uses an in memory KeyStore.
112    /// Although required, the `store_path` parameter from the `MlsClientConfiguration` won't be used here.
113    pub async fn try_new_in_memory(configuration: MlsClientConfiguration) -> crate::mls::Result<Self> {
114        let mls_backend = MlsCryptoProvider::try_new_with_configuration(MlsCryptoProviderConfiguration {
115            db_path: &configuration.store_path,
116            db_key: configuration.database_key.clone(),
117            in_memory: true,
118            entropy_seed: configuration.external_entropy.clone(),
119        })
120        .await
121        .map_err(MlsError::wrap(
122            "trying to initialize mls crypto provider object (in memory)",
123        ))?;
124        Self::new_with_backend(mls_backend, configuration).await
125    }
126
127    async fn new_with_backend(
128        mls_backend: MlsCryptoProvider,
129        configuration: MlsClientConfiguration,
130    ) -> crate::mls::Result<Self> {
131        // We create the core crypto instance first to enable creating a transaction from it and
132        // doing all subsequent actions inside a single transaction, though it forces us to clone
133        // a few Arcs and locks.
134        let client = Self {
135            crypto_provider: mls_backend.clone(),
136            inner: Default::default(),
137            transport: Arc::new(None.into()),
138            epoch_observer: Arc::new(None.into()),
139        };
140
141        let cc = CoreCrypto::from(client.clone());
142        let context = cc
143            .new_transaction()
144            .await
145            .map_err(RecursiveError::transaction("starting new transaction"))?;
146
147        if let Some(id) = configuration.client_id {
148            client
149                .init(
150                    ClientIdentifier::Basic(id),
151                    configuration.ciphersuites.as_slice(),
152                    &mls_backend,
153                    configuration
154                        .nb_init_key_packages
155                        .unwrap_or(INITIAL_KEYING_MATERIAL_COUNT),
156                )
157                .await
158                .map_err(RecursiveError::mls_client("initializing mls client"))?
159        }
160
161        let central = cc.mls;
162        context
163            .init_pki_env()
164            .await
165            .map_err(RecursiveError::transaction("initializing pki environment"))?;
166        context
167            .finish()
168            .await
169            .map_err(RecursiveError::transaction("finishing transaction"))?;
170        Ok(central)
171    }
172
173    /// Provide the implementation of functions to communicate with the delivery service
174    /// (see [MlsTransport]).
175    pub async fn provide_transport(&self, transport: Arc<dyn MlsTransport>) {
176        self.transport.write().await.replace(transport);
177    }
178
179    /// Initializes the client.
180    /// If the client's cryptographic material is already stored in the keystore, it loads it
181    /// Otherwise, it is being created.
182    ///
183    /// # Arguments
184    /// * `identifier` - client identifier ; either a [ClientId] or a x509 certificate chain
185    /// * `ciphersuites` - all ciphersuites this client is supposed to support
186    /// * `backend` - the KeyStore and crypto provider to read identities from
187    ///
188    /// # Errors
189    /// KeyStore and OpenMls errors can happen
190    pub async fn init(
191        &self,
192        identifier: ClientIdentifier,
193        ciphersuites: &[MlsCiphersuite],
194        backend: &MlsCryptoProvider,
195        nb_key_package: usize,
196    ) -> Result<()> {
197        self.ensure_unready().await?;
198        let id = identifier.get_id()?;
199
200        let credentials = backend
201            .key_store()
202            .find_all::<MlsCredential>(EntityFindParams::default())
203            .await
204            .map_err(KeystoreError::wrap("finding all mls credentials"))?;
205
206        let credentials = credentials
207            .into_iter()
208            .filter(|mls_credential| mls_credential.id.as_slice() == id.as_slice())
209            .map(|mls_credential| -> Result<_> {
210                let credential = Credential::tls_deserialize(&mut mls_credential.credential.as_slice())
211                    .map_err(Error::tls_deserialize("mls credential"))?;
212                Ok((credential, mls_credential.created_at))
213            })
214            .collect::<Result<Vec<_>>>()?;
215
216        if credentials.is_empty() {
217            debug!(count = nb_key_package, ciphersuites:? = ciphersuites; "Generating client");
218            self.generate(identifier, backend, ciphersuites, nb_key_package).await?;
219        } else {
220            let signature_schemes = ciphersuites
221                .iter()
222                .map(|cs| cs.signature_algorithm())
223                .collect::<HashSet<_>>();
224            let load_result = self.load(backend, id.as_ref(), credentials, signature_schemes).await;
225            if let Err(Error::ClientSignatureNotFound) = load_result {
226                debug!(count = nb_key_package, ciphersuites:? = ciphersuites; "Client signature not found. Generating client");
227                self.generate(identifier, backend, ciphersuites, nb_key_package).await?;
228            } else {
229                load_result?;
230            }
231        };
232
233        Ok(())
234    }
235
236    /// Resets the client to an uninitialized state.
237    #[cfg(test)]
238    pub(crate) async fn reset(&self) {
239        let mut inner_lock = self.inner.write().await;
240        *inner_lock = None;
241    }
242
243    pub(crate) async fn is_ready(&self) -> bool {
244        let inner_lock = self.inner.read().await;
245        inner_lock.is_some()
246    }
247
248    async fn ensure_unready(&self) -> Result<()> {
249        if self.is_ready().await {
250            Err(Error::UnexpectedlyReady)
251        } else {
252            Ok(())
253        }
254    }
255
256    async fn replace_inner(&self, new_inner: SessionInner) {
257        let mut inner_lock = self.inner.write().await;
258        *inner_lock = Some(new_inner);
259    }
260
261    /// Get an immutable view of an `MlsConversation`.
262    ///
263    /// Because it operates on the raw conversation type, this may be faster than
264    /// [crate::transaction_context::TransactionContext::conversation]. for transient and immutable
265    /// purposes. For long-lived or mutable purposes, prefer the other method.
266    pub async fn get_raw_conversation(&self, id: &ConversationId) -> Result<ImmutableConversation> {
267        let raw_conversation = GroupStore::fetch_from_keystore(id, &self.crypto_provider.keystore(), None)
268            .await
269            .map_err(RecursiveError::root("getting conversation by id"))?
270            .ok_or_else(|| LeafError::ConversationNotFound(id.clone()))?;
271        Ok(ImmutableConversation::new(raw_conversation, self.clone()))
272    }
273
274    /// Returns the client's most recent public signature key as a buffer.
275    /// Used to upload a public key to the server in order to verify client's messages signature.
276    ///
277    /// # Arguments
278    /// * `ciphersuite` - a callback to be called to perform authorization
279    /// * `credential_type` - of the credential to look for
280    pub async fn public_key(
281        &self,
282        ciphersuite: MlsCiphersuite,
283        credential_type: MlsCredentialType,
284    ) -> crate::mls::Result<Vec<u8>> {
285        let cb = self
286            .find_most_recent_credential_bundle(ciphersuite.signature_algorithm(), credential_type)
287            .await
288            .map_err(RecursiveError::mls_client("finding most recent credential bundle"))?;
289        Ok(cb.signature_key.to_public_vec())
290    }
291
292    pub(crate) fn new_basic_credential_bundle(
293        id: &ClientId,
294        sc: SignatureScheme,
295        backend: &MlsCryptoProvider,
296    ) -> Result<CredentialBundle> {
297        let (sk, pk) = backend
298            .crypto()
299            .signature_key_gen(sc)
300            .map_err(MlsError::wrap("generating a signature key"))?;
301
302        let signature_key = SignatureKeyPair::from_raw(sc, sk, pk);
303        let credential = Credential::new_basic(id.to_vec());
304        let cb = CredentialBundle {
305            credential,
306            signature_key,
307            created_at: 0,
308        };
309
310        Ok(cb)
311    }
312
313    pub(crate) fn new_x509_credential_bundle(cert: CertificateBundle) -> Result<CredentialBundle> {
314        let created_at = cert
315            .get_created_at()
316            .map_err(RecursiveError::mls_credential("getting credetntial created at"))?;
317        let (sk, ..) = cert.private_key.into_parts();
318        let chain = cert.certificate_chain;
319
320        let kp = CertificateKeyPair::new(sk, chain.clone()).map_err(MlsError::wrap("creating certificate key pair"))?;
321
322        let credential = Credential::new_x509(chain).map_err(MlsError::wrap("creating x509 credential"))?;
323
324        let cb = CredentialBundle {
325            credential,
326            signature_key: kp.0,
327            created_at,
328        };
329        Ok(cb)
330    }
331
332    /// Checks if a given conversation id exists locally
333    pub async fn conversation_exists(&self, id: &ConversationId) -> Result<bool> {
334        match self.get_raw_conversation(id).await {
335            Ok(_) => Ok(true),
336            Err(Error::Leaf(LeafError::ConversationNotFound(_))) => Ok(false),
337            Err(e) => Err(e),
338        }
339    }
340
341    /// Generates a random byte array of the specified size
342    pub fn random_bytes(&self, len: usize) -> crate::mls::Result<Vec<u8>> {
343        use openmls_traits::random::OpenMlsRand as _;
344        self.crypto_provider
345            .rand()
346            .random_vec(len)
347            .map_err(MlsError::wrap("generating random vector"))
348            .map_err(Into::into)
349    }
350
351    /// Reports whether the local KeyStore believes that it can currently close.
352    ///
353    /// Beware TOCTOU!
354    pub async fn can_close(&self) -> bool {
355        self.crypto_provider.can_close().await
356    }
357
358    /// Closes the connection with the local KeyStore
359    ///
360    /// # Errors
361    /// KeyStore errors, such as IO
362    pub async fn close(self) -> crate::mls::Result<()> {
363        self.crypto_provider
364            .close()
365            .await
366            .map_err(MlsError::wrap("closing connection with keystore"))
367            .map_err(Into::into)
368    }
369
370    /// see [mls_crypto_provider::MlsCryptoProvider::reseed]
371    pub async fn reseed(&self, seed: Option<EntropySeed>) -> crate::mls::Result<()> {
372        self.crypto_provider
373            .reseed(seed)
374            .map_err(MlsError::wrap("reseeding mls backend"))
375            .map_err(Into::into)
376    }
377
378    /// Generates a brand new client from scratch
379    pub(crate) async fn generate(
380        &self,
381        identifier: ClientIdentifier,
382        backend: &MlsCryptoProvider,
383        ciphersuites: &[MlsCiphersuite],
384        nb_key_package: usize,
385    ) -> Result<()> {
386        self.ensure_unready().await?;
387        let id = identifier.get_id()?;
388        let signature_schemes = ciphersuites
389            .iter()
390            .map(|cs| cs.signature_algorithm())
391            .collect::<HashSet<_>>();
392        self.replace_inner(SessionInner {
393            id: id.into_owned(),
394            identities: Identities::new(signature_schemes.len()),
395            keypackage_lifetime: KEYPACKAGE_DEFAULT_LIFETIME,
396        })
397        .await;
398
399        let identities = identifier.generate_credential_bundles(backend, signature_schemes)?;
400
401        for (sc, id, cb) in identities {
402            self.save_identity(&backend.keystore(), Some(&id), sc, cb).await?;
403        }
404
405        let guard = self.inner.read().await;
406        let SessionInner { identities, .. } = guard.as_ref().ok_or(Error::MlsNotInitialized)?;
407
408        if nb_key_package != 0 {
409            for ciphersuite in ciphersuites.iter().copied() {
410                let ciphersuite_signature_scheme = ciphersuite.signature_algorithm();
411                for credential_bundle in identities.iter().filter_map(|(signature_scheme, credential_bundle)| {
412                    (signature_scheme == ciphersuite_signature_scheme).then_some(credential_bundle)
413                }) {
414                    let credential_type = credential_bundle.credential.credential_type().into();
415                    self.request_key_packages(nb_key_package, ciphersuite, credential_type, backend)
416                        .await?;
417                }
418            }
419        }
420
421        Ok(())
422    }
423
424    /// Loads the client from the keystore.
425    pub(crate) async fn load(
426        &self,
427        backend: &MlsCryptoProvider,
428        id: &ClientId,
429        mut credentials: Vec<(Credential, u64)>,
430        signature_schemes: HashSet<SignatureScheme>,
431    ) -> Result<()> {
432        self.ensure_unready().await?;
433        let mut identities = Identities::new(signature_schemes.len());
434
435        // ensures we load credentials in chronological order
436        credentials.sort_by_key(|(_, timestamp)| *timestamp);
437
438        let stored_signature_keypairs = backend
439            .key_store()
440            .find_all::<MlsSignatureKeyPair>(EntityFindParams::default())
441            .await
442            .map_err(KeystoreError::wrap("finding all mls signature keypairs"))?;
443
444        for signature_scheme in signature_schemes {
445            let signature_keypair = stored_signature_keypairs
446                .iter()
447                .find(|skp| skp.signature_scheme == (signature_scheme as u16));
448
449            let signature_key = if let Some(kp) = signature_keypair {
450                SignatureKeyPair::tls_deserialize(&mut kp.keypair.as_slice())
451                    .map_err(Error::tls_deserialize("signature keypair"))?
452            } else {
453                let (private_key, public_key) = backend
454                    .crypto()
455                    .signature_key_gen(signature_scheme)
456                    .map_err(MlsError::wrap("generating signature key"))?;
457                let keypair = SignatureKeyPair::from_raw(signature_scheme, private_key, public_key.clone());
458                let raw_keypair = keypair
459                    .tls_serialize_detached()
460                    .map_err(Error::tls_serialize("raw keypair"))?;
461                let store_keypair =
462                    MlsSignatureKeyPair::new(signature_scheme, public_key, raw_keypair, id.as_slice().into());
463                backend
464                    .key_store()
465                    .save(store_keypair.clone())
466                    .await
467                    .map_err(KeystoreError::wrap("storing keypairs in keystore"))?;
468                SignatureKeyPair::tls_deserialize(&mut store_keypair.keypair.as_slice())
469                    .map_err(Error::tls_deserialize("signature keypair"))?
470            };
471
472            for (credential, created_at) in &credentials {
473                match credential.mls_credential() {
474                    openmls::prelude::MlsCredentialType::Basic(_) => {
475                        if id.as_slice() != credential.identity() {
476                            return Err(Error::WrongCredential);
477                        }
478                    }
479                    openmls::prelude::MlsCredentialType::X509(cert) => {
480                        let spk = cert
481                            .extract_public_key()
482                            .map_err(RecursiveError::mls_credential("extracting public key"))?
483                            .ok_or(LeafError::InternalMlsError)?;
484                        if signature_key.public() != spk {
485                            return Err(Error::WrongCredential);
486                        }
487                    }
488                };
489                let cb = CredentialBundle {
490                    credential: credential.clone(),
491                    signature_key: signature_key.clone(),
492                    created_at: *created_at,
493                };
494                identities.push_credential_bundle(signature_scheme, cb).await?;
495            }
496        }
497        self.replace_inner(SessionInner {
498            id: id.clone(),
499            identities,
500            keypackage_lifetime: KEYPACKAGE_DEFAULT_LIFETIME,
501        })
502        .await;
503        Ok(())
504    }
505
506    /// Restore from an external [`HistorySecret`].
507    pub(crate) async fn restore_from_history_secret(&self, history_secret: HistorySecret) -> Result<()> {
508        self.ensure_unready().await?;
509
510        // store the client id (with some other stuff)
511        self.replace_inner(SessionInner {
512            id: history_secret.client_id.clone(),
513            identities: Identities::new(1),
514            keypackage_lifetime: KEYPACKAGE_DEFAULT_LIFETIME,
515        })
516        .await;
517
518        // store the key package
519        let key_package = history_secret
520            .key_package
521            .store(&self.crypto_provider)
522            .await
523            .map_err(MlsError::wrap("storing key package encapsulation"))?;
524
525        let keystore = self.crypto_provider.key_store();
526
527        // store the credential bundle (with some other stuff)
528        self.save_identity(
529            keystore,
530            Some(&history_secret.client_id),
531            key_package.ciphersuite().signature_algorithm(),
532            history_secret.credential_bundle,
533        )
534        .await?;
535
536        Ok(())
537    }
538
539    pub(crate) async fn save_identity(
540        &self,
541        keystore: &Connection,
542        id: Option<&ClientId>,
543        signature_scheme: SignatureScheme,
544        mut credential_bundle: CredentialBundle,
545    ) -> Result<CredentialBundle> {
546        let mut guard = self.inner.write().await;
547        let SessionInner {
548            id: existing_id,
549            identities,
550            ..
551        } = guard.as_mut().ok_or(Error::MlsNotInitialized)?;
552
553        let id = id.unwrap_or(existing_id);
554
555        let credential = credential_bundle
556            .credential
557            .tls_serialize_detached()
558            .map_err(Error::tls_serialize("credential bundle"))?;
559        let credential = MlsCredential {
560            id: id.clone().into(),
561            credential,
562            created_at: 0,
563        };
564
565        let credential = keystore
566            .save(credential)
567            .await
568            .map_err(KeystoreError::wrap("saving credential"))?;
569
570        let sign_kp = MlsSignatureKeyPair::new(
571            signature_scheme,
572            credential_bundle.signature_key.to_public_vec(),
573            credential_bundle
574                .signature_key
575                .tls_serialize_detached()
576                .map_err(Error::tls_serialize("signature keypair"))?,
577            id.clone().into(),
578        );
579        keystore.save(sign_kp).await.map_err(|e| match e {
580            CryptoKeystoreError::AlreadyExists => Error::CredentialBundleConflict,
581            _ => KeystoreError::wrap("saving mls signature key pair")(e).into(),
582        })?;
583
584        // set the creation date of the signature keypair which is the same for the CredentialBundle
585        credential_bundle.created_at = credential.created_at;
586
587        identities
588            .push_credential_bundle(signature_scheme, credential_bundle.clone())
589            .await?;
590
591        Ok(credential_bundle)
592    }
593
594    /// Retrieves the client's client id. This is free-form and not inspected.
595    pub async fn id(&self) -> Result<ClientId> {
596        match self.inner.read().await.deref() {
597            None => Err(Error::MlsNotInitialized),
598            Some(SessionInner { id, .. }) => Ok(id.clone()),
599        }
600    }
601
602    /// Returns whether this client is E2EI capable
603    pub async fn is_e2ei_capable(&self) -> bool {
604        match self.inner.read().await.deref() {
605            None => false,
606            Some(SessionInner { identities, .. }) => identities
607                .iter()
608                .any(|(_, cred)| cred.credential().credential_type() == CredentialType::X509),
609        }
610    }
611
612    pub(crate) async fn get_most_recent_or_create_credential_bundle(
613        &self,
614        backend: &MlsCryptoProvider,
615        sc: SignatureScheme,
616        ct: MlsCredentialType,
617    ) -> Result<Arc<CredentialBundle>> {
618        match ct {
619            MlsCredentialType::Basic => {
620                self.init_basic_credential_bundle_if_missing(backend, sc).await?;
621                self.find_most_recent_credential_bundle(sc, ct).await
622            }
623            MlsCredentialType::X509 => self
624                .find_most_recent_credential_bundle(sc, ct)
625                .await
626                .map_err(|e| match e {
627                    Error::CredentialNotFound(_) => LeafError::E2eiEnrollmentNotDone.into(),
628                    _ => e,
629                }),
630        }
631    }
632
633    pub(crate) async fn init_basic_credential_bundle_if_missing(
634        &self,
635        backend: &MlsCryptoProvider,
636        sc: SignatureScheme,
637    ) -> Result<()> {
638        let existing_cb = self
639            .find_most_recent_credential_bundle(sc, MlsCredentialType::Basic)
640            .await;
641        if matches!(existing_cb, Err(Error::CredentialNotFound(_))) {
642            let id = self.id().await?;
643            debug!(id:% = &id; "Initializing basic credential bundle");
644            let cb = Self::new_basic_credential_bundle(&id, sc, backend)?;
645            self.save_identity(&backend.keystore(), None, sc, cb).await?;
646        }
647        Ok(())
648    }
649
650    pub(crate) async fn save_new_x509_credential_bundle(
651        &self,
652        keystore: &Connection,
653        sc: SignatureScheme,
654        cb: CertificateBundle,
655    ) -> Result<CredentialBundle> {
656        let id = cb
657            .get_client_id()
658            .map_err(RecursiveError::mls_credential("getting client id"))?;
659        let cb = Self::new_x509_credential_bundle(cb)?;
660        self.save_identity(keystore, Some(&id), sc, cb).await
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use crate::test_utils::*;
668    use crate::transaction_context::test_utils::EntitiesCount;
669    use core_crypto_keystore::connection::{DatabaseKey, FetchFromDatabase};
670    use core_crypto_keystore::entities::*;
671    use mls_crypto_provider::MlsCryptoProvider;
672    use wasm_bindgen_test::*;
673
674    impl Session {
675        // test functions are not held to the same documentation standard as proper functions
676        #![allow(missing_docs)]
677
678        pub async fn random_generate(
679            &self,
680            case: &crate::test_utils::TestContext,
681            signer: Option<&crate::test_utils::x509::X509Certificate>,
682            provision: bool,
683        ) -> Result<()> {
684            self.reset().await;
685            let user_uuid = uuid::Uuid::new_v4();
686            let rnd_id = rand::random::<usize>();
687            let client_id = format!("{}:{rnd_id:x}@members.wire.com", user_uuid.hyphenated());
688            let identity = match case.credential_type {
689                MlsCredentialType::Basic => ClientIdentifier::Basic(client_id.as_str().into()),
690                MlsCredentialType::X509 => {
691                    let signer = signer.expect("Missing intermediate CA");
692                    CertificateBundle::rand_identifier(&client_id, &[signer])
693                }
694            };
695            let nb_key_package = if provision {
696                crate::prelude::INITIAL_KEYING_MATERIAL_COUNT
697            } else {
698                0
699            };
700            let backend = self.crypto_provider.clone();
701            self.generate(identity, &backend, &[case.ciphersuite()], nb_key_package)
702                .await?;
703            Ok(())
704        }
705
706        pub async fn find_keypackages(&self, backend: &MlsCryptoProvider) -> Result<Vec<openmls::prelude::KeyPackage>> {
707            use core_crypto_keystore::CryptoKeystoreMls as _;
708            let kps = backend
709                .key_store()
710                .mls_fetch_keypackages::<openmls::prelude::KeyPackage>(u32::MAX)
711                .await
712                .map_err(KeystoreError::wrap("fetching mls keypackages"))?;
713            Ok(kps)
714        }
715
716        pub(crate) async fn init_x509_credential_bundle_if_missing(
717            &self,
718            backend: &MlsCryptoProvider,
719            sc: SignatureScheme,
720            cb: CertificateBundle,
721        ) -> Result<()> {
722            let existing_cb = self
723                .find_most_recent_credential_bundle(sc, MlsCredentialType::X509)
724                .await
725                .is_err();
726            if existing_cb {
727                self.save_new_x509_credential_bundle(&backend.keystore(), sc, cb)
728                    .await?;
729            }
730            Ok(())
731        }
732
733        pub(crate) async fn generate_one_keypackage(
734            &self,
735            backend: &MlsCryptoProvider,
736            cs: MlsCiphersuite,
737            ct: MlsCredentialType,
738        ) -> Result<openmls::prelude::KeyPackage> {
739            let cb = self
740                .find_most_recent_credential_bundle(cs.signature_algorithm(), ct)
741                .await?;
742            self.generate_one_keypackage_from_credential_bundle(backend, cs, &cb)
743                .await
744        }
745
746        /// Count the entities
747        pub async fn count_entities(&self) -> EntitiesCount {
748            let keystore = self.crypto_provider.keystore();
749            let credential = keystore.count::<MlsCredential>().await.unwrap();
750            let encryption_keypair = keystore.count::<MlsEncryptionKeyPair>().await.unwrap();
751            let epoch_encryption_keypair = keystore.count::<MlsEpochEncryptionKeyPair>().await.unwrap();
752            let enrollment = keystore.count::<E2eiEnrollment>().await.unwrap();
753            let group = keystore.count::<PersistedMlsGroup>().await.unwrap();
754            let hpke_private_key = keystore.count::<MlsHpkePrivateKey>().await.unwrap();
755            let key_package = keystore.count::<MlsKeyPackage>().await.unwrap();
756            let pending_group = keystore.count::<PersistedMlsPendingGroup>().await.unwrap();
757            let pending_messages = keystore.count::<MlsPendingMessage>().await.unwrap();
758            let psk_bundle = keystore.count::<MlsPskBundle>().await.unwrap();
759            let signature_keypair = keystore.count::<MlsSignatureKeyPair>().await.unwrap();
760            EntitiesCount {
761                credential,
762                encryption_keypair,
763                epoch_encryption_keypair,
764                enrollment,
765                group,
766                hpke_private_key,
767                key_package,
768                pending_group,
769                pending_messages,
770                psk_bundle,
771                signature_keypair,
772            }
773        }
774    }
775    wasm_bindgen_test_configure!(run_in_browser);
776
777    #[apply(all_cred_cipher)]
778    #[wasm_bindgen_test]
779    async fn can_generate_session(case: TestContext) {
780        let [alice] = case.sessions().await;
781        let key = DatabaseKey::generate();
782        let backend = MlsCryptoProvider::try_new_in_memory(&key).await.unwrap();
783        let x509_test_chain = if case.is_x509() {
784            let x509_test_chain = crate::test_utils::x509::X509TestChain::init_empty(case.signature_scheme());
785            x509_test_chain.register_with_provider(&backend).await;
786            Some(x509_test_chain)
787        } else {
788            None
789        };
790        backend.new_transaction().await.unwrap();
791        let session = alice.session().await;
792        session
793            .random_generate(
794                &case,
795                x509_test_chain.as_ref().map(|chain| chain.find_local_intermediate_ca()),
796                false,
797            )
798            .await
799            .unwrap();
800    }
801}