openmls 0.8.1

A Rust implementation of the Messaging Layer Security (MLS) protocol, as defined in RFC 9420.
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
//! This module contains validation functions for incoming messages
//! as defined in <https://github.com/openmls/openmls/wiki/Message-validation>

use std::collections::HashSet;

use openmls_traits::types::VerifiableCiphersuite;

use super::PublicGroup;
use crate::{
    binary_tree::array_representation::LeafNodeIndex,
    extensions::RequiredCapabilitiesExtension,
    framing::{
        mls_auth_content_in::VerifiableAuthenticatedContentIn, ContentType, ProtocolMessage,
        Sender, WireFormat,
    },
    group::{
        creation::LeafNodeLifetimePolicy,
        errors::{ExternalCommitValidationError, ProposalValidationError, ValidationError},
        past_secrets::MessageSecretsStore,
        proposal_store::ProposalQueue,
        GroupContextExtensionsProposalValidationError, Member,
    },
    messages::{
        proposals::{Proposal, ProposalOrRefType, ProposalType},
        Commit,
    },
    prelude::LibraryError,
    treesync::{
        errors::{LeafNodeValidationError, LifetimeError},
        LeafNode,
    },
};

#[cfg(feature = "extensions-draft-08")]
use crate::{
    group::errors::AppDataUpdateValidationError, messages::proposals::AppDataUpdateOperationType,
};

impl PublicGroup {
    // === Messages ===

    /// Checks the following semantic validation:
    ///  - ValSem002
    ///  - ValSem003
    ///  - [valn1307](https://validation.openmls.tech/#valn1307)
    pub(crate) fn validate_framing(
        &self,
        message: &ProtocolMessage,
    ) -> Result<(), ValidationError> {
        // ValSem002
        if message.group_id() != self.group_id() {
            return Err(ValidationError::WrongGroupId);
        }

        // ValSem003: Check boundaries for the epoch
        // We differentiate depending on the content type
        match message.content_type() {
            // For application messages we allow messages for older epochs as well
            ContentType::Application => {
                if message.epoch() > self.group_context().epoch() {
                    log::error!(
                        "Wrong Epoch: message.epoch() {} > {} self.group_context().epoch()",
                        message.epoch(),
                        self.group_context().epoch()
                    );
                    return Err(ValidationError::WrongEpoch);
                }
            }
            // For all other messages we only only accept the current epoch
            _ => {
                // https://validation.openmls.tech/#valn1307
                if message.epoch() != self.group_context().epoch() {
                    log::error!(
                        "Wrong Epoch: message.epoch() {} != {} self.group_context().epoch()",
                        message.epoch(),
                        self.group_context().epoch()
                    );
                    return Err(ValidationError::WrongEpoch);
                }
            }
        }

        Ok(())
    }

    /// Checks the following semantic validation:
    ///  - ValSem004
    ///  - ValSem005
    ///  - ValSem009
    pub(super) fn validate_verifiable_content(
        &self,
        verifiable_content: &VerifiableAuthenticatedContentIn,
        message_secrets_store_option: Option<&MessageSecretsStore>,
    ) -> Result<(), ValidationError> {
        // ValSem004
        let sender = verifiable_content.sender();
        if let Sender::Member(leaf_index) = sender {
            // If the sender is a member, it has to be in the tree, except if
            // it's an application message. Then it might be okay if it's in an
            // old secret tree instance.
            let is_in_secrets_store = if let Some(mss) = message_secrets_store_option {
                mss.epoch_has_leaf(verifiable_content.epoch(), *leaf_index)
            } else {
                false
            };
            if !self.treesync().is_leaf_in_tree(*leaf_index) && !is_in_secrets_store {
                return Err(ValidationError::UnknownMember);
            }
        }

        // ValSem005
        // Application messages must always be encrypted
        if verifiable_content.content_type() == ContentType::Application {
            if verifiable_content.wire_format() != WireFormat::PrivateMessage {
                return Err(ValidationError::UnencryptedApplicationMessage);
            } else if !verifiable_content.sender().is_member() {
                return Err(ValidationError::NonMemberApplicationMessage);
            }
        }

        // ValSem009
        if verifiable_content.content_type() == ContentType::Commit
            && verifiable_content.confirmation_tag().is_none()
        {
            return Err(ValidationError::MissingConfirmationTag);
        }

        Ok(())
    }

    // === Proposals ===

    /// Validate that all group members support the types of all proposals.
    /// Implements check [valn0311](https://validation.openmls.tech/#valn0311)
    pub(crate) fn validate_proposal_type_support(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ProposalValidationError> {
        // Collect signature keys of removed members s.t. we can skip them
        // when checking capabilities.
        let signature_keys: HashSet<_> = proposal_queue
            .remove_proposals()
            .filter_map(|p| {
                let removed_index = p.remove_proposal().removed();
                self.treesync()
                    .leaf(removed_index)
                    .map(|leaf_node| leaf_node.signature_key())
            })
            .collect();

        // Iterate over all leaf nodes except the removed ones
        let mut leaves = self
            .treesync()
            .full_leaves()
            .filter(|(_, leaf_node)| !signature_keys.contains(leaf_node.signature_key()));
        let Some((_, first_leaf)) = leaves.next() else {
            return Ok(());
        };

        // Initialize the capabilities intersection with the capabilities of the
        // first leaf node.
        let mut capabilities_intersection = first_leaf
            .capabilities()
            .proposals()
            .iter()
            .collect::<HashSet<_>>();
        // Iterate over the remaining leaf nodes and intersect their capabilities
        for (_, leaf_node) in leaves {
            let leaf_capabilities_set = leaf_node.capabilities().proposals().iter().collect();
            capabilities_intersection = capabilities_intersection
                .intersection(&leaf_capabilities_set)
                .cloned()
                .collect();
        }

        // Check that the types of all non-default proposals are supported by all members
        for proposal in proposal_queue.queued_proposals() {
            let proposal_type = proposal.proposal().proposal_type();
            if !proposal_type.is_default() && !capabilities_intersection.contains(&proposal_type) {
                return Err(ProposalValidationError::UnsupportedProposalType);
            }
        }
        Ok(())
    }

    /// Validate key uniqueness. This function implements the following checks:
    ///  - ValSem101: Add Proposal: Signature public key in proposals must be unique among proposals & members
    ///  - ValSem102: Add Proposal: Init key in proposals must be unique among proposals
    ///  - ValSem103: Add Proposal: Encryption key in proposals must be unique among proposals & members
    ///  - ValSem104: Add Proposal: Init key and encryption key must be different
    ///  - ValSem110: Update Proposal: Encryption key must be unique among proposals & members
    ///  - ValSem206: Commit: Path leaf node encryption key must be unique among proposals & members
    ///  - ValSem207: Commit: Path encryption keys must be unique among proposals & members
    ///  - [valn0111]: Verify that the following fields are unique among the members of the group: `signature_key`
    ///  - [valn0112]: Verify that the following fields are unique among the members of the group: `encryption_key`
    ///
    /// [valn0111]: https://validation.openmls.tech/#valn0111
    /// [valn0112]: https://validation.openmls.tech/#valn0112
    /// [valn1208]: https://validation.openmls.tech/#valn1208
    pub(crate) fn validate_key_uniqueness(
        &self,
        proposal_queue: &ProposalQueue,
        commit: Option<&Commit>,
    ) -> Result<(), ProposalValidationError> {
        let mut signature_key_set = HashSet::new();
        let mut init_key_set = HashSet::new();
        let mut encryption_key_set = HashSet::new();

        // Handle the exceptions needed for https://validation.openmls.tech/#valn0306
        let remove_proposals = HashSet::<LeafNodeIndex>::from_iter(
            proposal_queue
                .remove_proposals()
                .map(|remove_proposal| remove_proposal.remove_proposal().removed),
        );

        // Initialize the sets with the current members, filtered by the
        // remove proposals.
        for Member {
            index,
            encryption_key,
            signature_key,
            ..
        } in self.treesync().full_leaf_members()
        {
            if !remove_proposals.contains(&index) {
                signature_key_set.insert(signature_key);
                encryption_key_set.insert(encryption_key);
            }
        }

        // Collect signature keys from add proposals
        let signature_keys = proposal_queue.add_proposals().map(|add_proposal| {
            add_proposal
                .add_proposal()
                .key_package()
                .leaf_node()
                .signature_key()
                .as_slice()
                .to_vec()
        });

        // Collect encryption keys from add proposals, update proposals, the
        // commit leaf node and path keys
        let encryption_keys = proposal_queue
            .add_proposals()
            .map(|add_proposal| {
                add_proposal
                    .add_proposal()
                    .key_package()
                    .leaf_node()
                    .encryption_key()
                    .key()
                    .as_slice()
                    .to_vec()
            })
            .chain(proposal_queue.update_proposals().map(|update_proposal| {
                update_proposal
                    .update_proposal()
                    .leaf_node()
                    .encryption_key()
                    .key()
                    .as_slice()
                    .to_vec()
            }))
            .chain(commit.and_then(|commit| {
                commit
                    .path
                    .as_ref()
                    .map(|path| path.leaf_node().encryption_key().as_slice().to_vec())
            }))
            .chain(
                commit
                    .iter()
                    .filter_map(|commit| {
                        commit.path.as_ref().map(|path| {
                            path.nodes()
                                .iter()
                                .map(|node| node.encryption_key().as_slice().to_vec())
                        })
                    })
                    .flatten(),
            );

        // Collect init keys from add proposals
        let init_keys = proposal_queue.add_proposals().map(|add_proposal| {
            add_proposal
                .add_proposal()
                .key_package()
                .hpke_init_key()
                .as_slice()
                .to_vec()
        });

        // Validate uniqueness of signature keys
        //  - ValSem101
        //  - https://validation.openmls.tech/#valn0111
        //  - https://validation.openmls.tech/#valn0305
        //  - https://validation.openmls.tech/#valn0306
        for signature_key in signature_keys {
            if !signature_key_set.insert(signature_key) {
                return Err(ProposalValidationError::DuplicateSignatureKey);
            }
        }

        // Validate uniqueness of encryption keys
        //  - ValSem103
        //  - ValSem104
        //  - ValSem110
        //  - ValSem206
        //  - ValSem207
        //  - https://validation.openmls.tech/#valn0112
        //  - https://validation.openmls.tech/#valn1209
        for encryption_key in encryption_keys {
            if init_key_set.contains(&encryption_key) {
                return Err(ProposalValidationError::InitEncryptionKeyCollision);
            }
            if !encryption_key_set.insert(encryption_key) {
                return Err(ProposalValidationError::DuplicateEncryptionKey);
            }
        }

        // Validate uniqueness of init keys
        //  - ValSem102
        //  - ValSem104
        for init_key in init_keys {
            if encryption_key_set.contains(&init_key) {
                return Err(ProposalValidationError::InitEncryptionKeyCollision);
            }
            if !init_key_set.insert(init_key) {
                return Err(ProposalValidationError::DuplicateInitKey);
            }
        }

        Ok(())
    }

    /// Validate capabilities. This function implements the following checks:
    /// - ValSem106: Add Proposal: required capabilities
    /// - ValSem109: Update Proposal: required capabilities
    /// - [valn0113](https://validation.openmls.tech/#valn0113).
    pub(crate) fn validate_capabilities(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ProposalValidationError> {
        // ValSem106/ValSem109: Check the required capabilities of the add & update
        // proposals This includes the following checks:
        // - Are ciphersuite & version listed in the `Capabilities` Extension?
        // - If a `RequiredCapabilitiesExtension` is present in the group: Is
        //   this supported by the node?
        // - Check that all extensions are contained in the capabilities.
        // - Check that the capabilities contain the leaf node's credential
        //   type (https://validation.openmls.tech/#valn0113).
        // - Check that the credential type is supported by all members of the
        //   group.
        // - Check that the capabilities field of this LeafNode indicates
        //   support for all the credential types currently in use by other
        //   members.

        // Extract the leaf nodes from the add & update proposals and validate them
        proposal_queue
            .queued_proposals()
            .filter_map(|p| match p.proposal() {
                Proposal::Add(add_proposal) => Some(add_proposal.key_package().leaf_node()),
                Proposal::Update(update_proposal) => Some(update_proposal.leaf_node()),
                _ => None,
            })
            .try_for_each(|leaf_node| {
                self.validate_leaf_node_capabilities(leaf_node)
                    .map_err(|_| ProposalValidationError::InsufficientCapabilities)
            })
    }

    /// Validate Add proposals. This function implements the following checks:
    ///  - ValSem105: Add Proposal: Ciphersuite & protocol version must match the group
    pub(crate) fn validate_add_proposals(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ProposalValidationError> {
        let add_proposals = proposal_queue.add_proposals();

        // We do the key package validation checks here inline
        // https://validation.openmls.tech/#valn0501
        for add_proposal in add_proposals {
            // ValSem105: Check if ciphersuite and version of the group are correct:
            // https://validation.openmls.tech/#valn0201
            if add_proposal.add_proposal().key_package().ciphersuite() != self.ciphersuite()
                || add_proposal.add_proposal().key_package().protocol_version() != self.version()
            {
                return Err(ProposalValidationError::InvalidAddProposalCiphersuiteOrVersion);
            }

            // Check that the leaf node of the added key package supports all extensions in the group
            // context.
            // https://validation.openmls.tech/#valn0502
            let added_leaf_supports_all_group_context_extensions =
                self.group_context().extensions().iter().all(|extension| {
                    add_proposal
                        .add_proposal()
                        .key_package
                        .leaf_node()
                        .supports_extension(&extension.extension_type())
                });
            if !added_leaf_supports_all_group_context_extensions {
                return Err(ProposalValidationError::InsufficientCapabilities);
            }

            // https://validation.openmls.tech/#valn0202
            self.validate_leaf_node(add_proposal.add_proposal().key_package().leaf_node())?;
        }
        Ok(())
    }

    /// Validate Remove proposals. This function implements the following checks:
    ///  - ValSem107: Remove Proposal: Removed member must be unique among proposals
    ///  - ValSem108: Remove Proposal: Removed member must be an existing group member
    pub(crate) fn validate_remove_proposals(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ProposalValidationError> {
        let updates_set: HashSet<_> = proposal_queue
            .update_proposals()
            .map(|proposal| {
                if let Sender::Member(index) = proposal.sender() {
                    Ok(*index)
                } else {
                    Err(ProposalValidationError::UpdateFromNonMember)
                }
            })
            .collect::<Result<_, _>>()?;

        let remove_proposals = proposal_queue.remove_proposals();

        let mut removes_set = HashSet::new();

        // https://validation.openmls.tech/#valn0701
        for remove_proposal in remove_proposals {
            let removed = remove_proposal.remove_proposal().removed();
            // The node has to be a leaf in the tree
            // ValSem108
            if !self.treesync().is_leaf_in_tree(removed) {
                return Err(ProposalValidationError::UnknownMemberRemoval);
            }

            // ValSem107
            // https://validation.openmls.tech/#valn0304
            if !removes_set.insert(removed) {
                return Err(ProposalValidationError::DuplicateMemberRemoval);
            }
            if updates_set.contains(&removed) {
                return Err(ProposalValidationError::DuplicateMemberRemoval);
            }

            // removed node can not be blank
            if self.treesync().leaf(removed).is_none() {
                return Err(ProposalValidationError::UnknownMemberRemoval);
            }
        }

        Ok(())
    }

    /// Validate Update proposals. This function implements the following checks:
    ///  - ValSem111: Update Proposal: The sender of a full Commit must not include own update proposals
    ///  - ValSem112: Update Proposal: The sender of a standalone update proposal must be of type member
    ///
    /// TODO: #133 This validation must be updated according to Sec. 13.2
    pub(crate) fn validate_update_proposals(
        &self,
        proposal_queue: &ProposalQueue,
        committer: LeafNodeIndex,
    ) -> Result<(), ProposalValidationError> {
        // Check the update proposals from the proposal queue first
        let update_proposals = proposal_queue.update_proposals();

        for update_proposal in update_proposals {
            // ValSem112
            // The sender of a standalone update proposal must be of type member
            if let Sender::Member(sender_index) = update_proposal.sender() {
                // ValSem111
                // https://validation.openmls.tech/#valn0302
                // The sender of a full Commit must not include own update proposals
                if committer == *sender_index {
                    return Err(ProposalValidationError::CommitterIncludedOwnUpdate);
                }
            } else {
                return Err(ProposalValidationError::UpdateFromNonMember);
            }

            // https://validation.openmls.tech/#valn0601
            self.validate_leaf_node(update_proposal.update_proposal().leaf_node())?;

            // Check that the leaf node in the update proposal supports all group context extensions
            // https://validation.openmls.tech/#valn0602
            let leaf_node_supports_group_context_extensions =
                self.group_context().extensions().iter().all(|extension| {
                    update_proposal
                        .update_proposal()
                        .leaf_node()
                        .supports_extension(&extension.extension_type())
                });

            if !leaf_node_supports_group_context_extensions {
                return Err(ProposalValidationError::LeafNodeValidation(
                    LeafNodeValidationError::UnsupportedExtensions,
                ));
            }
        }
        Ok(())
    }

    /// Validate PreSharedKey proposals.
    ///
    /// This method implements the following checks:
    ///
    /// * ValSem401: The nonce of a PreSharedKeyID must have length KDF.Nh.
    /// * ValSem402: PSK in proposal must be of type Resumption (with usage Application) or External.
    pub(crate) fn validate_pre_shared_key_proposals(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ProposalValidationError> {
        for proposal in proposal_queue.psk_proposals() {
            let psk_id = proposal.psk_proposal().clone().into_psk_id();

            // ValSem401
            // ValSem402
            // https://validation.openmls.tech/#valn0803
            psk_id.validate_in_proposal(self.ciphersuite())?;
        }

        Ok(())
    }

    /// Validate constraints on an external commit. This function implements the following checks:
    ///  - ValSem240: External Commit, inline Proposals: There MUST be at least one ExternalInit proposal.
    ///  - ValSem241: External Commit, inline Proposals: There MUST be at most one ExternalInit proposal.
    ///  - ValSem242: External Commit must only cover inline proposal in allowlist (ExternalInit, Remove, PreSharedKey)
    pub(crate) fn validate_external_commit(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), ExternalCommitValidationError> {
        // [valn0401](https://validation.openmls.tech/#valn0401)
        let count_external_init_proposals = proposal_queue
            .filtered_by_type(ProposalType::ExternalInit)
            .count();
        if count_external_init_proposals == 0 {
            // ValSem240: External Commit, inline Proposals: There MUST be at least one ExternalInit proposal.
            return Err(ExternalCommitValidationError::NoExternalInitProposals);
        } else if count_external_init_proposals > 1 {
            // ValSem241: External Commit, inline Proposals: There MUST be at most one ExternalInit proposal.
            return Err(ExternalCommitValidationError::MultipleExternalInitProposals);
        }

        // ValSem242: External Commit must only cover inline proposal in allowlist (ExternalInit, Remove, PreSharedKey)
        // [valn0404](https://validation.openmls.tech/#valn0404)
        let contains_denied_proposal = proposal_queue.queued_proposals().any(|p| {
            let is_inline = p.proposal_or_ref_type() == ProposalOrRefType::Proposal;
            let is_allowed_type = matches!(
                p.proposal(),
                Proposal::ExternalInit(_)
                    | Proposal::Remove(_)
                    | Proposal::PreSharedKey(_)
                    | Proposal::Custom(_)
            );
            is_inline && !is_allowed_type
        });
        if contains_denied_proposal {
            return Err(ExternalCommitValidationError::InvalidInlineProposals);
        }

        // If a Remove proposal is present,
        // the credential in the LeafNode MUST present a set of
        // identifiers that is acceptable to the application for
        // the removed participant.
        // This MUST be checked by the application.

        Ok(())
    }

    /// Returns a [`LeafNodeValidationError`] if an [`ExtensionType`]
    /// in `extensions` is not supported by a leaf in this tree.
    /// Implements check [valn1001](https://validation.openmls.tech/#valn1001).
    pub(crate) fn validate_group_context_extensions_proposal(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), GroupContextExtensionsProposalValidationError> {
        let iter = proposal_queue.filtered_by_type(ProposalType::GroupContextExtensions);

        for (i, queued_proposal) in iter.enumerate() {
            // There must at most be one group context extionsion proposal. Return an error if there are more
            if i > 0 {
                return Err(GroupContextExtensionsProposalValidationError::TooManyGCEProposals);
            }

            match queued_proposal.proposal() {
                Proposal::GroupContextExtensions(extensions) => {
                    let required_capabilities_in_proposal =
                        extensions.extensions().required_capabilities();

                    // Prepare the empty required capabilities in case there is no
                    // RequiredCapabilitiesExtension in the proposal
                    let default_required_capabilities =
                        RequiredCapabilitiesExtension::new(&[], &[], &[]);

                    // If there is a RequiredCapabilitiesExtension in the proposal, validate it and
                    // use that. Otherwise, use the empty default one.
                    let required_capabilities = match required_capabilities_in_proposal {
                        Some(required_capabilities_new) => {
                            // If a group context extensions proposal updates the required capabilities, we
                            // need to check that these are satisfied for all existing members of the group.
                            self.check_extension_support(required_capabilities_new.extension_types()).map_err(|_| GroupContextExtensionsProposalValidationError::RequiredExtensionNotSupportedByAllMembers)?;
                            required_capabilities_new
                        }
                        None => &default_required_capabilities,
                    };

                    // Make sure that all other extensions are known to be supported, by checking
                    // that they are default extensions or included in the required capabilities.
                    let all_extensions_are_in_required_capabilities: bool = extensions
                        .extensions()
                        .iter()
                        .map(|ext| ext.extension_type())
                        .all(|ext_type| {
                            ext_type.is_default()
                                || required_capabilities.requires_extension_type_support(ext_type)
                        });

                    if !all_extensions_are_in_required_capabilities {
                        return Err(GroupContextExtensionsProposalValidationError::ExtensionNotInRequiredCapabilities);
                    }
                }
                _ => {
                    return Err(GroupContextExtensionsProposalValidationError::LibraryError(
                        LibraryError::custom(
                            "found non-gce proposal when filtered for gce proposals",
                        ),
                    ))
                }
            }
        }

        Ok(())
    }

    /// Returns an [`AppDataUpdateValidationError`] if:
    ///   - An [`AppDataUpdateProposal`] appears before a [`GroupContextExtensionProposal`]
    ///   - The [`GroupContextExtensionProposal`] updates the [`AppDataDictionary`] when the
    ///     required capabilities include AppDataUpdate proposal type
    ///   - For any [`ComponentId`], the list of [`AppDataUpdateProposal`]s includes both Updates
    ///     and Removes
    ///   - For any [`ComponentId`], the list of [`AppDataUpdateProposal`]s includes more than one
    ///     Remove
    #[cfg(feature = "extensions-draft-08")]
    pub(crate) fn validate_app_data_update_proposals_and_group_context(
        &self,
        proposal_queue: &ProposalQueue,
    ) -> Result<(), AppDataUpdateValidationError> {
        let no_app_data_updates = proposal_queue.app_data_update_proposals().next().is_none();
        if no_app_data_updates {
            return Ok(());
        }

        // retrieve the GroupContextExtensions proposal, if available
        let group_context_extension_proposal = proposal_queue
            .filtered_by_type(ProposalType::GroupContextExtensions)
            .filter_map(|queued_proposal| match queued_proposal.proposal() {
                Proposal::GroupContextExtensions(p) => Some(p),
                _ => None,
            })
            .next();

        // check ordering
        // return an error if an AppDataUpdate appears before a GroupContextExtensions proposal
        //
        // From the draft:
        //
        // A commit can contain a GroupContextExtensions proposal which modifies
        // GroupContext extensions other than app_data_dictionary, and can be
        // followed by zero or more AppDataUpdate proposals.
        //
        // https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions#section-4.7-7
        //
        // Note that it is a bit unclear if this is really needed; we already require that default
        // proposals are processed first.
        if proposal_queue
            .queued_proposals()
            .map(|proposal| proposal.proposal().proposal_type())
            .skip_while(|proposal_type| *proposal_type != ProposalType::AppDataUpdate)
            .any(|proposal_type| proposal_type == ProposalType::GroupContextExtensions)
        {
            return Err(AppDataUpdateValidationError::IncorrectOrder);
        }

        if let Some(group_context_extension) = group_context_extension_proposal {
            let required_capabilities_contain_app_data_update_proposal = group_context_extension
                .extensions()
                .required_capabilities()
                .map(|required_capabilities| {
                    required_capabilities
                        .proposal_types()
                        .contains(&ProposalType::AppDataUpdate)
                })
                .unwrap_or(false);

            // From https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions#section-4.7-6:
            // When an MLS group contains the AppDataUpdate proposal type in the proposal_types list in
            // the group's required_capabilities extension, a GroupContextExtensions proposal MUST NOT
            // add, remove, or modify the app_data_dictionary GroupContext extension. In other words,
            // when every member of the group supports the AppDataUpdate proposal, a
            // GroupContextExtensions proposal could be sent to update some other extension(s), but the
            // app_data_dictionary GroupContext extension, if it exists, is left as it was.
            if required_capabilities_contain_app_data_update_proposal
                && group_context_extension.extensions().app_data_dictionary()
                    != self.group_context().extensions().app_data_dictionary()
            {
                return Err(AppDataUpdateValidationError::CannotUpdateDictionaryDirectly);
            }
        }

        // From the draft:
        //
        // A proposal list is invalid if it includes multiple AppDataUpdate proposals that remove state for the same component_id, or proposals that both update and remove state for the same component_id.
        //
        // https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions#section-4.7-4
        // NOTE: We depend on the proposals being sorted by component id first and by
        // type second - for a given ID, removes come first. The sorting is stable and
        // won't mess with the ordering of updates within a component.
        // This is ensured in ProposalQueue::app_data_update_proposals.
        let mut latest = None;
        for proposal in proposal_queue.app_data_update_proposals() {
            let proposal = &proposal.app_data_update_proposal;
            let component_id = proposal.component_id();
            let operation_type = proposal.operation().operation_type();

            if latest == Some(component_id) {
                let app_data_update_validation_error = match operation_type {
                    AppDataUpdateOperationType::Update => {
                        AppDataUpdateValidationError::CombinedRemoveAndUpdateOperations
                    }
                    AppDataUpdateOperationType::Remove => {
                        AppDataUpdateValidationError::CombinedRemoveAndUpdateOperations
                    }
                };

                return Err(app_data_update_validation_error);
            }

            if proposal.operation().operation_type() == AppDataUpdateOperationType::Remove {
                // From the draft:
                //
                // An AppDataUpdate proposal is invalid if [...] it specifies the removal of
                // state for a component_id that has no state present.
                //
                // https://datatracker.ietf.org/doc/html/draft-ietf-mls-extensions#section-4.7-4
                let Some(gce) = group_context_extension_proposal else {
                    // extension gets implicitly created in the group context, so absence is not an
                    // error condition
                    return Ok(());
                };
                let Some(app_data_dict) = gce.extensions().app_data_dictionary() else {
                    // extension gets implicitly created in the group context, so absence is not an
                    // error condition
                    return Ok(());
                };

                if app_data_dict.dictionary().get(&component_id).is_none() {
                    return Err(AppDataUpdateValidationError::CannotRemoveNonexistentComponent);
                }

                latest = Some(component_id)
            }
        }

        Ok(())
    }

    fn validate_leaf_node_capabilities(
        &self,
        leaf_node: &LeafNode,
    ) -> Result<(), LeafNodeValidationError> {
        // Check that the data in the leaf node is self-consistent
        // Check that the capabilities contain the leaf node's credential
        // type (https://validation.openmls.tech/#valn0113)
        // Check that all extension types are valid in leaf node
        // (https://validation.openmls.tech/#valn1601)
        leaf_node.validate_locally()?;

        // Check if the ciphersuite and the version of the group are
        // supported.
        let capabilities = leaf_node.capabilities();
        if !capabilities.contains_ciphersuite(VerifiableCiphersuite::from(self.ciphersuite()))
            || !capabilities.contains_version(self.version())
        {
            return Err(LeafNodeValidationError::CiphersuiteNotInCapabilities);
        }

        // If there is a required capabilities extension, check if that one
        // is supported (https://validation.openmls.tech/#valn0103).
        if let Some(required_capabilities) =
            self.group_context().extensions().required_capabilities()
        {
            // Check if all required capabilities are supported.
            capabilities.supports_required_capabilities(required_capabilities)?;
        }

        // Check that the credential type is supported by all members of the group (https://validation.openmls.tech/#valn0104).
        if !self.treesync().full_leaves().all(|(_, node)| {
            node.capabilities()
                .contains_credential(leaf_node.credential().credential_type())
        }) {
            return Err(LeafNodeValidationError::UnsupportedCredentials);
        }

        // Check that the capabilities field of this LeafNode indicates
        // support for all the credential types currently in use by other
        // members (https://validation.openmls.tech/#valn0104).
        if !self
            .treesync()
            .full_leaves()
            .all(|(_, node)| capabilities.contains_credential(node.credential().credential_type()))
        {
            return Err(LeafNodeValidationError::UnsupportedCredentials);
        }

        Ok(())
    }

    /// Validate a leaf node.
    ///
    /// This always validates the lifetime.
    pub(crate) fn validate_leaf_node(
        &self,
        leaf_node: &crate::treesync::LeafNode,
    ) -> Result<(), LeafNodeValidationError> {
        // Call the validation function and validate the lifetime
        self.validate_leaf_node_inner(leaf_node, LeafNodeLifetimePolicy::Verify)
    }

    /// Validate a leaf node.
    ///
    /// This may skip checking the lifetime when validating a ratchet tree.
    pub(crate) fn validate_leaf_node_inner(
        &self,
        leaf_node: &crate::treesync::LeafNode,
        validate_lifetimes: LeafNodeLifetimePolicy,
    ) -> Result<(), LeafNodeValidationError> {
        // https://validation.openmls.tech/#valn0103
        // https://validation.openmls.tech/#valn0104
        // https://validation.openmls.tech/#valn0107
        self.validate_leaf_node_capabilities(leaf_node)?;

        // https://validation.openmls.tech/#valn0105 is done when sending

        // https://validation.openmls.tech/#valn0106
        //
        // Only leaf nodes in key packages contain lifetimes, so this will return None for other
        // cases. Therefore we only check the lifetimes for leaf nodes in key packages.
        //
        // We may want to check these in ratchet trees as well.
        // However, this may lead to errors when leaf nodes don't get updated
        // after being added to the tree. RFC 9420 recommends checking the lifetime
        // but acknowledges already that this may cause issues.
        // https://www.rfc-editor.org/rfc/rfc9420.html#section-7.3-4.5.1
        // See #1810 for more background.
        // We therefore check the lifetime by default, but skip it if ...
        //
        // Some KATs use key packages that are expired by now. In order to run these tests, we
        // provide a way to turn off this check.
        if matches!(validate_lifetimes, LeafNodeLifetimePolicy::Verify)
            && !crate::skip_validation::is_disabled::leaf_node_lifetime()
        {
            if let Some(lifetime) = leaf_node.life_time() {
                if !lifetime.is_valid() {
                    log::warn!(
                        "offending lifetime: {lifetime:?} for leaf node with {credential:?}",
                        credential = leaf_node.credential()
                    );
                    return Err(LeafNodeValidationError::Lifetime(LifetimeError::NotCurrent));
                }
            }
        }

        // These are done at the caller and we can't do them here:
        //
        // https://validation.openmls.tech/#valn0108
        // https://validation.openmls.tech/#valn0109
        // https://validation.openmls.tech/#valn0110

        // These are done in validate_key_uniqueness, which is called in the context of changing
        // this group:
        //
        // https://validation.openmls.tech/#valn0111
        // https://validation.openmls.tech/#valn0112

        Ok(())
    }

    /// Returns a [`LeafNodeValidationError`] if an [`ExtensionType`]
    /// in `extensions` is not supported by a leaf in this tree.
    pub(crate) fn check_extension_support(
        &self,
        extensions: &[crate::extensions::ExtensionType],
    ) -> Result<(), LeafNodeValidationError> {
        for (_, leaf) in self.treesync().full_leaves() {
            leaf.check_extension_support(extensions)?;
        }
        Ok(())
    }
}