core_crypto/mls/
external_commit.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
// Wire
// Copyright (C) 2022 Wire Swiss GmbH

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.

use openmls::prelude::{MlsGroup, group_info::VerifiableGroupInfo};
use openmls_traits::OpenMlsCryptoProvider;

use core_crypto_keystore::{
    CryptoKeystoreMls,
    connection::FetchFromDatabase,
    entities::{MlsPendingMessage, PersistedMlsPendingGroup},
};

use super::Result;
use crate::{
    KeystoreError, LeafError, MlsError, RecursiveError,
    context::CentralContext,
    mls,
    mls::credential::crl::{extract_crl_uris_from_group, get_new_crl_distribution_points},
    prelude::{
        ConversationId, MlsCiphersuite, MlsConversation, MlsConversationConfiguration, MlsCredentialType,
        MlsCustomConfiguration, MlsGroupInfoBundle, decrypt::MlsBufferedConversationDecryptMessage,
    },
};

use crate::prelude::{MlsCommitBundle, WelcomeBundle};

impl CentralContext {
    /// Issues an external commit and stores the group in a temporary table. This method is
    /// intended for example when a new client wants to join the user's existing groups.
    /// On success this function will return the group id and a message to be fanned out to other
    /// clients.
    ///
    /// If the Delivery Service accepts the external commit, you have to [CentralContext::merge_pending_group_from_external_commit]
    /// in order to get back a functional MLS group. On the opposite, if it rejects it, you can either
    /// retry by just calling again [CentralContext::join_by_external_commit].
    ///
    /// # Arguments
    /// * `group_info` - a GroupInfo wrapped in a MLS message. it can be obtained by deserializing a TLS serialized `GroupInfo` object
    /// * `custom_cfg` - configuration of the MLS conversation fetched from the Delivery Service
    /// * `credential_type` - kind of [openmls::prelude::Credential] to use for joining this group.
    ///   If [MlsCredentialType::Basic] is chosen and no Credential has been created yet for it,
    ///   a new one will be generated. When [MlsCredentialType::X509] is chosen, it fails when no
    ///   [openmls::prelude::Credential] has been created for the given Ciphersuite.
    ///
    /// # Return type
    /// It will return a tuple with the group/conversation id and the message containing the
    /// commit that was generated by this call
    ///
    /// # Errors
    /// Errors resulting from OpenMls, the KeyStore calls and serialization
    pub async fn join_by_external_commit(
        &self,
        group_info: VerifiableGroupInfo,
        custom_cfg: MlsCustomConfiguration,
        credential_type: MlsCredentialType,
    ) -> Result<WelcomeBundle> {
        let client = &self
            .mls_client()
            .await
            .map_err(RecursiveError::root("getting mls client"))?;

        let cs: MlsCiphersuite = group_info.ciphersuite().into();
        let mls_provider = self
            .mls_provider()
            .await
            .map_err(RecursiveError::root("getting mls provider"))?;
        let cb = client
            .get_most_recent_or_create_credential_bundle(&mls_provider, cs.signature_algorithm(), credential_type)
            .await
            .map_err(RecursiveError::mls_client("getting or creating credential bundle"))?;

        let serialized_cfg = serde_json::to_vec(&custom_cfg).map_err(MlsError::wrap("serializing mls keystore"))?;

        let configuration = MlsConversationConfiguration {
            ciphersuite: cs,
            custom: custom_cfg,
            ..Default::default()
        };

        let (group, commit, group_info) = MlsGroup::join_by_external_commit(
            &mls_provider,
            &cb.signature_key,
            None,
            group_info,
            &configuration
                .as_openmls_default_configuration()
                .map_err(RecursiveError::mls_conversation(
                    "using configuration as openmls default configuration",
                ))?,
            &[],
            cb.to_mls_credential_with_key(),
        )
        .await
        .map_err(MlsError::wrap("joining mls group by external commit"))?;

        // We should always have ratchet tree extension turned on hence GroupInfo should always be present
        let group_info = group_info.ok_or(LeafError::MissingGroupInfo)?;
        let group_info = MlsGroupInfoBundle::try_new_full_plaintext(group_info).map_err(
            RecursiveError::mls_conversation("trying new full plaintext group info bundle"),
        )?;

        let crl_new_distribution_points = get_new_crl_distribution_points(
            &mls_provider,
            extract_crl_uris_from_group(&group)
                .map_err(RecursiveError::mls_credential("extracting crl uris from group"))?,
        )
        .await
        .map_err(RecursiveError::mls_credential("getting new crl distribution points"))?;

        let new_group_id = group.group_id().to_vec();

        mls_provider
            .key_store()
            .mls_pending_groups_save(
                new_group_id.as_slice(),
                &core_crypto_keystore::ser(&group).map_err(KeystoreError::wrap("serializing mls group"))?,
                &serialized_cfg,
                None,
            )
            .await
            .map_err(KeystoreError::wrap("saving mls pending groups"))?;

        let commit_bundle = MlsCommitBundle {
            welcome: None,
            commit,
            group_info,
        };

        match self.send_commit(commit_bundle, None).await {
            Ok(need_to_merge_commit) => {
                debug_assert!(
                    need_to_merge_commit,
                    "If sending the external commit was successful, we should always need to merge it"
                );
                self.merge_pending_group_from_external_commit(&new_group_id).await?
            }
            Err(e @ mls::conversation::Error::MessageRejected { .. }) => {
                self.clear_pending_group_from_external_commit(&new_group_id).await?;
                return Err(RecursiveError::mls_conversation("sending commit")(e).into());
            }
            Err(e) => return Err(RecursiveError::mls_conversation("sending commit")(e).into()),
        };

        Ok(WelcomeBundle {
            id: new_group_id,
            crl_new_distribution_points,
        })
    }

    /// This merges the commit generated by [CentralContext::join_by_external_commit], persists the group permanently and
    /// deletes the temporary one. After merging, the group should be fully functional.
    ///
    /// # Arguments
    /// * `id` - the conversation id
    ///
    /// # Errors
    /// Errors resulting from OpenMls, the KeyStore calls and deserialization
    #[cfg_attr(test, crate::dispotent)]
    pub(crate) async fn merge_pending_group_from_external_commit(
        &self,
        id: &ConversationId,
    ) -> Result<Option<Vec<MlsBufferedConversationDecryptMessage>>> {
        // Retrieve the pending MLS group from the keystore
        let mls_provider = self
            .mls_provider()
            .await
            .map_err(RecursiveError::root("getting mls provider"))?;
        let (group, cfg) = mls_provider
            .key_store()
            .mls_pending_groups_load(id)
            .await
            .map_err(KeystoreError::wrap("loading mls pending groups"))?;

        let mut mls_group =
            core_crypto_keystore::deser::<MlsGroup>(&group).map_err(KeystoreError::wrap("deserializing mls group"))?;

        // Merge it aka bring the MLS group to life and make it usable
        mls_group
            .merge_pending_commit(&mls_provider)
            .await
            .map_err(MlsError::wrap("merging pending commit"))?;

        // Restore the custom configuration and build a conversation from it
        let custom_cfg =
            serde_json::from_slice(&cfg).map_err(MlsError::wrap("deserializing mls custom configuration"))?;
        let configuration = MlsConversationConfiguration {
            ciphersuite: mls_group.ciphersuite().into(),
            custom: custom_cfg,
            ..Default::default()
        };

        let is_rejoin = mls_provider.key_store().mls_group_exists(id.as_slice()).await;

        // Persist the now usable MLS group in the keystore
        // TODO: find a way to make the insertion of the MlsGroup and deletion of the pending group transactional. Tracking issue: WPB-9595
        let mut conversation = MlsConversation::from_mls_group(mls_group, configuration, &mls_provider)
            .await
            .map_err(RecursiveError::mls_conversation(
                "constructing conversation from mls group",
            ))?;

        let pending_messages = self
            .restore_pending_messages(&mut conversation, is_rejoin)
            .await
            .map_err(RecursiveError::mls_conversation("restoring pending messages"))?;

        self.mls_groups()
            .await
            .map_err(RecursiveError::root("getting mls groups"))?
            .insert(id.clone(), conversation);

        // cleanup the pending group we no longer need
        mls_provider
            .key_store()
            .mls_pending_groups_delete(id)
            .await
            .map_err(KeystoreError::wrap("cleaning up pending pending groups"))?;

        if pending_messages.is_some() {
            mls_provider
                .key_store()
                .remove::<MlsPendingMessage, _>(id)
                .await
                .map_err(KeystoreError::wrap("deleting mls pending message by id"))?;
        }

        Ok(pending_messages)
    }

    /// In case the external commit generated by [CentralContext::join_by_external_commit] is rejected by the Delivery Service
    /// and we want to abort this external commit once for all, we can wipe out the pending group from
    /// the keystore in order not to waste space
    ///
    /// # Arguments
    /// * `id` - the conversation id
    ///
    /// # Errors
    /// Errors resulting from the KeyStore calls
    pub(crate) async fn clear_pending_group_from_external_commit(&self, id: &ConversationId) -> Result<()> {
        self.keystore()
            .await
            .map_err(RecursiveError::root("getting keystore"))?
            .mls_pending_groups_delete(id)
            .await
            .map_err(KeystoreError::wrap("deleting pending groups by id"))?;
        Ok(())
    }

    pub(crate) async fn pending_group_exists(&self, id: &ConversationId) -> Result<bool> {
        Ok(self
            .keystore()
            .await
            .map_err(RecursiveError::root("getting keystore"))?
            .find::<PersistedMlsPendingGroup>(id.as_slice())
            .await
            .ok()
            .flatten()
            .is_some())
    }
}

#[cfg(test)]
mod tests {
    use openmls::prelude::*;
    use wasm_bindgen_test::*;

    use core_crypto_keystore::{CryptoKeystoreError, CryptoKeystoreMls, MissingKeyErrorKind};

    use crate::{
        LeafError,
        prelude::{MlsConversationConfiguration, WelcomeBundle},
        test_utils::*,
    };

    wasm_bindgen_test_configure!(run_in_browser);

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn join_by_external_commit_should_succeed(case: TestCase) {
        run_test_with_client_ids(
            case.clone(),
            ["alice", "bob"],
            move |[alice_central, mut bob_central]| {
                Box::pin(async move {
                    let id = conversation_id();
                    alice_central
                        .context
                        .new_conversation(&id, case.credential_type, case.cfg.clone())
                        .await
                        .unwrap();

                    // export Alice group info
                    let group_info = alice_central.get_group_info(&id).await;

                    // Bob tries to join Alice's group
                    let external_commit = bob_central
                        .create_unmerged_external_commit(group_info.clone(), case.custom_cfg(), case.credential_type)
                        .await
                        .commit;

                    // Alice acks the request and adds the new member
                    assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 1);
                    let decrypted = alice_central
                        .context
                        .decrypt_message(&id, &external_commit.to_bytes().unwrap())
                        .await
                        .unwrap();
                    assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 2);

                    // verify Bob's (sender) identity
                    bob_central.verify_sender_identity(&case, &decrypted).await;

                    // Let's say backend accepted our external commit.
                    // So Bob can merge the commit and update the local state
                    assert!(bob_central.context.get_conversation(&id).await.is_err());
                    bob_central
                        .context
                        .merge_pending_group_from_external_commit(&id)
                        .await
                        .unwrap();
                    assert!(bob_central.context.get_conversation(&id).await.is_ok());
                    assert_eq!(bob_central.get_conversation_unchecked(&id).await.members().len(), 2);
                    assert!(alice_central.try_talk_to(&id, &bob_central).await.is_ok());

                    // Pending group removed from keystore
                    let error = alice_central
                        .context
                        .keystore()
                        .await
                        .unwrap()
                        .mls_pending_groups_load(&id)
                        .await;
                    assert!(matches!(
                        error.unwrap_err(),
                        CryptoKeystoreError::MissingKeyInStore(MissingKeyErrorKind::MlsPendingGroup)
                    ));

                    // Ensure it's durable i.e. MLS group has been persisted
                    bob_central.context.drop_and_restore(&id).await;
                    assert!(bob_central.try_talk_to(&id, &alice_central).await.is_ok());
                })
            },
        )
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn join_by_external_commit_should_be_retriable(case: TestCase) {
        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();

                // export Alice group info
                let group_info = alice_central.get_group_info(&id).await;

                // Bob tries to join Alice's group
                bob_central
                    .create_unmerged_external_commit(group_info.clone(), case.custom_cfg(), case.credential_type)
                    .await;
                // BUT for some reason the Delivery Service will reject this external commit
                // e.g. another commit arrived meanwhile and the [GroupInfo] is no longer valid
                // But bob doesn't receive the rejection message, so the commit is still pending

                // Retrying
                let WelcomeBundle {
                    id: conversation_id, ..
                } = bob_central
                    .context
                    .join_by_external_commit(group_info, case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();
                assert_eq!(conversation_id.as_slice(), &id);
                assert!(bob_central.context.get_conversation(&id).await.is_ok());
                assert_eq!(bob_central.get_conversation_unchecked(&id).await.members().len(), 2);

                let external_commit = bob_central.mls_transport.latest_commit().await;
                // Alice decrypts the external commit and adds Bob
                assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 1);
                alice_central
                    .context
                    .decrypt_message(&id, &external_commit.to_bytes().unwrap())
                    .await
                    .unwrap();
                assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 2);

                assert!(alice_central.try_talk_to(&id, &bob_central).await.is_ok());
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn should_fail_when_bad_epoch(case: TestCase) {
        use crate::mls;

        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();

                let group_info = alice_central.get_group_info(&id).await;
                // try to make an external join into Alice's group
                bob_central
                    .context
                    .join_by_external_commit(group_info, case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();

                let external_commit = bob_central.mls_transport.latest_commit().await;

                // Alice creates a new commit before receiving the external join
                alice_central
                    .context
                    .conversation_guard(&id)
                    .await
                    .unwrap()
                    .update_key_material()
                    .await
                    .unwrap();

                // receiving the external join with outdated epoch should fail because of
                // the wrong epoch
                let result = alice_central
                    .context
                    .decrypt_message(&id, &external_commit.to_bytes().unwrap())
                    .await;
                assert!(matches!(result.unwrap_err(), mls::conversation::Error::StaleCommit));
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn existing_clients_can_join(case: TestCase) {
        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();
                alice_central.invite_all(&case, &id, [&bob_central]).await.unwrap();
                let group_info = alice_central.get_group_info(&id).await;
                // Alice can rejoin by external commit
                alice_central
                    .context
                    .join_by_external_commit(group_info.clone(), case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn should_fail_when_no_pending_external_commit(case: TestCase) {
        use crate::{KeystoreError, mls};

        run_test_with_central(case.clone(), move |[central]| {
            Box::pin(async move {
                let id = conversation_id();
                // try to merge an inexisting pending group
                let merge_unknown = central.context.merge_pending_group_from_external_commit(&id).await;

                assert!(matches!(
                    merge_unknown.unwrap_err(),
                    mls::error::Error::Keystore(KeystoreError { source, .. })
                    if matches!(
                        source.downcast_ref(),
                        Some(&CryptoKeystoreError::MissingKeyInStore(MissingKeyErrorKind::MlsPendingGroup))
                    )
                ));
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn should_return_valid_group_info(case: TestCase) {
        run_test_with_client_ids(
            case.clone(),
            ["alice", "bob", "charlie"],
            move |[alice_central, bob_central, charlie_central]| {
                Box::pin(async move {
                    let id = conversation_id();
                    alice_central
                        .context
                        .new_conversation(&id, case.credential_type, case.cfg.clone())
                        .await
                        .unwrap();

                    // export Alice group info
                    let group_info = alice_central.get_group_info(&id).await;

                    // Bob tries to join Alice's group
                    bob_central
                        .context
                        .join_by_external_commit(group_info, case.custom_cfg(), case.credential_type)
                        .await
                        .unwrap();

                    let bob_external_commit = bob_central.mls_transport.latest_commit().await;
                    assert!(bob_central.context.get_conversation(&id).await.is_ok());
                    assert_eq!(bob_central.get_conversation_unchecked(&id).await.members().len(), 2);

                    // Alice decrypts the commit, Bob's in !
                    alice_central
                        .context
                        .decrypt_message(&id, &bob_external_commit.to_bytes().unwrap())
                        .await
                        .unwrap();
                    assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 2);
                    assert!(alice_central.try_talk_to(&id, &bob_central).await.is_ok());

                    // Now charlie wants to join with the [GroupInfo] from Bob's external commit
                    let group_info = bob_central.mls_transport.latest_group_info().await;
                    let bob_gi = group_info.get_group_info();
                    charlie_central
                        .context
                        .join_by_external_commit(bob_gi, case.custom_cfg(), case.credential_type)
                        .await
                        .unwrap();

                    let charlie_external_commit = charlie_central.mls_transport.latest_commit().await;

                    // Both Alice & Bob decrypt the commit
                    alice_central
                        .context
                        .decrypt_message(&id, charlie_external_commit.to_bytes().unwrap())
                        .await
                        .unwrap();
                    bob_central
                        .context
                        .decrypt_message(&id, charlie_external_commit.to_bytes().unwrap())
                        .await
                        .unwrap();
                    assert_eq!(alice_central.get_conversation_unchecked(&id).await.members().len(), 3);
                    assert_eq!(bob_central.get_conversation_unchecked(&id).await.members().len(), 3);

                    // Charlie is also in!
                    assert!(charlie_central.context.get_conversation(&id).await.is_ok());
                    assert_eq!(charlie_central.get_conversation_unchecked(&id).await.members().len(), 3);
                    assert!(charlie_central.try_talk_to(&id, &alice_central).await.is_ok());
                    assert!(charlie_central.try_talk_to(&id, &bob_central).await.is_ok());
                })
            },
        )
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn clear_pending_group_should_succeed(case: TestCase) {
        use crate::{KeystoreError, mls};

        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();

                let initial_count = alice_central.context.count_entities().await;

                // export Alice group info
                let group_info = alice_central.get_group_info(&id).await;

                // Bob tries to join Alice's group
                bob_central
                    .context
                    .join_by_external_commit(group_info, case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();

                // But for some reason, Bob wants to abort joining the group
                bob_central
                    .context
                    .clear_pending_group_from_external_commit(&id)
                    .await
                    .unwrap();

                let final_count = alice_central.context.count_entities().await;
                assert_eq!(initial_count, final_count);

                // Hence trying to merge the pending should fail
                let result = bob_central.context.merge_pending_group_from_external_commit(&id).await;
                assert!(matches!(
                    result.unwrap_err(),
                    mls::error::Error::Keystore(KeystoreError { source, .. })
                    if matches!(
                        source.downcast_ref(),
                        Some(&CryptoKeystoreError::MissingKeyInStore(MissingKeyErrorKind::MlsPendingGroup))
                    )
                ))
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn new_with_inflight_join_should_fail_when_already_exists(case: TestCase) {
        use crate::mls;

        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();
                let gi = alice_central.get_group_info(&id).await;

                // Bob to join a conversation but while the server processes its request he
                // creates a conversation with the id of the conversation he's trying to join
                bob_central
                    .context
                    .join_by_external_commit(gi, case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();
                // erroneous call
                let conflict_join = bob_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await;
                assert!(matches!(
                    conflict_join.unwrap_err(),
                    mls::Error::Leaf(LeafError::ConversationAlreadyExists(i))
                    if i == id
                ));
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn new_with_inflight_welcome_should_fail_when_already_exists(case: TestCase) {
        use crate::mls;

        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();
                let gi = alice_central.get_group_info(&id).await;

                // While Bob tries to join a conversation via external commit he's also invited
                // to a conversation with the same id through a Welcome message
                bob_central
                    .context
                    .join_by_external_commit(gi, case.custom_cfg(), case.credential_type)
                    .await
                    .unwrap();

                let bob = bob_central.rand_key_package(&case).await;
                alice_central
                    .context
                    .conversation_guard(&id)
                    .await
                    .unwrap()
                    .add_members(vec![bob])
                    .await
                    .unwrap();

                let welcome = alice_central.mls_transport.latest_welcome_message().await;
                // erroneous call
                let conflict_welcome = bob_central
                    .context
                    .process_welcome_message(welcome.into(), case.custom_cfg())
                    .await;

                assert!(matches!(
                    conflict_welcome.unwrap_err(),
                    mls::conversation::Error::Leaf(LeafError::ConversationAlreadyExists(i))
                    if i == id
                ));
            })
        })
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn should_fail_when_invalid_group_info(case: TestCase) {
        run_test_with_client_ids(
            case.clone(),
            ["alice", "bob", "guest"],
            move |[alice_central, bob_central, guest_central]| {
                Box::pin(async move {
                    let expiration_time = 14;
                    let start = web_time::Instant::now();
                    let id = conversation_id();
                    alice_central
                        .context
                        .new_conversation(&id, case.credential_type, case.cfg.clone())
                        .await
                        .unwrap();

                    let invalid_kp = bob_central.new_keypackage(&case, Lifetime::new(expiration_time)).await;
                    alice_central
                        .context
                        .conversation_guard(&id)
                        .await
                        .unwrap()
                        .add_members(vec![invalid_kp.into()])
                        .await
                        .unwrap();

                    let elapsed = start.elapsed();
                    // Give time to the certificate to expire
                    let expiration_time = core::time::Duration::from_secs(expiration_time);
                    if expiration_time > elapsed {
                        async_std::task::sleep(expiration_time - elapsed + core::time::Duration::from_secs(1)).await;
                    }

                    let group_info = alice_central.get_group_info(&id).await;

                    let join_ext_commit = guest_central
                        .context
                        .join_by_external_commit(group_info, case.custom_cfg(), case.credential_type)
                        .await;

                    // TODO: currently succeeds as we don't anymore validate KeyPackage lifetime upon reception: find another way to craft an invalid KeyPackage. Tracking issue: WPB-9596
                    join_ext_commit.unwrap();
                    /*assert!(matches!(
                        join_ext_commit.unwrap_err(),
                        CryptoError::MlsError(MlsError::MlsExternalCommitError(ExternalCommitError::PublicGroupError(
                            CreationFromExternalError::TreeSyncError(TreeSyncFromNodesError::LeafNodeValidationError(
                                LeafNodeValidationError::Lifetime(LifetimeError::NotCurrent),
                            )),
                        )))
                    ));*/
                })
            },
        )
        .await
    }

    #[apply(all_cred_cipher)]
    #[wasm_bindgen_test]
    async fn group_should_have_right_config(case: TestCase) {
        run_test_with_client_ids(case.clone(), ["alice", "bob"], move |[alice_central, bob_central]| {
            Box::pin(async move {
                let id = conversation_id();
                alice_central
                    .context
                    .new_conversation(&id, case.credential_type, case.cfg.clone())
                    .await
                    .unwrap();

                let gi = alice_central.get_group_info(&id).await;
                bob_central
                    .create_unmerged_external_commit(gi, case.custom_cfg(), case.credential_type)
                    .await;
                bob_central
                    .context
                    .merge_pending_group_from_external_commit(&id)
                    .await
                    .unwrap();
                let group = bob_central.get_conversation_unchecked(&id).await;

                let capabilities = group.group.group_context_extensions().required_capabilities().unwrap();

                // see https://www.rfc-editor.org/rfc/rfc9420.html#section-11.1
                assert!(capabilities.extension_types().is_empty());
                assert!(capabilities.proposal_types().is_empty());
                assert_eq!(
                    capabilities.credential_types(),
                    MlsConversationConfiguration::DEFAULT_SUPPORTED_CREDENTIALS
                );
            })
        })
        .await
    }
}