core_crypto/mls/conversation/
mod.rs

1//! MLS groups (aka conversation) are the actual entities cementing all the participants in a
2//! conversation.
3//!
4//! This table summarizes what operations are permitted on a group depending its state:
5//! *(PP=pending proposal, PC=pending commit)*
6//!
7//! | can I ?   | 0 PP / 0 PC | 1+ PP / 0 PC | 0 PP / 1 PC | 1+ PP / 1 PC |
8//! |-----------|-------------|--------------|-------------|--------------|
9//! | encrypt   | ✅           | ❌            | ❌           | ❌            |
10//! | handshake | ✅           | ✅            | ❌           | ❌            |
11//! | merge     | ❌           | ❌            | ✅           | ✅            |
12//! | decrypt   | ✅           | ✅            | ✅           | ✅            |
13
14pub(crate) mod commit;
15mod commit_delay;
16pub(crate) mod config;
17pub(crate) mod conversation_guard;
18mod credential;
19mod duplicate;
20#[cfg(test)]
21mod durability;
22mod error;
23pub(crate) mod group_info;
24mod id;
25mod immutable_conversation;
26pub(crate) mod merge;
27mod orphan_welcome;
28mod own_commit;
29pub(crate) mod pending_conversation;
30mod persistence;
31pub(crate) mod proposal;
32mod renew;
33pub(crate) mod welcome;
34mod wipe;
35
36use std::{
37    borrow::Borrow,
38    collections::{HashMap, HashSet},
39    ops::Deref,
40    sync::Arc,
41};
42
43use core_crypto_keystore::Database;
44use itertools::Itertools as _;
45use log::trace;
46use openmls::{
47    group::{MlsGroup, QueuedProposal},
48    prelude::{LeafNode, LeafNodeIndex, Proposal, Sender},
49};
50use openmls_traits::OpenMlsCryptoProvider;
51
52use self::config::MlsConversationConfiguration;
53pub use self::{
54    conversation_guard::ConversationGuard,
55    error::{Error, Result},
56    id::{ConversationId, ConversationIdRef},
57    immutable_conversation::ImmutableConversation,
58};
59use super::credential::Credential;
60use crate::{
61    Ciphersuite, ClientId, ClientIdRef, CredentialRef, CredentialType, E2eiConversationState, LeafError, MlsError,
62    RecursiveError, UserId, WireIdentity,
63    mls::{HasSessionAndCrypto, Session, credential::ext::CredentialExt as _},
64    mls_provider::MlsCryptoProvider,
65};
66
67/// The base layer for [Conversation].
68/// The trait is only exposed internally.
69#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
70#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
71pub(crate) trait ConversationWithMls<'a> {
72    /// [`Session`] and [`TransactionContext`][crate::transaction_context::TransactionContext] both implement
73    /// [`HasSessionAndCrypto`].
74    type Context: HasSessionAndCrypto;
75
76    type Conversation: Deref<Target = MlsConversation> + Send;
77
78    async fn context(&self) -> Result<Self::Context>;
79
80    async fn conversation(&'a self) -> Self::Conversation;
81
82    async fn crypto_provider(&self) -> Result<MlsCryptoProvider> {
83        self.context()
84            .await?
85            .crypto_provider()
86            .await
87            .map_err(RecursiveError::mls("getting mls provider"))
88            .map_err(Into::into)
89    }
90
91    async fn session(&self) -> Result<Session<Database>> {
92        self.context()
93            .await?
94            .session()
95            .await
96            .map_err(RecursiveError::mls("getting mls client"))
97            .map_err(Into::into)
98    }
99}
100
101/// The `Conversation` trait provides a set of operations that can be done on
102/// an **immutable** conversation.
103// We keep the super trait internal intentionally, as it is not meant to be used by the public API,
104// hence #[expect(private_bounds)].
105#[expect(private_bounds)]
106#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]
107#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]
108pub trait Conversation<'a>: ConversationWithMls<'a> {
109    /// Returns the epoch of a given conversation
110    async fn epoch(&'a self) -> u64 {
111        self.conversation().await.group().epoch().as_u64()
112    }
113
114    /// Returns the ciphersuite of a given conversation
115    async fn ciphersuite(&'a self) -> Ciphersuite {
116        self.conversation().await.ciphersuite()
117    }
118
119    /// Returns the credential ref to a credential of a given conversation
120    async fn credential_ref(&'a self) -> Result<CredentialRef> {
121        let inner = self.conversation().await;
122        let session = self.session().await?;
123        let credential = inner
124            .find_current_credential(&session)
125            .await
126            .map_err(|_| Error::IdentityInitializationError)?;
127        Ok(CredentialRef::from_credential(&credential))
128    }
129
130    /// Derives a new key from the one in the group, to be used elsewhere.
131    ///
132    /// # Arguments
133    /// * `key_length` - the length of the key to be derived. If the value is higher than the bounds of `u16` or the
134    ///   context hash * 255, an error will be returned
135    ///
136    /// # Errors
137    /// OpenMls secret generation error
138    async fn export_secret_key(&'a self, key_length: usize) -> Result<Vec<u8>> {
139        const EXPORTER_LABEL: &str = "exporter";
140        const EXPORTER_CONTEXT: &[u8] = &[];
141        let backend = self.crypto_provider().await?;
142        let inner = self.conversation().await;
143        inner
144            .group()
145            .export_secret(&backend, EXPORTER_LABEL, EXPORTER_CONTEXT, key_length)
146            .map_err(MlsError::wrap("exporting secret key"))
147            .map_err(Into::into)
148    }
149
150    /// Exports the clients from a conversation
151    ///
152    /// # Arguments
153    /// * `conversation_id` - the group/conversation id
154    async fn get_client_ids(&'a self) -> Vec<ClientId> {
155        let inner = self.conversation().await;
156        inner
157            .group()
158            .members()
159            .map(|kp| ClientId::from(kp.credential.identity().to_owned()))
160            .collect()
161    }
162
163    /// Returns the raw public key of the single external sender present in this group.
164    /// This should be used to initialize a subconversation
165    async fn get_external_sender(&'a self) -> Result<Vec<u8>> {
166        let inner = self.conversation().await;
167        let ext_senders = inner
168            .group()
169            .group_context_extensions()
170            .external_senders()
171            .ok_or(Error::MissingExternalSenderExtension)?;
172        let ext_sender = ext_senders.first().ok_or(Error::MissingExternalSenderExtension)?;
173        let ext_sender_public_key = ext_sender.signature_key().as_slice().to_vec();
174        Ok(ext_sender_public_key)
175    }
176
177    /// Indicates when to mark a conversation as not verified i.e. when not all its members have a X509
178    /// Credential generated by Wire's end-to-end identity enrollment
179    async fn e2ei_conversation_state(&'a self) -> Result<E2eiConversationState> {
180        let backend = self.crypto_provider().await?;
181        let authentication_service = backend.authentication_service();
182        authentication_service.refresh_time_of_interest().await;
183        let inner = self.conversation().await;
184        let state = Session::<Database>::compute_conversation_state(
185            inner.ciphersuite(),
186            inner.group.members_credentials(),
187            CredentialType::X509,
188            authentication_service.borrow().await.as_ref(),
189        )
190        .await;
191        Ok(state)
192    }
193
194    /// From a given conversation, get the identity of the members supplied. Identity is only present for
195    /// members with a Certificate Credential (after turning on end-to-end identity).
196    /// If no member has a x509 certificate, it will return an empty Vec
197    async fn get_device_identities(
198        &'a self,
199        device_ids: &[impl Borrow<ClientIdRef> + Sync],
200    ) -> Result<Vec<WireIdentity>> {
201        if device_ids.is_empty() {
202            return Err(Error::CallerError(
203                "This function accepts a list of IDs as a parameter, but that list was empty.",
204            ));
205        }
206        let mls_provider = self.crypto_provider().await?;
207        let auth_service = mls_provider.authentication_service();
208        auth_service.refresh_time_of_interest().await;
209        let auth_service = auth_service.borrow().await;
210        let env = auth_service.as_ref();
211        let conversation = self.conversation().await;
212        conversation
213            .members_with_key()
214            .into_iter()
215            .filter(|(id, _)| device_ids.iter().any(|client_id| client_id.borrow() == id))
216            .map(|(_, c)| {
217                c.extract_identity(conversation.ciphersuite(), env)
218                    .map_err(RecursiveError::mls_credential("extracting identity"))
219            })
220            .collect::<Result<Vec<_>, _>>()
221            .map_err(Into::into)
222    }
223
224    /// From a given conversation, get the identity of the users (device holders) supplied.
225    /// Identity is only present for devices with a Certificate Credential (after turning on end-to-end identity).
226    /// If no member has a x509 certificate, it will return an empty Vec.
227    ///
228    /// Returns a Map with all the identities for a given users. Consumers are then recommended to
229    /// reduce those identities to determine the actual status of a user.
230    async fn get_user_identities(&'a self, user_ids: &[String]) -> Result<HashMap<String, Vec<WireIdentity>>> {
231        if user_ids.is_empty() {
232            return Err(Error::CallerError(
233                "This function accepts a list of IDs as a parameter, but that list was empty.",
234            ));
235        }
236        let mls_provider = self.crypto_provider().await?;
237        let auth_service = mls_provider.authentication_service();
238        auth_service.refresh_time_of_interest().await;
239        let auth_service = auth_service.borrow().await;
240        let env = auth_service.as_ref();
241        let conversation = self.conversation().await;
242        let user_ids = user_ids.iter().map(|uid| uid.as_bytes()).collect::<Vec<_>>();
243
244        conversation
245            .members_with_key()
246            .iter()
247            .filter_map(|(id, c)| UserId::try_from(id.as_slice()).ok().zip(Some(c)))
248            .filter(|(uid, _)| user_ids.contains(uid))
249            .map(|(uid, c)| {
250                let uid = String::try_from(uid).map_err(RecursiveError::mls_client("getting user identities"))?;
251                let identity = c
252                    .extract_identity(conversation.ciphersuite(), env)
253                    .map_err(RecursiveError::mls_credential("extracting identity"))?;
254                Ok((uid, identity))
255            })
256            .process_results(|iter| iter.into_group_map())
257    }
258
259    /// Generate a new [`crate::HistorySecret`].
260    ///
261    /// This is useful when it's this client's turn to generate a new history client.
262    ///
263    /// The generated secret is cryptographically unrelated to the current CoreCrypto client.
264    async fn generate_history_secret(&'a self) -> Result<crate::HistorySecret> {
265        let ciphersuite = self.ciphersuite().await;
266        crate::ephemeral::generate_history_secret(ciphersuite)
267            .await
268            .map_err(RecursiveError::root("generating history secret"))
269            .map_err(Into::into)
270    }
271
272    /// Check if history sharing is enabled, i.e., if any of the conversation members have a [ClientId] starting
273    /// with [crate::HISTORY_CLIENT_ID_PREFIX].
274    async fn is_history_sharing_enabled(&'a self) -> bool {
275        self.get_client_ids()
276            .await
277            .iter()
278            .any(|client_id| client_id.starts_with(crate::ephemeral::HISTORY_CLIENT_ID_PREFIX.as_bytes()))
279    }
280}
281
282impl<'a, T: ConversationWithMls<'a>> Conversation<'a> for T {}
283
284/// This is a wrapper on top of the OpenMls's [MlsGroup], that provides Core Crypto specific functionality
285///
286/// This type will store the state of a group. With the [MlsGroup] it holds, it provides all
287/// operations that can be done in a group, such as creating proposals and commits.
288/// More information [here](https://messaginglayersecurity.rocks/mls-architecture/draft-ietf-mls-architecture.html#name-general-setting)
289#[derive(Debug)]
290#[allow(dead_code)]
291pub struct MlsConversation {
292    pub(crate) id: ConversationId,
293    pub(crate) parent_id: Option<ConversationId>,
294    pub(crate) group: MlsGroup,
295    configuration: MlsConversationConfiguration,
296}
297
298impl MlsConversation {
299    /// Creates a new group/conversation
300    pub async fn create(
301        id: ConversationId,
302        provider: &MlsCryptoProvider,
303        database: &Database,
304        credential_ref: &CredentialRef,
305        configuration: MlsConversationConfiguration,
306    ) -> Result<Self> {
307        let credential = credential_ref
308            .load(database)
309            .await
310            .map_err(RecursiveError::mls_credential_ref("getting credential"))?;
311
312        let group = MlsGroup::new_with_group_id(
313            provider,
314            &credential.signature_key_pair,
315            &configuration.as_openmls_default_configuration()?,
316            openmls::prelude::GroupId::from_slice(id.as_ref()),
317            credential.to_mls_credential_with_key(),
318        )
319        .await
320        .map_err(MlsError::wrap("creating group with id"))?;
321
322        let mut conversation = Self {
323            id,
324            group,
325            parent_id: None,
326            configuration,
327        };
328
329        conversation.persist_group_when_changed(database, true).await?;
330
331        Ok(conversation)
332    }
333
334    /// Internal API: create a group from an existing conversation. For example by external commit
335    pub(crate) async fn from_mls_group(
336        group: MlsGroup,
337        configuration: MlsConversationConfiguration,
338        database: &Database,
339    ) -> Result<Self> {
340        let id = ConversationId::from(group.group_id().as_slice());
341
342        let mut conversation = Self {
343            id,
344            group,
345            configuration,
346            parent_id: None,
347        };
348
349        conversation.persist_group_when_changed(database, true).await?;
350
351        Ok(conversation)
352    }
353
354    /// Group/conversation id
355    pub fn id(&self) -> &ConversationId {
356        &self.id
357    }
358
359    pub(crate) fn group(&self) -> &MlsGroup {
360        &self.group
361    }
362
363    /// Get actual group members and subtract pending remove proposals
364    pub fn members_in_next_epoch(&self) -> Vec<ClientId> {
365        let pending_removals = self.pending_removals();
366        let existing_clients = self
367            .group
368            .members()
369            .filter_map(|kp| {
370                if !pending_removals.contains(&kp.index) {
371                    Some(kp.credential.identity().to_owned().into())
372                } else {
373                    trace!(client_index:% = kp.index; "Client is pending removal");
374                    None
375                }
376            })
377            .collect::<HashSet<_>>();
378        existing_clients.into_iter().collect()
379    }
380
381    /// Gather pending remove proposals
382    fn pending_removals(&self) -> Vec<LeafNodeIndex> {
383        self.group
384            .pending_proposals()
385            .filter_map(|proposal| match proposal.proposal() {
386                Proposal::Remove(remove) => Some(remove.removed()),
387                _ => None,
388            })
389            .collect::<Vec<_>>()
390    }
391
392    pub(crate) fn ciphersuite(&self) -> Ciphersuite {
393        self.configuration.ciphersuite
394    }
395
396    fn extract_own_updated_node_from_proposals<'a>(
397        own_index: &LeafNodeIndex,
398        pending_proposals: impl Iterator<Item = &'a QueuedProposal>,
399    ) -> Option<&'a LeafNode> {
400        pending_proposals
401            .filter_map(|proposal| {
402                if let Sender::Member(index) = proposal.sender()
403                    && index == own_index
404                    && let Proposal::Update(update_proposal) = proposal.proposal()
405                {
406                    return Some(update_proposal.leaf_node());
407                }
408                None
409            })
410            .last()
411    }
412
413    async fn find_credential_for_leaf_node(
414        &self,
415        session: &Session<Database>,
416        leaf_node: &LeafNode,
417    ) -> Result<Arc<Credential>> {
418        let credential = session
419            .find_credential_by_public_key(leaf_node.signature_key())
420            .await
421            .map_err(RecursiveError::mls_client("finding current credential"))?;
422        Ok(credential)
423    }
424
425    pub(crate) async fn find_current_credential(&self, client: &Session<Database>) -> Result<Arc<Credential>> {
426        // if the group has pending proposals one of which is an own update proposal, we should take the credential from
427        // there.
428        let own_leaf = Self::extract_own_updated_node_from_proposals(
429            &self.group().own_leaf_index(),
430            self.group().pending_proposals(),
431        )
432        .or_else(|| self.group.own_leaf())
433        .ok_or(LeafError::InternalMlsError)?;
434        self.find_credential_for_leaf_node(client, own_leaf).await
435    }
436}
437
438#[cfg(test)]
439pub mod test_utils {
440    use openmls::prelude::SignaturePublicKey;
441
442    use super::*;
443
444    impl MlsConversation {
445        pub fn signature_keys(&self) -> impl Iterator<Item = SignaturePublicKey> + '_ {
446            self.group
447                .members()
448                .map(|m| m.signature_key)
449                .map(|mpk| SignaturePublicKey::from(mpk.as_slice()))
450        }
451
452        pub fn encryption_keys(&self) -> impl Iterator<Item = Vec<u8>> + '_ {
453            self.group.members().map(|m| m.encryption_key)
454        }
455
456        pub fn extensions(&self) -> &openmls::prelude::Extensions {
457            self.group.export_group_context().extensions()
458        }
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use crate::test_utils::*;
466
467    #[apply(all_cred_cipher)]
468    pub async fn create_self_conversation_should_succeed(case: TestContext) {
469        let [alice] = case.sessions().await;
470        Box::pin(async move {
471            let conversation = case.create_conversation([&alice]).await;
472            assert_eq!(1, conversation.member_count().await);
473            let alice_can_send_message = conversation.guard().await.encrypt_message(b"me").await;
474            assert!(alice_can_send_message.is_ok());
475        })
476        .await;
477    }
478
479    #[apply(all_cred_cipher)]
480    pub async fn create_1_1_conversation_should_succeed(case: TestContext) {
481        let [alice, bob] = case.sessions().await;
482        Box::pin(async move {
483            let conversation = case.create_conversation([&alice, &bob]).await;
484            assert_eq!(2, conversation.member_count().await);
485            assert!(conversation.is_functional_and_contains([&alice, &bob]).await);
486        })
487        .await;
488    }
489
490    #[apply(all_cred_cipher)]
491    pub async fn create_many_people_conversation(case: TestContext) {
492        const SIZE_PLUS_1: usize = GROUP_SAMPLE_SIZE + 1;
493        let alice_and_friends = case.sessions::<SIZE_PLUS_1>().await;
494        Box::pin(async move {
495            let alice = &alice_and_friends[0];
496            let conversation = case.create_conversation([alice]).await;
497
498            let bob_and_friends = &alice_and_friends[1..];
499            let conversation = conversation.invite_notify(bob_and_friends).await;
500
501            assert_eq!(conversation.member_count().await, 1 + GROUP_SAMPLE_SIZE);
502            assert!(conversation.is_functional_and_contains(&alice_and_friends).await);
503        })
504        .await;
505    }
506
507    mod wire_identity_getters {
508        use super::Error;
509        use crate::{
510            ClientId, CredentialType, DeviceStatus, E2eiConversationState, mls::conversation::Conversation,
511            test_utils::*,
512        };
513
514        async fn all_identities_check<'a, C, const N: usize>(
515            conversation: &'a C,
516            user_ids: &[String; N],
517            expected_sizes: [usize; N],
518        ) where
519            C: Conversation<'a> + Sync,
520        {
521            let all_identities = conversation.get_user_identities(user_ids).await.unwrap();
522            assert_eq!(all_identities.len(), N);
523            for (expected_size, user_id) in expected_sizes.into_iter().zip(user_ids.iter()) {
524                let alice_identities = all_identities.get(user_id).unwrap();
525                assert_eq!(alice_identities.len(), expected_size);
526            }
527            // Not found
528            let not_found = conversation
529                .get_user_identities(&["aaaaaaaaaaaaa".to_string()])
530                .await
531                .unwrap();
532            assert!(not_found.is_empty());
533
534            // Invalid usage
535            let invalid = conversation.get_user_identities(&[]).await;
536            assert!(matches!(invalid.unwrap_err(), Error::CallerError(_)));
537        }
538
539        async fn check_identities_device_status<'a, C, const N: usize>(
540            conversation: &'a C,
541            client_ids: &[ClientId; N],
542            name_status: &[(impl ToString, DeviceStatus); N],
543        ) where
544            C: Conversation<'a> + Sync,
545        {
546            let mut identities = conversation.get_device_identities(client_ids).await.unwrap();
547
548            for (user_name, status) in name_status.iter() {
549                let client_identity = identities.remove(
550                    identities
551                        .iter()
552                        .position(|i| i.x509_identity.as_ref().unwrap().display_name == user_name.to_string())
553                        .unwrap(),
554                );
555                assert_eq!(client_identity.status, *status);
556            }
557            assert!(identities.is_empty());
558
559            assert_eq!(
560                conversation.e2ei_conversation_state().await.unwrap(),
561                E2eiConversationState::NotVerified
562            );
563        }
564
565        #[macro_rules_attribute::apply(smol_macros::test)]
566        async fn should_read_device_identities() {
567            let case = TestContext::default_x509();
568
569            let [alice_android, alice_ios] = case.sessions().await;
570            Box::pin(async move {
571                let conversation = case.create_conversation([&alice_android, &alice_ios]).await;
572
573                let (android_id, ios_id) = (alice_android.get_client_id().await, alice_ios.get_client_id().await);
574
575                let mut android_ids = conversation
576                    .guard()
577                    .await
578                    .get_device_identities(&[android_id.clone(), ios_id.clone()])
579                    .await
580                    .unwrap();
581                android_ids.sort_by(|a, b| a.client_id.cmp(&b.client_id));
582                assert_eq!(android_ids.len(), 2);
583                let mut ios_ids = conversation
584                    .guard_of(&alice_ios)
585                    .await
586                    .get_device_identities(&[android_id.clone(), ios_id.clone()])
587                    .await
588                    .unwrap();
589                ios_ids.sort_by(|a, b| a.client_id.cmp(&b.client_id));
590                assert_eq!(ios_ids.len(), 2);
591
592                assert_eq!(android_ids, ios_ids);
593
594                let android_identities = conversation
595                    .guard()
596                    .await
597                    .get_device_identities(&[android_id])
598                    .await
599                    .unwrap();
600                let android_id = android_identities.first().unwrap();
601                assert_eq!(
602                    android_id.client_id.as_bytes(),
603                    alice_android.transaction.client_id().await.unwrap().0.as_slice()
604                );
605
606                let ios_identities = conversation
607                    .guard()
608                    .await
609                    .get_device_identities(&[ios_id])
610                    .await
611                    .unwrap();
612                let ios_id = ios_identities.first().unwrap();
613                assert_eq!(
614                    ios_id.client_id.as_bytes(),
615                    alice_ios.transaction.client_id().await.unwrap().0.as_slice()
616                );
617
618                let empty_slice: &[ClientId] = &[];
619                let invalid = conversation.guard().await.get_device_identities(empty_slice).await;
620                assert!(matches!(invalid.unwrap_err(), Error::CallerError(_)));
621            })
622            .await
623        }
624
625        // TODO: ignore this test for now, until we rework the test suite & CRL handling (WPB-19580).
626        #[ignore]
627        #[macro_rules_attribute::apply(smol_macros::test)]
628        async fn should_read_revoked_device() {
629            let case = TestContext::default_x509();
630            let rupert_user_id = uuid::Uuid::new_v4();
631            let bob_user_id = uuid::Uuid::new_v4();
632            let alice_user_id = uuid::Uuid::new_v4();
633
634            let [rupert_client_id] = case.x509_client_ids_for_user(&rupert_user_id);
635            let [alice_client_id] = case.x509_client_ids_for_user(&alice_user_id);
636            let [bob_client_id] = case.x509_client_ids_for_user(&bob_user_id);
637
638            let sessions = case
639                .sessions_x509_with_client_ids_and_revocation(
640                    [alice_client_id.clone(), bob_client_id.clone(), rupert_client_id.clone()],
641                    &[rupert_user_id.to_string()],
642                )
643                .await;
644
645            Box::pin(async move {
646                let [alice, bob, rupert] = &sessions;
647                let conversation = case.create_conversation(&sessions).await;
648
649                let (alice_id, bob_id, rupert_id) = (
650                    alice.get_client_id().await,
651                    bob.get_client_id().await,
652                    rupert.get_client_id().await,
653                );
654
655                let client_ids = [alice_id, bob_id, rupert_id];
656                let name_status = [
657                    (alice_user_id, DeviceStatus::Valid),
658                    (bob_user_id, DeviceStatus::Valid),
659                    (rupert_user_id, DeviceStatus::Revoked),
660                ];
661
662                // Do it a multiple times to avoid WPB-6904 happening again
663                for _ in 0..2 {
664                    for session in sessions.iter() {
665                        let conversation = conversation.guard_of(session).await;
666                        check_identities_device_status(&conversation, &client_ids, &name_status).await;
667                    }
668                }
669            })
670            .await
671        }
672
673        #[macro_rules_attribute::apply(smol_macros::test)]
674        async fn should_not_fail_when_basic() {
675            let case = TestContext::default();
676
677            let [alice_android, alice_ios] = case.sessions().await;
678            Box::pin(async move {
679                let conversation = case.create_conversation([&alice_android, &alice_ios]).await;
680
681                let (android_id, ios_id) = (alice_android.get_client_id().await, alice_ios.get_client_id().await);
682
683                let mut android_ids = conversation
684                    .guard()
685                    .await
686                    .get_device_identities(&[android_id.clone(), ios_id.clone()])
687                    .await
688                    .unwrap();
689                android_ids.sort();
690
691                let mut ios_ids = conversation
692                    .guard_of(&alice_ios)
693                    .await
694                    .get_device_identities(&[android_id, ios_id])
695                    .await
696                    .unwrap();
697                ios_ids.sort();
698
699                assert_eq!(ios_ids.len(), 2);
700                assert_eq!(ios_ids, android_ids);
701
702                assert!(ios_ids.iter().all(|i| {
703                    matches!(i.credential_type, CredentialType::Basic)
704                        && matches!(i.status, DeviceStatus::Valid)
705                        && i.x509_identity.is_none()
706                        && !i.thumbprint.is_empty()
707                        && !i.client_id.is_empty()
708                }));
709            })
710            .await
711        }
712
713        #[macro_rules_attribute::apply(smol_macros::test)]
714        async fn should_read_users() {
715            let case = TestContext::default_x509();
716            let [alice_android, alice_ios] = case.x509_client_ids_for_user(&uuid::Uuid::new_v4());
717            let [bob_android] = case.x509_client_ids();
718
719            let sessions = case
720                .sessions_x509_with_client_ids([alice_android, alice_ios, bob_android])
721                .await;
722
723            Box::pin(async move {
724                let conversation = case.create_conversation(&sessions).await;
725
726                let nb_members = conversation.member_count().await;
727                assert_eq!(nb_members, 3);
728
729                let [alice_android, alice_ios, bob_android] = &sessions;
730                assert_eq!(alice_android.get_user_id().await, alice_ios.get_user_id().await);
731
732                // Finds both Alice's devices
733                let alice_user_id = alice_android.get_user_id().await;
734                let alice_identities = conversation
735                    .guard()
736                    .await
737                    .get_user_identities(std::slice::from_ref(&alice_user_id))
738                    .await
739                    .unwrap();
740                assert_eq!(alice_identities.len(), 1);
741                let identities = alice_identities.get(&alice_user_id).unwrap();
742                assert_eq!(identities.len(), 2);
743
744                // Finds Bob only device
745                let bob_user_id = bob_android.get_user_id().await;
746                let bob_identities = conversation
747                    .guard()
748                    .await
749                    .get_user_identities(std::slice::from_ref(&bob_user_id))
750                    .await
751                    .unwrap();
752                assert_eq!(bob_identities.len(), 1);
753                let identities = bob_identities.get(&bob_user_id).unwrap();
754                assert_eq!(identities.len(), 1);
755
756                let user_ids = [alice_user_id, bob_user_id];
757                let expected_sizes = [2, 1];
758
759                for session in &sessions {
760                    all_identities_check(&conversation.guard_of(session).await, &user_ids, expected_sizes).await;
761                }
762            })
763            .await
764        }
765    }
766
767    mod export_secret {
768        use openmls::prelude::ExportSecretError;
769
770        use super::*;
771        use crate::MlsErrorKind;
772
773        #[apply(all_cred_cipher)]
774        pub async fn can_export_secret_key(case: TestContext) {
775            let [alice] = case.sessions().await;
776            Box::pin(async move {
777                let conversation = case.create_conversation([&alice]).await;
778
779                let key_length = 128;
780                let result = conversation.guard().await.export_secret_key(key_length).await;
781                assert!(result.is_ok());
782                assert_eq!(result.unwrap().len(), key_length);
783            })
784            .await
785        }
786
787        #[apply(all_cred_cipher)]
788        pub async fn cannot_export_secret_key_invalid_length(case: TestContext) {
789            let [alice] = case.sessions().await;
790            Box::pin(async move {
791                let conversation = case.create_conversation([&alice]).await;
792
793                let result = conversation.guard().await.export_secret_key(usize::MAX).await;
794                let error = result.unwrap_err();
795                assert!(innermost_source_matches!(
796                    error,
797                    MlsErrorKind::MlsExportSecretError(ExportSecretError::KeyLengthTooLong)
798                ));
799            })
800            .await
801        }
802    }
803
804    mod get_client_ids {
805        use super::*;
806
807        #[apply(all_cred_cipher)]
808        pub async fn can_get_client_ids(case: TestContext) {
809            let [alice, bob] = case.sessions().await;
810            Box::pin(async move {
811                let conversation = case.create_conversation([&alice]).await;
812
813                assert_eq!(conversation.guard().await.get_client_ids().await.len(), 1);
814
815                let conversation = conversation.invite_notify([&bob]).await;
816
817                assert_eq!(conversation.guard().await.get_client_ids().await.len(), 2);
818            })
819            .await
820        }
821    }
822
823    mod external_sender {
824        use super::*;
825
826        #[apply(all_cred_cipher)]
827        pub async fn should_fetch_ext_sender(mut case: TestContext) {
828            let [alice, external_sender] = case.sessions().await;
829            Box::pin(async move {
830                use core_crypto_keystore::Sha256Hash;
831
832                let conversation = case
833                    .create_conversation_with_external_sender(&external_sender, [&alice])
834                    .await;
835
836                let alice_ext_sender = conversation.guard().await.get_external_sender().await.unwrap();
837                assert!(!alice_ext_sender.is_empty());
838                assert_eq!(
839                    Sha256Hash::hash_from(alice_ext_sender),
840                    external_sender.initial_credential.public_key_hash()
841                );
842            })
843            .await
844        }
845    }
846}