core_crypto/mls/
external_proposal.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
use log::trace;
use openmls::prelude::{GroupEpoch, GroupId, JoinProposal, LeafNodeIndex, MlsMessageOut, Proposal};
use std::collections::HashSet;

use crate::{
    mls::{credential::typ::MlsCredentialType, ClientId, ConversationId},
    prelude::{CryptoError, CryptoResult, MlsCiphersuite, MlsConversation, MlsError},
};

use crate::context::CentralContext;

impl MlsConversation {
    /// Get actual group members and subtract pending remove proposals
    pub fn members_in_next_epoch(&self) -> Vec<ClientId> {
        let pending_removals = self.pending_removals();
        let existing_clients = self
            .group
            .members()
            .filter_map(|kp| {
                if !pending_removals.contains(&kp.index) {
                    Some(kp.credential.identity().into())
                } else {
                    trace!(client_index:% = kp.index; "Client is pending removal");
                    None
                }
            })
            .collect::<HashSet<_>>();
        existing_clients.into_iter().collect()
    }

    /// Gather pending remove proposals
    fn pending_removals(&self) -> Vec<LeafNodeIndex> {
        self.group
            .pending_proposals()
            .filter_map(|proposal| match proposal.proposal() {
                Proposal::Remove(ref remove) => Some(remove.removed()),
                _ => None,
            })
            .collect::<Vec<_>>()
    }
}

impl CentralContext {
    /// Crafts a new external Add proposal. Enables a client outside a group to request addition to this group.
    /// For Wire only, the client must belong to an user already in the group
    ///
    /// # Arguments
    /// * `conversation_id` - the group/conversation id
    /// * `epoch` - the current epoch of the group. See [openmls::group::GroupEpoch]
    /// * `ciphersuite` - of the new [openmls::prelude::KeyPackage] to create
    /// * `credential_type` - of the new [openmls::prelude::KeyPackage] to create
    ///
    /// # Return type
    /// Returns a message with the proposal to be add a new client
    ///
    /// # Errors
    /// Errors resulting from the creation of the proposal within OpenMls.
    /// Fails when `credential_type` is [MlsCredentialType::X509] and no Credential has been created
    /// for it beforehand with [CentralContext::e2ei_mls_init_only] or variants.
    #[cfg_attr(test, crate::dispotent)]
    pub async fn new_external_add_proposal(
        &self,
        conversation_id: ConversationId,
        epoch: GroupEpoch,
        ciphersuite: MlsCiphersuite,
        credential_type: MlsCredentialType,
    ) -> CryptoResult<MlsMessageOut> {
        let group_id = GroupId::from_slice(&conversation_id[..]);
        let mls_provider = self.mls_provider().await?;

        let client = self.mls_client().await?;
        let cb = client
            .find_most_recent_credential_bundle(ciphersuite.signature_algorithm(), credential_type)
            .await;
        let cb = match (cb, credential_type) {
            (Ok(cb), _) => cb,
            (Err(CryptoError::CredentialNotFound(_)), MlsCredentialType::Basic) => {
                // If a Basic CredentialBundle does not exist, just create one instead of failing
                client
                    .init_basic_credential_bundle_if_missing(&mls_provider, ciphersuite.signature_algorithm())
                    .await?;

                client
                    .find_most_recent_credential_bundle(ciphersuite.signature_algorithm(), credential_type)
                    .await?
            }
            (Err(CryptoError::CredentialNotFound(_)), MlsCredentialType::X509) => {
                return Err(CryptoError::E2eiEnrollmentNotDone)
            }
            (Err(e), _) => return Err(e),
        };
        let kp = client
            .generate_one_keypackage_from_credential_bundle(&mls_provider, ciphersuite, &cb)
            .await?;

        Ok(JoinProposal::new(kp, group_id, epoch, &cb.signature_key).map_err(MlsError::from)?)
    }
}

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

    use crate::{prelude::MlsCommitBundle, test_utils::*};

    wasm_bindgen_test_configure!(run_in_browser);

    mod add {
        use super::*;

        #[apply(all_cred_cipher)]
        #[wasm_bindgen_test]
        async fn guest_should_externally_propose_adding_itself_to_owner_group(case: TestCase) {
            run_test_with_client_ids(
                case.clone(),
                ["owner", "guest"],
                move |[owner_central, guest_central]| {
                    Box::pin(async move {
                        let id = conversation_id();
                        owner_central
                            .context
                            .new_conversation(&id, case.credential_type, case.cfg.clone())
                            .await
                            .unwrap();
                        let epoch = owner_central.get_conversation_unchecked(&id).await.group.epoch();

                        // Craft an external proposal from guest
                        let external_add = guest_central
                            .context
                            .new_external_add_proposal(id.clone(), epoch, case.ciphersuite(), case.credential_type)
                            .await
                            .unwrap();

                        // Owner receives external proposal message from server
                        let decrypted = owner_central
                            .context
                            .decrypt_message(&id, external_add.to_bytes().unwrap())
                            .await
                            .unwrap();
                        // just owner for now
                        assert_eq!(owner_central.get_conversation_unchecked(&id).await.members().len(), 1);

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

                        // simulate commit message reception from server
                        let MlsCommitBundle { welcome, .. } = owner_central
                            .context
                            .commit_pending_proposals(&id)
                            .await
                            .unwrap()
                            .unwrap();
                        owner_central.context.commit_accepted(&id).await.unwrap();
                        // guest joined the group
                        assert_eq!(owner_central.get_conversation_unchecked(&id).await.members().len(), 2);

                        guest_central
                            .context
                            .process_welcome_message(welcome.unwrap().into(), case.custom_cfg())
                            .await
                            .unwrap();
                        assert_eq!(guest_central.get_conversation_unchecked(&id).await.members().len(), 2);
                        // guest can send messages in the group
                        assert!(guest_central.try_talk_to(&id, &owner_central).await.is_ok());
                    })
                },
            )
            .await
        }
    }

    mod remove {
        use super::*;
        use crate::prelude::{CryptoError, MlsConversationCreationMessage, MlsConversationInitBundle, MlsError};
        use openmls::prelude::{
            ExternalProposal, GroupId, MlsMessageIn, ProcessMessageError, SenderExtensionIndex, ValidationError,
        };

        #[apply(all_cred_cipher)]
        #[wasm_bindgen_test]
        async fn ds_should_remove_guest_from_conversation(case: TestCase) {
            run_test_with_client_ids(case.clone(), ["owner", "guest", "ds"], move |[owner, guest, ds]| {
                Box::pin(async move {
                    let owner_central = &owner.context;
                    let guest_central = &guest.context;
                    let id = conversation_id();

                    let ds_signature_key = ds.client_signature_key(&case).await.as_slice().to_vec();
                    let mut cfg = case.cfg.clone();
                    owner_central
                        .set_raw_external_senders(&mut cfg, vec![ds_signature_key])
                        .await
                        .unwrap();
                    owner_central
                        .new_conversation(&id, case.credential_type, cfg)
                        .await
                        .unwrap();

                    owner.invite_all(&case, &id, [&guest]).await.unwrap();
                    assert_eq!(owner.get_conversation_unchecked(&id).await.members().len(), 2);

                    // now, as e.g. a Delivery Service, let's create an external remove proposal
                    // and kick guest out of the conversation
                    let to_remove = owner.index_of(&id, guest.get_client_id().await).await;
                    let sender_index = SenderExtensionIndex::new(0);

                    let (sc, ct) = (case.signature_scheme(), case.credential_type);
                    let cb = ds.find_most_recent_credential_bundle(sc, ct).await.unwrap();

                    let group_id = GroupId::from_slice(&id[..]);
                    let epoch = owner.get_conversation_unchecked(&id).await.group.epoch();
                    let proposal =
                        ExternalProposal::new_remove(to_remove, group_id, epoch, &cb.signature_key, sender_index)
                            .unwrap();

                    owner_central
                        .decrypt_message(&id, proposal.to_bytes().unwrap())
                        .await
                        .unwrap();
                    guest_central
                        .decrypt_message(&id, proposal.to_bytes().unwrap())
                        .await
                        .unwrap();
                    let MlsCommitBundle { commit, .. } =
                        owner_central.commit_pending_proposals(&id).await.unwrap().unwrap();

                    // before merging, commit is not applied
                    assert_eq!(owner.get_conversation_unchecked(&id).await.members().len(), 2);
                    owner_central.commit_accepted(&id).await.unwrap();
                    assert_eq!(owner.get_conversation_unchecked(&id).await.members().len(), 1);

                    // guest can no longer participate
                    guest_central
                        .decrypt_message(&id, commit.to_bytes().unwrap())
                        .await
                        .unwrap();
                    assert!(guest_central.get_conversation(&id).await.is_err());
                    assert!(guest.try_talk_to(&id, &owner).await.is_err());
                })
            })
            .await
        }

        #[apply(all_cred_cipher)]
        #[wasm_bindgen_test]
        async fn should_fail_when_invalid_external_sender(case: TestCase) {
            run_test_with_client_ids(
                case.clone(),
                ["owner", "guest", "ds", "attacker"],
                move |[owner, guest, ds, attacker]| {
                    Box::pin(async move {
                        let id = conversation_id();
                        // Delivery service key is used in the group..
                        let ds_signature_key = ds.client_signature_key(&case).await.as_slice().to_vec();
                        let mut cfg = case.cfg.clone();
                        owner
                            .context
                            .set_raw_external_senders(&mut cfg, vec![ds_signature_key])
                            .await
                            .unwrap();
                        owner
                            .context
                            .new_conversation(&id, case.credential_type, cfg)
                            .await
                            .unwrap();

                        owner.invite_all(&case, &id, [&guest]).await.unwrap();
                        assert_eq!(owner.get_conversation_unchecked(&id).await.members().len(), 2);

                        // now, attacker will try to remove guest from the group, and should fail
                        let to_remove = owner.index_of(&id, guest.get_client_id().await).await;
                        let sender_index = SenderExtensionIndex::new(1);

                        let (sc, ct) = (case.signature_scheme(), case.credential_type);
                        let cb = attacker.find_most_recent_credential_bundle(sc, ct).await.unwrap();
                        let group_id = GroupId::from_slice(&id[..]);
                        let epoch = owner.get_conversation_unchecked(&id).await.group.epoch();
                        let proposal =
                            ExternalProposal::new_remove(to_remove, group_id, epoch, &cb.signature_key, sender_index)
                                .unwrap();

                        let owner_decrypt = owner.context.decrypt_message(&id, proposal.to_bytes().unwrap()).await;

                        assert!(matches!(
                            owner_decrypt.unwrap_err(),
                            CryptoError::MlsError(MlsError::MlsMessageError(ProcessMessageError::ValidationError(
                                ValidationError::UnauthorizedExternalSender
                            )))
                        ));

                        let guest_decrypt = owner.context.decrypt_message(&id, proposal.to_bytes().unwrap()).await;
                        assert!(matches!(
                            guest_decrypt.unwrap_err(),
                            CryptoError::MlsError(MlsError::MlsMessageError(ProcessMessageError::ValidationError(
                                ValidationError::UnauthorizedExternalSender
                            )))
                        ));
                    })
                },
            )
            .await
        }

        #[apply(all_cred_cipher)]
        #[wasm_bindgen_test]
        async fn should_fail_when_wrong_signature_key(case: TestCase) {
            run_test_with_client_ids(case.clone(), ["owner", "guest", "ds"], move |[owner, guest, ds]| {
                Box::pin(async move {
                    let id = conversation_id();

                    // Here we're going to add the Delivery Service's (DS) signature key to the
                    // external senders list. However, for the purpose of this test, we will
                    // intentionally _not_ use that key when generating the remove proposal below.
                    let key = ds.client_signature_key(&case).await.as_slice().to_vec();
                    let mut cfg = case.cfg.clone();
                    owner
                        .context
                        .set_raw_external_senders(&mut cfg, vec![key.as_slice().to_vec()])
                        .await
                        .unwrap();
                    owner
                        .context
                        .new_conversation(&id, case.credential_type, cfg)
                        .await
                        .unwrap();

                    owner.invite_all(&case, &id, [&guest]).await.unwrap();
                    assert_eq!(owner.get_conversation_unchecked(&id).await.members().len(), 2);

                    let to_remove = owner.index_of(&id, guest.get_client_id().await).await;
                    let sender_index = SenderExtensionIndex::new(0);

                    let (sc, ct) = (case.signature_scheme(), case.credential_type);
                    // Intentionally use the guest's credential, and therefore the guest's signature
                    // key when generating the proposal so that the signature verification fails.
                    let cb = guest.find_most_recent_credential_bundle(sc, ct).await.unwrap();
                    let group_id = GroupId::from_slice(&id[..]);
                    let epoch = owner.get_conversation_unchecked(&id).await.group.epoch();
                    let proposal =
                        ExternalProposal::new_remove(to_remove, group_id, epoch, &cb.signature_key, sender_index)
                            .unwrap();

                    let owner_decrypt = owner.context.decrypt_message(&id, proposal.to_bytes().unwrap()).await;
                    assert!(matches!(
                        owner_decrypt.unwrap_err(),
                        CryptoError::MlsError(MlsError::MlsMessageError(ProcessMessageError::InvalidSignature))
                    ));

                    let guest_decrypt = owner.context.decrypt_message(&id, proposal.to_bytes().unwrap()).await;
                    assert!(matches!(
                        guest_decrypt.unwrap_err(),
                        CryptoError::MlsError(MlsError::MlsMessageError(ProcessMessageError::InvalidSignature))
                    ));
                })
            })
            .await
        }

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

                        let ds_signature_key = ds.client_signature_key(&case).await.as_slice().to_vec();
                        let mut cfg = case.cfg.clone();
                        alice_central
                            .set_raw_external_senders(&mut cfg, vec![ds_signature_key])
                            .await
                            .unwrap();

                        alice_central
                            .new_conversation(&id, case.credential_type, cfg)
                            .await
                            .unwrap();

                        alice.invite_all(&case, &id, [&bob]).await.unwrap();
                        assert_eq!(alice.get_conversation_unchecked(&id).await.members().len(), 2);

                        // Charlie joins through a Welcome and should get external_senders from Welcome
                        // message and not from configuration
                        let charlie_kp = charlie.rand_key_package(&case).await;
                        let MlsConversationCreationMessage { welcome, commit, .. } = alice_central
                            .add_members_to_conversation(&id, vec![charlie_kp])
                            .await
                            .unwrap();
                        alice_central.commit_accepted(&id).await.unwrap();
                        bob_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        // Purposely have a configuration without `external_senders`
                        charlie_central
                            .process_welcome_message(MlsMessageIn::from(welcome), case.custom_cfg())
                            .await
                            .unwrap();
                        assert_eq!(charlie.get_conversation_unchecked(&id).await.members().len(), 3);
                        assert!(charlie.try_talk_to(&id, &alice).await.is_ok());
                        assert!(charlie.try_talk_to(&id, &bob).await.is_ok());

                        // now, as e.g. a Delivery Service, let's create an external remove proposal
                        // and kick Bob out of the conversation
                        let to_remove = alice.index_of(&id, bob.get_client_id().await).await;
                        let sender_index = SenderExtensionIndex::new(0);
                        let (sc, ct) = (case.signature_scheme(), case.credential_type);
                        let cb = ds.find_most_recent_credential_bundle(sc, ct).await.unwrap();
                        let group_id = GroupId::from_slice(&id[..]);
                        let epoch = alice.get_conversation_unchecked(&id).await.group.epoch();
                        let proposal =
                            ExternalProposal::new_remove(to_remove, group_id, epoch, &cb.signature_key, sender_index)
                                .unwrap();

                        // joiner from Welcome should be able to verify the external remove proposal since
                        // it has fetched back the external_sender from Welcome
                        let charlie_can_verify_ext_proposal =
                            charlie_central.decrypt_message(&id, proposal.to_bytes().unwrap()).await;
                        assert!(charlie_can_verify_ext_proposal.is_ok());

                        alice_central
                            .decrypt_message(&id, proposal.to_bytes().unwrap())
                            .await
                            .unwrap();
                        bob_central
                            .decrypt_message(&id, proposal.to_bytes().unwrap())
                            .await
                            .unwrap();

                        let commit = charlie_central
                            .commit_pending_proposals(&id)
                            .await
                            .unwrap()
                            .unwrap()
                            .commit;
                        charlie_central.commit_accepted(&id).await.unwrap();
                        assert_eq!(charlie.get_conversation_unchecked(&id).await.members().len(), 2);

                        alice_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        assert_eq!(alice.get_conversation_unchecked(&id).await.members().len(), 2);
                        bob_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        assert!(alice.try_talk_to(&id, &charlie).await.is_ok());
                        assert!(alice.try_talk_to(&id, &bob).await.is_err());
                    })
                },
            )
            .await
        }

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

                        let ds_signature_key = ds.client_signature_key(&case).await.as_slice().to_vec();
                        let mut cfg = case.cfg.clone();
                        alice_central
                            .set_raw_external_senders(&mut cfg, vec![ds_signature_key])
                            .await
                            .unwrap();

                        alice_central
                            .new_conversation(&id, case.credential_type, cfg)
                            .await
                            .unwrap();

                        alice.invite_all(&case, &id, [&bob]).await.unwrap();
                        assert_eq!(alice.get_conversation_unchecked(&id).await.members().len(), 2);

                        // Charlie joins through an external commit and should get external_senders
                        // from PGS and not from configuration
                        let public_group_state = alice.get_group_info(&id).await;
                        let MlsConversationInitBundle { commit, .. } = charlie_central
                            .join_by_external_commit(public_group_state, case.custom_cfg(), case.credential_type)
                            .await
                            .unwrap();

                        // Purposely have a configuration without `external_senders`
                        charlie_central
                            .merge_pending_group_from_external_commit(&id)
                            .await
                            .unwrap();
                        alice_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        bob_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();

                        assert_eq!(charlie.get_conversation_unchecked(&id).await.members().len(), 3);
                        assert!(charlie.try_talk_to(&id, &alice).await.is_ok());
                        assert!(charlie.try_talk_to(&id, &bob).await.is_ok());

                        // now, as e.g. a Delivery Service, let's create an external remove proposal
                        // and kick Bob out of the conversation
                        let to_remove = alice.index_of(&id, bob.get_client_id().await).await;
                        let sender_index = SenderExtensionIndex::new(0);
                        let (sc, ct) = (case.signature_scheme(), case.credential_type);
                        let cb = ds.find_most_recent_credential_bundle(sc, ct).await.unwrap();
                        let group_id = GroupId::from_slice(&id[..]);
                        let epoch = alice.get_conversation_unchecked(&id).await.group.epoch();
                        let proposal =
                            ExternalProposal::new_remove(to_remove, group_id, epoch, &cb.signature_key, sender_index)
                                .unwrap();

                        // joiner from external commit should be able to verify the external remove proposal
                        // since it has fetched back the external_sender from external commit
                        let charlie_can_verify_ext_proposal =
                            charlie_central.decrypt_message(&id, proposal.to_bytes().unwrap()).await;
                        assert!(charlie_can_verify_ext_proposal.is_ok());

                        alice_central
                            .decrypt_message(&id, proposal.to_bytes().unwrap())
                            .await
                            .unwrap();
                        bob_central
                            .decrypt_message(&id, proposal.to_bytes().unwrap())
                            .await
                            .unwrap();

                        let commit = charlie_central
                            .commit_pending_proposals(&id)
                            .await
                            .unwrap()
                            .unwrap()
                            .commit;
                        charlie_central.commit_accepted(&id).await.unwrap();
                        assert_eq!(charlie.get_conversation_unchecked(&id).await.members().len(), 2);

                        alice_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        assert_eq!(alice.get_conversation_unchecked(&id).await.members().len(), 2);
                        bob_central
                            .decrypt_message(&id, commit.to_bytes().unwrap())
                            .await
                            .unwrap();
                        assert!(alice.try_talk_to(&id, &charlie).await.is_ok());
                        assert!(alice.try_talk_to(&id, &bob).await.is_err());
                    })
                },
            )
            .await
        }
    }
}