mls_rs/group/
message_processor.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// Copyright by contributors to this project.
3// SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5#[cfg(all(
6    feature = "by_ref_proposal",
7    feature = "custom_proposal",
8    feature = "self_remove_proposal"
9))]
10use super::SelfRemoveProposal;
11use super::{
12    commit_sender,
13    confirmation_tag::ConfirmationTag,
14    framing::{
15        ApplicationData, Content, ContentType, MlsMessage, MlsMessagePayload, PublicMessage, Sender,
16    },
17    message_signature::AuthenticatedContent,
18    mls_rules::{CommitDirection, MlsRules},
19    proposal_filter::ProposalBundle,
20    state::GroupState,
21    transcript_hash::InterimTranscriptHash,
22    transcript_hashes, validate_group_info_member, GroupContext, GroupInfo, ReInitProposal,
23    RemoveProposal, Welcome,
24};
25use crate::{
26    client::MlsError,
27    key_package::validate_key_package_properties,
28    time::MlsTime,
29    tree_kem::{
30        leaf_node_validator::{LeafNodeValidator, ValidationContext},
31        node::LeafIndex,
32        path_secret::PathSecret,
33        validate_update_path, TreeKemPrivate, TreeKemPublic, ValidatedUpdatePath,
34    },
35    CipherSuiteProvider, KeyPackage,
36};
37use itertools::Itertools;
38use mls_rs_codec::{MlsDecode, MlsEncode, MlsSize};
39
40use alloc::boxed::Box;
41use alloc::vec::Vec;
42use core::fmt::{self, Debug};
43use mls_rs_core::{
44    identity::{IdentityProvider, MemberValidationContext},
45    protocol_version::ProtocolVersion,
46    psk::PreSharedKeyStorage,
47};
48
49#[cfg(feature = "by_ref_proposal")]
50use super::proposal_ref::ProposalRef;
51
52#[cfg(not(feature = "by_ref_proposal"))]
53use crate::group::proposal_cache::resolve_for_commit;
54
55use super::proposal::Proposal;
56use super::proposal_filter::ProposalInfo;
57
58#[cfg(feature = "private_message")]
59use crate::group::framing::PrivateMessage;
60
61#[derive(Debug)]
62pub(crate) struct ProvisionalState {
63    pub(crate) public_tree: TreeKemPublic,
64    pub(crate) applied_proposals: ProposalBundle,
65    pub(crate) group_context: GroupContext,
66    pub(crate) external_init_index: Option<LeafIndex>,
67    pub(crate) indexes_of_added_kpkgs: Vec<LeafIndex>,
68    pub(crate) unused_proposals: Vec<ProposalInfo<Proposal>>,
69}
70
71//By default, the path field of a Commit MUST be populated. The path field MAY be omitted if
72//(a) it covers at least one proposal and (b) none of the proposals covered by the Commit are
73//of "path required" types. A proposal type requires a path if it cannot change the group
74//membership in a way that requires the forward secrecy and post-compromise security guarantees
75//that an UpdatePath provides. The only proposal types defined in this document that do not
76//require a path are:
77
78// add
79// psk
80// reinit
81pub(crate) fn path_update_required(proposals: &ProposalBundle) -> bool {
82    let res = !proposals.external_init_proposals().is_empty();
83
84    #[cfg(feature = "by_ref_proposal")]
85    let res = res || !proposals.update_proposals().is_empty();
86
87    #[cfg(all(
88        feature = "by_ref_proposal",
89        feature = "custom_proposal",
90        feature = "self_remove_proposal"
91    ))]
92    let res = res || !proposals.self_removes.is_empty();
93
94    res || proposals.length() == 0
95        || proposals.group_context_extensions_proposal().is_some()
96        || !proposals.remove_proposals().is_empty()
97}
98
99#[cfg_attr(
100    all(feature = "ffi", not(test)),
101    safer_ffi_gen::ffi_type(clone, opaque)
102)]
103#[derive(Clone, Debug, PartialEq, MlsSize, MlsEncode, MlsDecode)]
104#[non_exhaustive]
105pub struct NewEpoch {
106    pub epoch: u64,
107    pub prior_state: GroupState,
108    pub applied_proposals: Vec<ProposalInfo<Proposal>>,
109    pub unused_proposals: Vec<ProposalInfo<Proposal>>,
110}
111
112impl NewEpoch {
113    pub(crate) fn new(prior_state: GroupState, provisional_state: &ProvisionalState) -> NewEpoch {
114        NewEpoch {
115            epoch: provisional_state.group_context.epoch,
116            prior_state,
117            unused_proposals: provisional_state.unused_proposals.clone(),
118            applied_proposals: provisional_state
119                .applied_proposals
120                .clone()
121                .into_proposals()
122                .collect_vec(),
123        }
124    }
125}
126
127#[cfg(all(feature = "ffi", not(test)))]
128#[safer_ffi_gen::safer_ffi_gen]
129impl NewEpoch {
130    pub fn epoch(&self) -> u64 {
131        self.epoch
132    }
133
134    pub fn prior_state(&self) -> &GroupState {
135        &self.prior_state
136    }
137
138    pub fn applied_proposals(&self) -> &[ProposalInfo<Proposal>] {
139        &self.applied_proposals
140    }
141
142    pub fn unused_proposals(&self) -> &[ProposalInfo<Proposal>] {
143        &self.unused_proposals
144    }
145}
146
147#[cfg_attr(
148    all(feature = "ffi", not(test)),
149    safer_ffi_gen::ffi_type(clone, opaque)
150)]
151#[derive(Clone, Debug, PartialEq)]
152pub enum CommitEffect {
153    NewEpoch(Box<NewEpoch>),
154    Removed {
155        new_epoch: Box<NewEpoch>,
156        remover: Sender,
157    },
158    ReInit(ProposalInfo<ReInitProposal>),
159}
160
161impl MlsSize for CommitEffect {
162    fn mls_encoded_len(&self) -> usize {
163        0u8.mls_encoded_len()
164            + match self {
165                Self::NewEpoch(e) => e.mls_encoded_len(),
166                Self::Removed { new_epoch, remover } => {
167                    new_epoch.mls_encoded_len() + remover.mls_encoded_len()
168                }
169                Self::ReInit(r) => r.mls_encoded_len(),
170            }
171    }
172}
173
174impl MlsEncode for CommitEffect {
175    fn mls_encode(&self, writer: &mut Vec<u8>) -> Result<(), mls_rs_codec::Error> {
176        match self {
177            Self::NewEpoch(e) => {
178                1u8.mls_encode(writer)?;
179                e.mls_encode(writer)?;
180            }
181            Self::Removed { new_epoch, remover } => {
182                2u8.mls_encode(writer)?;
183                new_epoch.mls_encode(writer)?;
184                remover.mls_encode(writer)?;
185            }
186            Self::ReInit(r) => {
187                3u8.mls_encode(writer)?;
188                r.mls_encode(writer)?;
189            }
190        }
191
192        Ok(())
193    }
194}
195
196impl MlsDecode for CommitEffect {
197    fn mls_decode(reader: &mut &[u8]) -> Result<Self, mls_rs_codec::Error> {
198        match u8::mls_decode(reader)? {
199            1u8 => Ok(Self::NewEpoch(NewEpoch::mls_decode(reader)?.into())),
200            2u8 => Ok(Self::Removed {
201                new_epoch: NewEpoch::mls_decode(reader)?.into(),
202                remover: Sender::mls_decode(reader)?,
203            }),
204            3u8 => Ok(Self::ReInit(ProposalInfo::mls_decode(reader)?)),
205            _ => Err(mls_rs_codec::Error::UnsupportedEnumDiscriminant),
206        }
207    }
208}
209
210#[cfg_attr(
211    all(feature = "ffi", not(test)),
212    safer_ffi_gen::ffi_type(clone, opaque)
213)]
214#[derive(Debug, Clone)]
215#[allow(clippy::large_enum_variant)]
216/// An event generated as a result of processing a message for a group with
217/// [`Group::process_incoming_message`](crate::group::Group::process_incoming_message).
218pub enum ReceivedMessage {
219    /// An application message was decrypted.
220    ApplicationMessage(ApplicationMessageDescription),
221    /// A new commit was processed creating a new group state.
222    Commit(CommitMessageDescription),
223    /// A proposal was received.
224    Proposal(ProposalMessageDescription),
225    /// Validated GroupInfo object
226    GroupInfo(GroupInfo),
227    /// Validated welcome message
228    Welcome,
229    /// Validated key package
230    KeyPackage(KeyPackage),
231}
232
233impl TryFrom<ApplicationMessageDescription> for ReceivedMessage {
234    type Error = MlsError;
235
236    fn try_from(value: ApplicationMessageDescription) -> Result<Self, Self::Error> {
237        Ok(ReceivedMessage::ApplicationMessage(value))
238    }
239}
240
241impl From<CommitMessageDescription> for ReceivedMessage {
242    fn from(value: CommitMessageDescription) -> Self {
243        ReceivedMessage::Commit(value)
244    }
245}
246
247impl From<ProposalMessageDescription> for ReceivedMessage {
248    fn from(value: ProposalMessageDescription) -> Self {
249        ReceivedMessage::Proposal(value)
250    }
251}
252
253impl From<GroupInfo> for ReceivedMessage {
254    fn from(value: GroupInfo) -> Self {
255        ReceivedMessage::GroupInfo(value)
256    }
257}
258
259impl From<Welcome> for ReceivedMessage {
260    fn from(_: Welcome) -> Self {
261        ReceivedMessage::Welcome
262    }
263}
264
265impl From<KeyPackage> for ReceivedMessage {
266    fn from(value: KeyPackage) -> Self {
267        ReceivedMessage::KeyPackage(value)
268    }
269}
270
271#[cfg_attr(
272    all(feature = "ffi", not(test)),
273    safer_ffi_gen::ffi_type(clone, opaque)
274)]
275#[derive(Clone, PartialEq, Eq)]
276/// Description of a MLS application message.
277pub struct ApplicationMessageDescription {
278    /// Index of this user in the group state.
279    pub sender_index: u32,
280    /// Received application data.
281    data: ApplicationData,
282    /// Plaintext authenticated data in the received MLS packet.
283    pub authenticated_data: Vec<u8>,
284}
285
286impl Debug for ApplicationMessageDescription {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.debug_struct("ApplicationMessageDescription")
289            .field("sender_index", &self.sender_index)
290            .field("data", &self.data)
291            .field(
292                "authenticated_data",
293                &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
294            )
295            .finish()
296    }
297}
298
299#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::safer_ffi_gen)]
300impl ApplicationMessageDescription {
301    pub fn data(&self) -> &[u8] {
302        self.data.as_bytes()
303    }
304}
305
306#[cfg_attr(
307    all(feature = "ffi", not(test)),
308    safer_ffi_gen::ffi_type(clone, opaque)
309)]
310#[derive(Clone, PartialEq, MlsSize, MlsEncode, MlsDecode)]
311#[non_exhaustive]
312/// Description of a processed MLS commit message.
313pub struct CommitMessageDescription {
314    /// True if this is the result of an external commit.
315    pub is_external: bool,
316    /// The index in the group state of the member who performed this commit.
317    pub committer: u32,
318    /// A full description of group state changes as a result of this commit.
319    pub effect: CommitEffect,
320    /// Plaintext authenticated data in the received MLS packet.
321    #[mls_codec(with = "mls_rs_codec::byte_vec")]
322    pub authenticated_data: Vec<u8>,
323}
324
325impl Debug for CommitMessageDescription {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.debug_struct("CommitMessageDescription")
328            .field("is_external", &self.is_external)
329            .field("committer", &self.committer)
330            .field("effect", &self.effect)
331            .field(
332                "authenticated_data",
333                &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
334            )
335            .finish()
336    }
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq, MlsEncode, MlsDecode, MlsSize)]
340#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
341#[repr(u8)]
342/// Proposal sender type.
343pub enum ProposalSender {
344    /// A current member of the group by index in the group state.
345    Member(u32) = 1u8,
346    /// An external entity by index within an
347    /// [`ExternalSendersExt`](crate::extension::built_in::ExternalSendersExt).
348    External(u32) = 2u8,
349    /// A new member proposing their addition to the group.
350    NewMember = 3u8,
351}
352
353impl TryFrom<Sender> for ProposalSender {
354    type Error = MlsError;
355
356    fn try_from(value: Sender) -> Result<Self, Self::Error> {
357        match value {
358            Sender::Member(index) => Ok(Self::Member(index)),
359            #[cfg(feature = "by_ref_proposal")]
360            Sender::External(index) => Ok(Self::External(index)),
361            #[cfg(feature = "by_ref_proposal")]
362            Sender::NewMemberProposal => Ok(Self::NewMember),
363            Sender::NewMemberCommit => Err(MlsError::InvalidSender),
364        }
365    }
366}
367
368#[cfg(feature = "by_ref_proposal")]
369#[cfg_attr(
370    all(feature = "ffi", not(test)),
371    safer_ffi_gen::ffi_type(clone, opaque)
372)]
373#[derive(Clone, MlsEncode, MlsDecode, MlsSize, PartialEq)]
374#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
375#[non_exhaustive]
376/// Description of a processed MLS proposal message.
377pub struct ProposalMessageDescription {
378    /// Sender of the proposal.
379    pub sender: ProposalSender,
380    /// Proposal content.
381    pub proposal: Proposal,
382    /// Plaintext authenticated data in the received MLS packet.
383    pub authenticated_data: Vec<u8>,
384    /// Proposal reference.
385    pub proposal_ref: ProposalRef,
386}
387
388#[cfg(feature = "by_ref_proposal")]
389impl Debug for ProposalMessageDescription {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        f.debug_struct("ProposalMessageDescription")
392            .field("sender", &self.sender)
393            .field("proposal", &self.proposal)
394            .field(
395                "authenticated_data",
396                &mls_rs_core::debug::pretty_bytes(&self.authenticated_data),
397            )
398            .field("proposal_ref", &self.proposal_ref)
399            .finish()
400    }
401}
402
403#[cfg(feature = "by_ref_proposal")]
404#[derive(MlsSize, MlsEncode, MlsDecode)]
405pub struct CachedProposal {
406    pub(crate) proposal: Proposal,
407    pub(crate) proposal_ref: ProposalRef,
408    pub(crate) sender: Sender,
409}
410
411#[cfg(feature = "by_ref_proposal")]
412impl CachedProposal {
413    /// Deserialize the proposal
414    pub fn from_bytes(bytes: &[u8]) -> Result<Self, MlsError> {
415        Ok(Self::mls_decode(&mut &*bytes)?)
416    }
417
418    /// Serialize the proposal
419    pub fn to_bytes(&self) -> Result<Vec<u8>, MlsError> {
420        Ok(self.mls_encode_to_vec()?)
421    }
422}
423
424#[cfg(feature = "by_ref_proposal")]
425impl ProposalMessageDescription {
426    pub fn cached_proposal(self) -> CachedProposal {
427        let sender = match self.sender {
428            ProposalSender::Member(i) => Sender::Member(i),
429            ProposalSender::External(i) => Sender::External(i),
430            ProposalSender::NewMember => Sender::NewMemberProposal,
431        };
432
433        CachedProposal {
434            proposal: self.proposal,
435            proposal_ref: self.proposal_ref,
436            sender,
437        }
438    }
439
440    pub fn proposal_ref(&self) -> Vec<u8> {
441        self.proposal_ref.to_vec()
442    }
443
444    #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
445    pub(crate) async fn new<C: CipherSuiteProvider>(
446        cs: &C,
447        content: &AuthenticatedContent,
448        proposal: Proposal,
449    ) -> Result<Self, MlsError> {
450        Ok(ProposalMessageDescription {
451            authenticated_data: content.content.authenticated_data.clone(),
452            proposal,
453            sender: content.content.sender.try_into()?,
454            proposal_ref: ProposalRef::from_content(cs, content).await?,
455        })
456    }
457}
458
459#[cfg(not(feature = "by_ref_proposal"))]
460#[cfg_attr(
461    all(feature = "ffi", not(test)),
462    safer_ffi_gen::ffi_type(clone, opaque)
463)]
464#[derive(Debug, Clone)]
465/// Description of a processed MLS proposal message.
466pub struct ProposalMessageDescription {}
467
468#[allow(clippy::large_enum_variant)]
469pub(crate) enum EventOrContent<E> {
470    #[cfg_attr(
471        not(all(feature = "private_message", feature = "external_client")),
472        allow(dead_code)
473    )]
474    Event(E),
475    Content(AuthenticatedContent),
476}
477
478#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
479#[cfg_attr(all(target_arch = "wasm32", mls_build_async), maybe_async::must_be_async(?Send))]
480#[cfg_attr(
481    all(not(target_arch = "wasm32"), mls_build_async),
482    maybe_async::must_be_async
483)]
484pub(crate) trait MessageProcessor: Send + Sync {
485    type OutputType: TryFrom<ApplicationMessageDescription, Error = MlsError>
486        + From<CommitMessageDescription>
487        + From<ProposalMessageDescription>
488        + From<GroupInfo>
489        + From<Welcome>
490        + From<KeyPackage>
491        + Send;
492
493    type MlsRules: MlsRules;
494    type IdentityProvider: IdentityProvider;
495    type CipherSuiteProvider: CipherSuiteProvider;
496    type PreSharedKeyStorage: PreSharedKeyStorage;
497
498    async fn process_incoming_message(
499        &mut self,
500        message: MlsMessage,
501        #[cfg(feature = "by_ref_proposal")] cache_proposal: bool,
502    ) -> Result<Self::OutputType, MlsError> {
503        self.process_incoming_message_with_time(
504            message,
505            #[cfg(feature = "by_ref_proposal")]
506            cache_proposal,
507            None,
508        )
509        .await
510    }
511
512    async fn process_incoming_message_with_time(
513        &mut self,
514        message: MlsMessage,
515        #[cfg(feature = "by_ref_proposal")] cache_proposal: bool,
516        time_sent: Option<MlsTime>,
517    ) -> Result<Self::OutputType, MlsError> {
518        let event_or_content = self.get_event_from_incoming_message(message).await?;
519
520        self.process_event_or_content(
521            event_or_content,
522            #[cfg(feature = "by_ref_proposal")]
523            cache_proposal,
524            time_sent,
525        )
526        .await
527    }
528
529    async fn get_event_from_incoming_message(
530        &mut self,
531        message: MlsMessage,
532    ) -> Result<EventOrContent<Self::OutputType>, MlsError> {
533        self.check_metadata(&message)?;
534
535        match message.payload {
536            MlsMessagePayload::Plain(plaintext) => {
537                self.verify_plaintext_authentication(plaintext).await
538            }
539            #[cfg(feature = "private_message")]
540            MlsMessagePayload::Cipher(cipher_text) => self.process_ciphertext(&cipher_text).await,
541            MlsMessagePayload::GroupInfo(group_info) => {
542                validate_group_info_member(
543                    self.group_state(),
544                    message.version,
545                    &group_info,
546                    self.cipher_suite_provider(),
547                )
548                .await?;
549
550                Ok(EventOrContent::Event(group_info.into()))
551            }
552            MlsMessagePayload::Welcome(welcome) => {
553                self.validate_welcome(&welcome, message.version)?;
554
555                Ok(EventOrContent::Event(welcome.into()))
556            }
557            MlsMessagePayload::KeyPackage(key_package) => {
558                self.validate_key_package(&key_package, message.version)
559                    .await?;
560
561                Ok(EventOrContent::Event(key_package.into()))
562            }
563        }
564    }
565
566    async fn process_event_or_content(
567        &mut self,
568        event_or_content: EventOrContent<Self::OutputType>,
569        #[cfg(feature = "by_ref_proposal")] cache_proposal: bool,
570        time_sent: Option<MlsTime>,
571    ) -> Result<Self::OutputType, MlsError> {
572        let msg = match event_or_content {
573            EventOrContent::Event(event) => event,
574            EventOrContent::Content(content) => {
575                self.process_auth_content(
576                    content,
577                    #[cfg(feature = "by_ref_proposal")]
578                    cache_proposal,
579                    time_sent,
580                )
581                .await?
582            }
583        };
584
585        Ok(msg)
586    }
587
588    async fn process_auth_content(
589        &mut self,
590        auth_content: AuthenticatedContent,
591        #[cfg(feature = "by_ref_proposal")] cache_proposal: bool,
592        time_sent: Option<MlsTime>,
593    ) -> Result<Self::OutputType, MlsError> {
594        let event = match auth_content.content.content {
595            #[cfg(feature = "private_message")]
596            Content::Application(data) => {
597                let authenticated_data = auth_content.content.authenticated_data;
598                let sender = auth_content.content.sender;
599
600                self.process_application_message(data, sender, authenticated_data)
601                    .and_then(Self::OutputType::try_from)
602            }
603            Content::Commit(_) => self
604                .process_commit(auth_content, time_sent)
605                .await
606                .map(Self::OutputType::from),
607            #[cfg(feature = "by_ref_proposal")]
608            Content::Proposal(ref proposal) => self
609                .process_proposal(&auth_content, proposal, cache_proposal)
610                .await
611                .map(Self::OutputType::from),
612        }?;
613
614        Ok(event)
615    }
616
617    #[cfg(feature = "private_message")]
618    fn process_application_message(
619        &self,
620        data: ApplicationData,
621        sender: Sender,
622        authenticated_data: Vec<u8>,
623    ) -> Result<ApplicationMessageDescription, MlsError> {
624        let Sender::Member(sender_index) = sender else {
625            return Err(MlsError::InvalidSender);
626        };
627
628        Ok(ApplicationMessageDescription {
629            authenticated_data,
630            sender_index,
631            data,
632        })
633    }
634
635    #[cfg(feature = "by_ref_proposal")]
636    #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
637    async fn process_proposal(
638        &mut self,
639        auth_content: &AuthenticatedContent,
640        proposal: &Proposal,
641        cache_proposal: bool,
642    ) -> Result<ProposalMessageDescription, MlsError> {
643        let proposal = ProposalMessageDescription::new(
644            self.cipher_suite_provider(),
645            auth_content,
646            proposal.clone(),
647        )
648        .await?;
649
650        let group_state = self.group_state_mut();
651
652        if cache_proposal {
653            group_state.proposals.insert(
654                proposal.proposal_ref.clone(),
655                proposal.proposal.clone(),
656                auth_content.content.sender,
657            );
658        }
659
660        Ok(proposal)
661    }
662
663    async fn process_commit(
664        &mut self,
665        auth_content: AuthenticatedContent,
666        time_sent: Option<MlsTime>,
667    ) -> Result<CommitMessageDescription, MlsError> {
668        if self.group_state().pending_reinit.is_some() {
669            return Err(MlsError::GroupUsedAfterReInit);
670        }
671
672        // Update the new GroupContext's confirmed and interim transcript hashes using the new Commit.
673        let (interim_transcript_hash, confirmed_transcript_hash) = transcript_hashes(
674            self.cipher_suite_provider(),
675            &self.group_state().interim_transcript_hash,
676            &auth_content,
677        )
678        .await?;
679
680        #[cfg(any(feature = "private_message", feature = "by_ref_proposal"))]
681        let commit = match auth_content.content.content {
682            Content::Commit(commit) => Ok(commit),
683            _ => Err(MlsError::UnexpectedMessageType),
684        }?;
685
686        #[cfg(not(any(feature = "private_message", feature = "by_ref_proposal")))]
687        let Content::Commit(commit) = auth_content.content.content;
688
689        let group_state = self.group_state();
690        let id_provider = self.identity_provider();
691
692        #[cfg(feature = "by_ref_proposal")]
693        let proposals = group_state
694            .proposals
695            .resolve_for_commit(auth_content.content.sender, commit.proposals)?;
696
697        #[cfg(not(feature = "by_ref_proposal"))]
698        let proposals = resolve_for_commit(auth_content.content.sender, commit.proposals)?;
699
700        let mut provisional_state = group_state
701            .apply_resolved(
702                auth_content.content.sender,
703                proposals,
704                commit.path.as_ref().map(|path| &path.leaf_node),
705                &id_provider,
706                self.cipher_suite_provider(),
707                &self.psk_storage(),
708                &self.mls_rules(),
709                time_sent,
710                CommitDirection::Receive,
711            )
712            .await?;
713
714        let sender = commit_sender(&auth_content.content.sender, &provisional_state)?;
715
716        //Verify that the path value is populated if the proposals vector contains any Update
717        // or Remove proposals, or if it's empty. Otherwise, the path value MAY be omitted.
718        if path_update_required(&provisional_state.applied_proposals) && commit.path.is_none() {
719            return Err(MlsError::CommitMissingPath);
720        }
721
722        let self_removed = self.removal_proposal(&provisional_state);
723        #[cfg(all(
724            feature = "by_ref_proposal",
725            feature = "custom_proposal",
726            feature = "self_remove_proposal"
727        ))]
728        let self_removed_by_self = self.self_removal_proposal(&provisional_state);
729
730        let is_self_removed = self_removed.is_some();
731        #[cfg(all(
732            feature = "by_ref_proposal",
733            feature = "custom_proposal",
734            feature = "self_remove_proposal"
735        ))]
736        let is_self_removed = is_self_removed || self_removed_by_self.is_some();
737
738        let update_path = match commit.path {
739            Some(update_path) => Some(
740                validate_update_path(
741                    &self.identity_provider(),
742                    self.cipher_suite_provider(),
743                    update_path,
744                    &provisional_state,
745                    sender,
746                    time_sent,
747                    &group_state.context,
748                )
749                .await?,
750            ),
751            None => None,
752        };
753
754        let commit_effect =
755            if let Some(reinit) = provisional_state.applied_proposals.reinitializations.pop() {
756                self.group_state_mut().pending_reinit = Some(reinit.proposal.clone());
757                CommitEffect::ReInit(reinit)
758            } else if let Some(remove_proposal) = self_removed {
759                let new_epoch = NewEpoch::new(self.group_state().clone(), &provisional_state);
760                CommitEffect::Removed {
761                    remover: remove_proposal.sender,
762                    new_epoch: Box::new(new_epoch),
763                }
764            } else {
765                CommitEffect::NewEpoch(Box::new(NewEpoch::new(
766                    self.group_state().clone(),
767                    &provisional_state,
768                )))
769            };
770
771        #[cfg(all(
772            feature = "by_ref_proposal",
773            feature = "custom_proposal",
774            feature = "self_remove_proposal"
775        ))]
776        let commit_effect = if let Some(self_remove_proposal) = self_removed_by_self {
777            let new_epoch = NewEpoch::new(self.group_state().clone(), &provisional_state);
778            CommitEffect::Removed {
779                remover: self_remove_proposal.sender,
780                new_epoch: Box::new(new_epoch),
781            }
782        } else {
783            commit_effect
784        };
785
786        let new_secrets = match update_path {
787            Some(update_path) if !is_self_removed => {
788                self.apply_update_path(sender, &update_path, &mut provisional_state)
789                    .await
790            }
791            _ => Ok(None),
792        }?;
793
794        // Update the transcript hash to get the new context.
795        provisional_state.group_context.confirmed_transcript_hash = confirmed_transcript_hash;
796
797        // Update the parent hashes in the new context
798        provisional_state
799            .public_tree
800            .update_hashes(&[sender], self.cipher_suite_provider())
801            .await?;
802
803        // Update the tree hash in the new context
804        provisional_state.group_context.tree_hash = provisional_state
805            .public_tree
806            .tree_hash(self.cipher_suite_provider())
807            .await?;
808
809        if let Some(confirmation_tag) = &auth_content.auth.confirmation_tag {
810            if !is_self_removed {
811                // Update the key schedule to calculate new private keys
812                self.update_key_schedule(
813                    new_secrets,
814                    interim_transcript_hash,
815                    confirmation_tag,
816                    provisional_state,
817                )
818                .await?;
819            }
820            Ok(CommitMessageDescription {
821                is_external: matches!(auth_content.content.sender, Sender::NewMemberCommit),
822                authenticated_data: auth_content.content.authenticated_data,
823                committer: *sender,
824                effect: commit_effect,
825            })
826        } else {
827            Err(MlsError::InvalidConfirmationTag)
828        }
829    }
830
831    fn group_state(&self) -> &GroupState;
832    fn group_state_mut(&mut self) -> &mut GroupState;
833    fn mls_rules(&self) -> Self::MlsRules;
834    fn identity_provider(&self) -> Self::IdentityProvider;
835    fn cipher_suite_provider(&self) -> &Self::CipherSuiteProvider;
836    fn psk_storage(&self) -> Self::PreSharedKeyStorage;
837
838    fn removal_proposal(
839        &self,
840        provisional_state: &ProvisionalState,
841    ) -> Option<ProposalInfo<RemoveProposal>>;
842
843    #[cfg(all(
844        feature = "by_ref_proposal",
845        feature = "custom_proposal",
846        feature = "self_remove_proposal"
847    ))]
848    #[cfg_attr(feature = "ffi", safer_ffi_gen::safer_ffi_gen_ignore)]
849    fn self_removal_proposal(
850        &self,
851        provisional_state: &ProvisionalState,
852    ) -> Option<ProposalInfo<SelfRemoveProposal>>;
853
854    #[cfg(feature = "private_message")]
855    fn min_epoch_available(&self) -> Option<u64>;
856
857    fn check_metadata(&self, message: &MlsMessage) -> Result<(), MlsError> {
858        let context = &self.group_state().context;
859
860        if message.version != context.protocol_version {
861            return Err(MlsError::ProtocolVersionMismatch);
862        }
863
864        if let Some((group_id, epoch, content_type)) = match &message.payload {
865            MlsMessagePayload::Plain(plaintext) => Some((
866                &plaintext.content.group_id,
867                plaintext.content.epoch,
868                plaintext.content.content_type(),
869            )),
870            #[cfg(feature = "private_message")]
871            MlsMessagePayload::Cipher(ciphertext) => Some((
872                &ciphertext.group_id,
873                ciphertext.epoch,
874                ciphertext.content_type,
875            )),
876            _ => None,
877        } {
878            if group_id != &context.group_id {
879                return Err(MlsError::GroupIdMismatch);
880            }
881
882            match content_type {
883                ContentType::Commit => {
884                    if context.epoch != epoch {
885                        Err(MlsError::InvalidEpoch)
886                    } else {
887                        Ok(())
888                    }
889                }
890                #[cfg(feature = "by_ref_proposal")]
891                ContentType::Proposal => {
892                    if context.epoch != epoch {
893                        Err(MlsError::InvalidEpoch)
894                    } else {
895                        Ok(())
896                    }
897                }
898                #[cfg(feature = "private_message")]
899                ContentType::Application => {
900                    if let Some(min) = self.min_epoch_available() {
901                        if epoch < min {
902                            Err(MlsError::InvalidEpoch)
903                        } else {
904                            Ok(())
905                        }
906                    } else {
907                        Ok(())
908                    }
909                }
910            }?;
911
912            // Proposal and commit messages must be sent in the current epoch
913            let check_epoch = content_type == ContentType::Commit;
914
915            #[cfg(feature = "by_ref_proposal")]
916            let check_epoch = check_epoch || content_type == ContentType::Proposal;
917
918            if check_epoch && epoch != context.epoch {
919                return Err(MlsError::InvalidEpoch);
920            }
921
922            // Unencrypted application messages are not allowed
923            #[cfg(feature = "private_message")]
924            if !matches!(&message.payload, MlsMessagePayload::Cipher(_))
925                && content_type == ContentType::Application
926            {
927                return Err(MlsError::UnencryptedApplicationMessage);
928            }
929        }
930
931        Ok(())
932    }
933
934    fn validate_welcome(
935        &self,
936        welcome: &Welcome,
937        version: ProtocolVersion,
938    ) -> Result<(), MlsError> {
939        let state = self.group_state();
940
941        (welcome.cipher_suite == state.context.cipher_suite
942            && version == state.context.protocol_version)
943            .then_some(())
944            .ok_or(MlsError::InvalidWelcomeMessage)
945    }
946
947    async fn validate_key_package(
948        &self,
949        key_package: &KeyPackage,
950        version: ProtocolVersion,
951    ) -> Result<(), MlsError> {
952        let cs = self.cipher_suite_provider();
953        let id = self.identity_provider();
954
955        validate_key_package(key_package, version, cs, &id).await
956    }
957
958    #[cfg(feature = "private_message")]
959    async fn process_ciphertext(
960        &mut self,
961        cipher_text: &PrivateMessage,
962    ) -> Result<EventOrContent<Self::OutputType>, MlsError>;
963
964    async fn verify_plaintext_authentication(
965        &self,
966        message: PublicMessage,
967    ) -> Result<EventOrContent<Self::OutputType>, MlsError>;
968
969    async fn apply_update_path(
970        &mut self,
971        sender: LeafIndex,
972        update_path: &ValidatedUpdatePath,
973        provisional_state: &mut ProvisionalState,
974    ) -> Result<Option<(TreeKemPrivate, PathSecret)>, MlsError> {
975        provisional_state
976            .public_tree
977            .apply_update_path(
978                sender,
979                update_path,
980                &provisional_state.group_context.extensions,
981                self.identity_provider(),
982                self.cipher_suite_provider(),
983            )
984            .await
985            .map(|_| None)
986    }
987
988    async fn update_key_schedule(
989        &mut self,
990        secrets: Option<(TreeKemPrivate, PathSecret)>,
991        interim_transcript_hash: InterimTranscriptHash,
992        confirmation_tag: &ConfirmationTag,
993        provisional_public_state: ProvisionalState,
994    ) -> Result<(), MlsError>;
995}
996
997#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
998pub(crate) async fn validate_key_package<C: CipherSuiteProvider, I: IdentityProvider>(
999    key_package: &KeyPackage,
1000    version: ProtocolVersion,
1001    cs: &C,
1002    id: &I,
1003) -> Result<(), MlsError> {
1004    let validator = LeafNodeValidator::new(cs, id, MemberValidationContext::None);
1005
1006    #[cfg(feature = "std")]
1007    let context = Some(MlsTime::now());
1008
1009    #[cfg(not(feature = "std"))]
1010    let context = None;
1011
1012    let context = ValidationContext::Add(context);
1013
1014    validator
1015        .check_if_valid(&key_package.leaf_node, context)
1016        .await?;
1017
1018    validate_key_package_properties(key_package, version, cs).await?;
1019
1020    Ok(())
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use alloc::{vec, vec::Vec};
1026    use mls_rs_codec::{MlsDecode, MlsEncode};
1027
1028    use crate::{
1029        client::test_utils::TEST_PROTOCOL_VERSION,
1030        group::{test_utils::get_test_group_context, GroupState, Sender},
1031    };
1032
1033    use super::{CommitEffect, NewEpoch};
1034
1035    #[maybe_async::test(not(mls_build_async), async(mls_build_async, crate::futures_test))]
1036    async fn commit_effect_codec() {
1037        let epoch = NewEpoch {
1038            epoch: 7,
1039            prior_state: GroupState {
1040                #[cfg(feature = "by_ref_proposal")]
1041                proposals: crate::group::ProposalCache::new(TEST_PROTOCOL_VERSION, vec![]),
1042                context: get_test_group_context(7, 7.into()).await,
1043                public_tree: Default::default(),
1044                interim_transcript_hash: vec![].into(),
1045                pending_reinit: None,
1046                confirmation_tag: Default::default(),
1047            },
1048            applied_proposals: vec![],
1049            unused_proposals: vec![],
1050        };
1051
1052        let effects = vec![
1053            CommitEffect::NewEpoch(epoch.clone().into()),
1054            CommitEffect::Removed {
1055                new_epoch: epoch.into(),
1056                remover: Sender::Member(0),
1057            },
1058        ];
1059
1060        let bytes = effects.mls_encode_to_vec().unwrap();
1061
1062        assert_eq!(
1063            effects,
1064            Vec::<CommitEffect>::mls_decode(&mut &*bytes).unwrap()
1065        );
1066    }
1067}