openmls 0.4.1

This is a WIP Rust implementation of the Messaging Layer Security (MLS) protocol based on draft 12+.
Documentation
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! This module tests the validation of commits as defined in
//! https://openmls.tech/book/message_validation.html#commit-message-validation

use openmls_rust_crypto::OpenMlsRustCrypto;
use openmls_traits::key_store::OpenMlsKeyStore;
use openmls_traits::types::Ciphersuite;
use tls_codec::{Deserialize, Serialize};

use rstest::*;
use rstest_reuse::{self, *};

use crate::group::*;
use crate::{
    ciphersuite::signable::{Signable, Verifiable},
    credentials::*,
    framing::*,
    group::errors::*,
    messages::proposals::ProposalOrRef,
    treesync::errors::ApplyUpdatePathError,
};

use super::utils::{generate_credential_bundle, generate_key_package_bundle};

struct CommitValidationTestSetup {
    alice_group: MlsGroup,
    bob_group: MlsGroup,
}

// Validation test setup
fn validation_test_setup(
    wire_format_policy: WireFormatPolicy,
    ciphersuite: Ciphersuite,
    backend: &impl OpenMlsCryptoProvider,
) -> CommitValidationTestSetup {
    let group_id = GroupId::from_slice(b"Test Group");

    // Generate credential bundles
    let alice_credential = generate_credential_bundle(
        "Alice".into(),
        CredentialType::Basic,
        ciphersuite.signature_algorithm(),
        backend,
    )
    .expect("An unexpected error occurred.");

    let bob_credential = generate_credential_bundle(
        "Bob".into(),
        CredentialType::Basic,
        ciphersuite.signature_algorithm(),
        backend,
    )
    .expect("An unexpected error occurred.");

    // Generate KeyPackages
    let alice_key_package =
        generate_key_package_bundle(&[ciphersuite], &alice_credential, vec![], backend)
            .expect("An unexpected error occurred.");

    let bob_key_package =
        generate_key_package_bundle(&[ciphersuite], &bob_credential, vec![], backend)
            .expect("An unexpected error occurred.");

    // Define the MlsGroup configuration

    let mls_group_config = MlsGroupConfig::builder()
        .wire_format_policy(wire_format_policy)
        .build();

    // === Alice creates a group ===
    let mut alice_group = MlsGroup::new(
        backend,
        &mls_group_config,
        group_id,
        alice_key_package
            .hash_ref(backend.crypto())
            .expect("Could not hash KeyPackage.")
            .as_slice(),
    )
    .expect("An unexpected error occurred.");

    let (_message, welcome) = alice_group
        .add_members(backend, &[bob_key_package])
        .expect("error adding Bob to group");

    alice_group
        .merge_pending_commit()
        .expect("error merging pending commit");

    let bob_group = MlsGroup::new_from_welcome(
        backend,
        &mls_group_config,
        welcome,
        Some(alice_group.export_ratchet_tree()),
    )
    .expect("error creating group from welcome");

    CommitValidationTestSetup {
        alice_group,
        bob_group,
    }
}

// ValSem200: Commit must not cover inline self Remove proposal
#[apply(ciphersuites_and_backends)]
fn test_valsem200(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ciphersuite, backend);

    let alice_hash_ref = *alice_group
        .key_package_ref()
        .expect("Couldn't find key package ref.");

    // Since Alice won't commit to her own removal directly, we have to create
    // proposal and commit independently and then insert the proposal into the
    // commit manually.
    let serialized_proposal_message = alice_group
        .propose_remove_member(backend, &alice_hash_ref)
        .expect("error creating commit")
        .tls_serialize_detached()
        .expect("serialization error");

    // Let's get the proposal out of the message.
    let proposal_message =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_proposal_message.as_slice())
            .expect("Could not deserialize message.");

    let proposal = if let MlsPlaintextContentType::Proposal(proposal) = proposal_message.content() {
        proposal.clone()
    } else {
        panic!("Unexpected content type.");
    };

    // We have to clear the pending proposals so Alice doesn't try to commit to
    // her own remove.
    alice_group.clear_pending_proposals();

    // Now let's stick it in the commit.
    let serialized_message = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let mut plaintext = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_message.as_slice())
        .expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = plaintext.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };

    commit_content
        .proposals
        .push(ProposalOrRef::Proposal(proposal));

    plaintext.set_content(MlsPlaintextContentType::Commit(commit_content));

    let alice_credential_bundle = backend
        .key_store()
        .read(
            &alice_group
                .credential()
                .expect("error retrieving credential")
                .signature_key()
                .tls_serialize_detached()
                .expect("error serializing credential"),
        )
        .expect("error retrieving credential bundle");

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // We have to re-sign, since we changed the content.
    let mut signed_plaintext: MlsPlaintext = plaintext
        .payload()
        .clone()
        .sign(backend, &alice_credential_bundle)
        .expect("Error signing modified payload.");

    // Set old confirmation tag
    signed_plaintext.set_confirmation_tag(
        original_plaintext
            .confirmation_tag()
            .expect("no confirmation tag on original message")
            .clone(),
    );

    let membership_key = alice_group.group().message_secrets().membership_key();

    signed_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(signed_plaintext, None);

    // Have Bob try to process the commit.
    let message_in = MlsMessageIn::from(verifiable_plaintext);

    let unverified_message = bob_group
        .parse_message(message_in, backend)
        .expect("Could not parse message.");

    let err: UnverifiedMessageError = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite self remove.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::AttemptedSelfRemoval)
    );

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}

// ValSem201: Path must be present, if Commit contains Removes or Updates
#[apply(ciphersuites_and_backends)]
fn test_valsem201(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    let wire_format_policy = PURE_PLAINTEXT_WIRE_FORMAT_POLICY;
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(wire_format_policy, ciphersuite, backend);

    // This case is simple: Have Alice generate a self-updating commit, clear
    // the pending commit and then create a remove commit.

    // Start with the update
    // Create the self-update
    let serialized_update = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("error serializing plaintext");

    let mut update = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
        .expect("Could not deserialize message.");

    // The self-update currently contains an update proposal. This should change
    // with a future spec-change issue, but for now, we have to remove it
    // manually to create a completely empty commit.
    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = update.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };

    commit_content.proposals = vec![].into();

    update.set_content(MlsPlaintextContentType::Commit(commit_content));

    let serialized_update = update
        .tls_serialize_detached()
        .expect("error serializing plaintext");

    let update_message_in = erase_path(backend, &serialized_update, &alice_group);

    let unverified_message = bob_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite missing path.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::RequiredPathNotFound)
    );

    let original_update_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_update_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");

    // Now do the remove
    // Clear the pending commit.
    alice_group.clear_pending_commit();

    // Before we can test the commit, we first have to add Charlie so we can
    // actually remove someone and have someone else process the commit.
    let charlie_credential = generate_credential_bundle(
        "Charlie".into(),
        CredentialType::Basic,
        ciphersuite.signature_algorithm(),
        backend,
    )
    .expect("An unexpected error occurred.");

    // Generate KeyPackages
    let charlie_key_package =
        generate_key_package_bundle(&[ciphersuite], &charlie_credential, vec![], backend)
            .expect("An unexpected error occurred.");

    let (_msg_out, welcome) = alice_group
        .add_members(backend, &[charlie_key_package])
        .expect("error adding charlie");

    alice_group
        .merge_pending_commit()
        .expect("error merging pending commit");

    let mls_group_config = MlsGroupConfig::builder()
        .wire_format_policy(wire_format_policy)
        .build();

    let mut charlie_group = MlsGroup::new_from_welcome(
        backend,
        &mls_group_config,
        welcome,
        Some(alice_group.export_ratchet_tree()),
    )
    .expect("Error creating group.");

    // Create the remove.
    let serialized_remove = alice_group
        .remove_members(
            backend,
            &[*bob_group
                .key_package_ref()
                .expect("error retrieving kp ref")],
        )
        .expect("Error creating remove")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let remove_message_in = erase_path(backend, &serialized_remove, &alice_group);

    // Have Charlie process everything
    let unverified_message = charlie_group
        .parse_message(remove_message_in, backend)
        .expect("Could not parse message.");

    let err = charlie_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite missing path.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::RequiredPathNotFound)
    );

    let original_remove_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_remove.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = charlie_group
        .parse_message(MlsMessageIn::from(original_remove_plaintext), backend)
        .expect("Could not parse message.");
    if let ProcessedMessage::StagedCommitMessage(staged_commit) = charlie_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.")
    {
        charlie_group
            .merge_staged_commit(*staged_commit)
            .expect("error merging staged commit");
    } else {
        panic!("Expected a staged commit.");
    };

    // Make sure that alice' and charlies states match up.
    alice_group
        .merge_pending_commit()
        .expect("error merging pending commit");

    // Create a commit covering an update proposal.
    // Have charlie create an update proposal and then let Alice commit to it.
    let charlie_update_proposal = charlie_group
        .propose_self_update(backend, None)
        .expect("error creating self-update proposal");

    let unverified_message = alice_group
        .parse_message(charlie_update_proposal.into(), backend)
        .expect("error parsing proposal");
    alice_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("error processing proposal");

    let serialized_update = alice_group
        .commit_to_pending_proposals(backend)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    // Erase the path.
    let update_message_in = erase_path(backend, &serialized_update, &alice_group);

    // Have charlie process it.
    let unverified_message = charlie_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = charlie_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite missing path.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::RequiredPathNotFound)
    );

    let original_update_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = charlie_group
        .parse_message(MlsMessageIn::from(original_update_plaintext), backend)
        .expect("Could not parse message.");
    charlie_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}

fn erase_path(
    backend: &impl OpenMlsCryptoProvider,
    mut pt: &[u8],
    alice_group: &MlsGroup,
) -> MlsMessageIn {
    let mut plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut pt).expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = plaintext.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };
    commit_content.path = None;

    plaintext.set_content(MlsPlaintextContentType::Commit(commit_content));

    let alice_credential_bundle = backend
        .key_store()
        .read(
            &alice_group
                .credential()
                .expect("error retrieving credential")
                .signature_key()
                .tls_serialize_detached()
                .expect("error serializing credential"),
        )
        .expect("error retrieving credential bundle");

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // We have to re-sign, since we changed the content.
    let mut signed_plaintext: MlsPlaintext = plaintext
        .payload()
        .clone()
        .sign(backend, &alice_credential_bundle)
        .expect("Error signing modified payload.");

    // Set old confirmation tag
    signed_plaintext.set_confirmation_tag(
        original_plaintext
            .confirmation_tag()
            .expect("no confirmation tag on original message")
            .clone(),
    );

    let membership_key = alice_group.group().message_secrets().membership_key();

    signed_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(signed_plaintext, None);

    MlsMessageIn::from(verifiable_plaintext)
}

// ValSem202: Path must be the right length
#[apply(ciphersuites_and_backends)]
fn test_valsem202(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ciphersuite, backend);

    // Have Alice generate a self-updating commit, remove a node from the path,
    // re-sign and have Bob process it.

    // Create the self-update
    let serialized_update = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let mut plaintext = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
        .expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = plaintext.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };
    if let Some(ref mut path) = commit_content.path {
        path.pop();
    };

    plaintext.set_content(MlsPlaintextContentType::Commit(commit_content));

    let alice_credential_bundle = backend
        .key_store()
        .read(
            &alice_group
                .credential()
                .expect("error retrieving credential")
                .signature_key()
                .tls_serialize_detached()
                .expect("error serializing credential"),
        )
        .expect("error retrieving credential bundle");

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // We have to re-sign, since we changed the content.
    let mut signed_plaintext: MlsPlaintext = plaintext
        .payload()
        .clone()
        .sign(backend, &alice_credential_bundle)
        .expect("Error signing modified payload.");

    // Set old confirmation tag
    signed_plaintext.set_confirmation_tag(
        original_plaintext
            .confirmation_tag()
            .expect("no confirmation tag on original message")
            .clone(),
    );

    let membership_key = alice_group.group().message_secrets().membership_key();

    signed_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(signed_plaintext, None);

    let update_message_in = MlsMessageIn::from(verifiable_plaintext);

    let unverified_message = bob_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite path length mismatch.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::UpdatePathError(
            ApplyUpdatePathError::PathLengthMismatch
        ))
    );

    let original_update_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_update_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}

// ValSem203: Path secrets must decrypt correctly
#[apply(ciphersuites_and_backends)]
fn test_valsem203(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ciphersuite, backend);

    // Have Alice generate a self-updating commit, scramble some ciphertexts and
    // have Bob process the resulting commit.

    // Create the self-update
    let serialized_update = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let mut plaintext = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
        .expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = plaintext.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };

    // This should cause decryption to fail.
    if let Some(ref mut path) = commit_content.path {
        path.flip_eps_bytes();
    };

    plaintext.set_content(MlsPlaintextContentType::Commit(commit_content));

    let alice_credential_bundle = backend
        .key_store()
        .read(
            &alice_group
                .credential()
                .expect("error retrieving credential")
                .signature_key()
                .tls_serialize_detached()
                .expect("error serializing credential"),
        )
        .expect("error retrieving credential bundle");

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // We have to re-sign, since we changed the content.
    let mut signed_plaintext: MlsPlaintext = plaintext
        .payload()
        .clone()
        .sign(backend, &alice_credential_bundle)
        .expect("Error signing modified payload.");

    // Set old confirmation tag
    signed_plaintext.set_confirmation_tag(
        original_plaintext
            .confirmation_tag()
            .expect("no confirmation tag on original message")
            .clone(),
    );

    let membership_key = alice_group.group().message_secrets().membership_key();

    signed_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(signed_plaintext, None);

    let update_message_in = MlsMessageIn::from(verifiable_plaintext);

    let unverified_message = bob_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite scrambled ciphertexts.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::UpdatePathError(
            ApplyUpdatePathError::UnableToDecrypt
        ))
    );

    let original_update_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_update_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}

// ValSem204: Public keys from Path must be verified and match the private keys from the direct path
#[apply(ciphersuites_and_backends)]
fn test_valsem204(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ciphersuite, backend);

    // Have Alice generate a self-updating commit, flip the last byte of one of
    // the public keys in the path and have Bob process the commit.

    // Create the self-update
    let serialized_update = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let mut plaintext = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
        .expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut commit_content = if let MlsPlaintextContentType::Commit(commit) = plaintext.content() {
        commit.clone()
    } else {
        panic!("Unexpected content type.");
    };

    // This should cause decryption to fail.
    if let Some(ref mut path) = commit_content.path {
        path.flip_node_bytes();
    };

    plaintext.set_content(MlsPlaintextContentType::Commit(commit_content));

    let alice_credential_bundle = backend
        .key_store()
        .read(
            &alice_group
                .credential()
                .expect("error retrieving credential")
                .signature_key()
                .tls_serialize_detached()
                .expect("error serializing credential"),
        )
        .expect("error retrieving credential bundle");

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // We have to re-sign, since we changed the content.
    let mut signed_plaintext: MlsPlaintext = plaintext
        .payload()
        .clone()
        .sign(backend, &alice_credential_bundle)
        .expect("Error signing modified payload.");

    // Set old confirmation tag
    signed_plaintext.set_confirmation_tag(
        original_plaintext
            .confirmation_tag()
            .expect("no confirmation tag on original message")
            .clone(),
    );

    let membership_key = alice_group.group().message_secrets().membership_key();

    signed_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(signed_plaintext, None);

    let update_message_in = MlsMessageIn::from(verifiable_plaintext);

    let unverified_message = bob_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite modified public key in path.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::UpdatePathError(
            ApplyUpdatePathError::PathMismatch
        ))
    );

    let original_update_plaintext =
        VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
            .expect("Could not deserialize message.");

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_update_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}

// ValSem205: Confirmation tag must be successfully verified
#[apply(ciphersuites_and_backends)]
fn test_valsem205(ciphersuite: Ciphersuite, backend: &impl OpenMlsCryptoProvider) {
    // Test with MlsPlaintext
    let CommitValidationTestSetup {
        mut alice_group,
        mut bob_group,
    } = validation_test_setup(PURE_PLAINTEXT_WIRE_FORMAT_POLICY, ciphersuite, backend);

    // Have Alice generate a self-updating commit, flip the last bit of the
    // confirmation tag and have Bob process the commit.

    // Create the self-update
    let serialized_update = alice_group
        .self_update(backend, None)
        .expect("Error creating self-update")
        .tls_serialize_detached()
        .expect("Could not serialize message.");

    let mut plaintext = VerifiableMlsPlaintext::tls_deserialize(&mut serialized_update.as_slice())
        .expect("Could not deserialize message.");

    // Keep the original plaintext for positive test later.
    let original_plaintext = plaintext.clone();

    let mut new_confirmation_tag = plaintext
        .confirmation_tag()
        .expect("no confirmation tag on commit")
        .clone();

    new_confirmation_tag.0.flip_last_byte();

    plaintext.set_confirmation_tag(Some(new_confirmation_tag));

    // Since the membership tag covers the confirmation tag, we have to refresh it.
    let membership_key = alice_group.group().message_secrets().membership_key();

    let serialized_context = alice_group
        .export_group_context()
        .tls_serialize_detached()
        .expect("error serializing context");
    plaintext.set_context(serialized_context.clone());

    // Verify the plaintext so we have access to the membership tag computation
    // function.
    let mut verified_plaintext: MlsPlaintext = plaintext
        .verify(
            backend,
            alice_group
                .credential()
                .expect("error getting credential from group"),
        )
        .expect("error verifying plaintext");

    verified_plaintext
        .set_membership_tag(backend, &serialized_context, membership_key)
        .expect("error refreshing membership tag");

    let verifiable_plaintext: VerifiableMlsPlaintext =
        VerifiableMlsPlaintext::from_plaintext(verified_plaintext, None);

    let update_message_in = MlsMessageIn::from(verifiable_plaintext);

    let unverified_message = bob_group
        .parse_message(update_message_in, backend)
        .expect("Could not parse message.");

    let err = bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect_err("Could process unverified message despite confirmation tag mismatch.");

    assert_eq!(
        err,
        UnverifiedMessageError::InvalidCommit(StageCommitError::ConfirmationTagMismatch)
    );

    // Positive case
    let unverified_message = bob_group
        .parse_message(MlsMessageIn::from(original_plaintext), backend)
        .expect("Could not parse message.");
    bob_group
        .process_unverified_message(unverified_message, None, backend)
        .expect("Unexpected error.");
}