Skip to main content

openmls/group/mls_group/
processing.rs

1//! Processing functions of an [`MlsGroup`] for incoming messages.
2
3use std::mem;
4
5#[cfg(any(not(feature = "virtual-clients-draft"), feature = "test-utils", test))]
6use errors::CommitToPendingProposalsError;
7use errors::MergePendingCommitError;
8#[cfg(feature = "extensions-draft")]
9use errors::ResolveAppDataCommitError;
10use openmls_traits::crypto::OpenMlsCrypto;
11#[cfg(any(not(feature = "virtual-clients-draft"), feature = "test-utils", test))]
12use openmls_traits::signatures::Signer;
13
14#[cfg(any(not(feature = "virtual-clients-draft"), feature = "test-utils", test))]
15use crate::messages::group_info::GroupInfo;
16use crate::{
17    framing::mls_content::FramedContentBody,
18    group::{errors::MergeCommitError, LeafNodeLifetimePolicy, StageCommitError, ValidationError},
19    storage::OpenMlsProvider,
20    tree::{secret_tree::PendingRatchetUpdate, sender_ratchet::SenderRatchetConfiguration},
21};
22
23// `virtual-clients-draft` implies `extensions-draft`, so this gate covers
24// both the sibling-commit detection and the AppDataUpdate handling below.
25#[cfg(feature = "extensions-draft")]
26use crate::messages::Commit;
27
28#[cfg(feature = "extensions-draft")]
29use crate::{
30    component::{ComponentData, ComponentId},
31    extensions::AppDataDictionary,
32    messages::proposals::AppDataUpdateProposal,
33};
34
35#[cfg(feature = "extensions-draft")]
36use std::collections::BTreeMap;
37
38use super::{errors::ProcessMessageError, *};
39
40/// Result of unprotecting an inbound message.
41pub(crate) enum UnprotectedMessage {
42    /// A message from another sender that has been unprotected and is ready
43    /// for signature verification and content parsing.
44    Unverified {
45        message: Box<UnverifiedMessage>,
46        ratchet_update: Option<EpochRatchetUpdate>,
47    },
48    /// A PrivateMessage whose sender data claims this client's own leaf. The
49    /// content cannot be decrypted; callers should surface
50    /// [`ProcessedMessageContent::OwnPrivateMessage`] and skip further
51    /// processing.
52    OwnPrivateMessage {
53        epoch: GroupEpoch,
54        authenticated_data: Vec<u8>,
55    },
56}
57
58/// A sender ratchet change from decrypting a PrivateMessage and the epoch of
59/// the secret tree it belongs to. It must only be applied once the message is
60/// processed successfully.
61pub(crate) struct EpochRatchetUpdate {
62    epoch: GroupEpoch,
63    update: PendingRatchetUpdate,
64}
65
66#[cfg(feature = "extensions-draft")]
67/// Keeps the old dictionary as well as the values that are being overwritten
68pub struct AppDataDictionaryUpdater<'a> {
69    old_dict: Option<&'a AppDataDictionary>,
70    new_entries: Option<AppDataUpdates>,
71}
72
73/// A diff of update values that can be provided to [`MlsGroup::stage_app_data_commit`] or [`CommitBuilder::with_app_data_dictionary_updates`]
74///
75/// [`CommitBuilder::with_app_data_dictionary_updates`]: crate::group::CommitBuilder::with_app_data_dictionary_updates
76#[cfg(feature = "extensions-draft")]
77#[derive(Default, Debug)]
78pub struct AppDataUpdates(BTreeMap<ComponentId, Option<Vec<u8>>>);
79
80#[cfg(feature = "extensions-draft")]
81impl IntoIterator for AppDataUpdates {
82    type Item = (ComponentId, Option<Vec<u8>>);
83
84    type IntoIter = <BTreeMap<ComponentId, Option<Vec<u8>>> as IntoIterator>::IntoIter;
85
86    fn into_iter(self) -> Self::IntoIter {
87        self.0.into_iter()
88    }
89}
90
91#[cfg(feature = "extensions-draft")]
92impl AppDataUpdates {
93    /// Returns the number of changes.
94    pub fn len(&self) -> usize {
95        self.0.len()
96    }
97
98    /// Returns whether there are changes.
99    pub fn is_empty(&self) -> bool {
100        self.0.is_empty()
101    }
102}
103
104#[cfg(feature = "extensions-draft")]
105impl<'a> AppDataDictionaryUpdater<'a> {
106    /// Creates a new [`AppDataDictionaryUpdater`].
107    pub fn new(old_dict: Option<&'a AppDataDictionary>) -> Self {
108        Self {
109            old_dict,
110            new_entries: None,
111        }
112    }
113
114    /// Looks up the old value for a component.
115    pub fn old_value(&self, component_id: ComponentId) -> Option<&[u8]> {
116        self.old_dict?.get(&component_id)
117    }
118
119    /// Helper method that returns a mutable reference to the
120    /// [`AppDataUpdates`], creating the struct if it does not exist.
121    fn new_entries_mut(&mut self) -> &mut AppDataUpdates {
122        self.new_entries
123            .get_or_insert_with(|| AppDataUpdates(BTreeMap::new()))
124    }
125
126    /// Sets a value in the new_entries. if we already have data for that component id, overwrite
127    /// it. Else add it in the right position.
128    pub fn set(&mut self, component_data: ComponentData) {
129        let (id, data) = component_data.into_parts();
130
131        self.new_entries_mut().0.insert(id, Some(data.into()));
132    }
133
134    /// Flags an entry in the dictionary for removal
135    pub fn remove(&mut self, id: &ComponentId) {
136        self.new_entries_mut().0.insert(*id, None);
137    }
138
139    /// Consumes the updater and returns just the changes, so we can pass them into
140    /// [`MlsGroup::stage_app_data_commit`] or
141    /// [`CommitBuilder::with_app_data_dictionary_updates`].
142    /// Only returns Some if we actually called set.
143    ///
144    /// [`CommitBuilder::with_app_data_dictionary_updates`]: crate::group::CommitBuilder::with_app_data_dictionary_updates
145    pub fn changes(self) -> Option<AppDataUpdates> {
146        self.new_entries
147    }
148}
149
150/// A verified Commit covering AppDataUpdate proposals that cannot be staged
151/// yet.
152///
153/// The AppDataUpdate proposals carry diffs in an application-defined format,
154/// so the application has to interpret them and compute the resulting
155/// [`AppDataUpdates`] before the commit can be staged: the updated
156/// [`AppDataDictionary`] becomes part of the new epoch's GroupContext and
157/// feeds into the key schedule.
158///
159/// Returned by [`MlsGroup::process_message()`] and
160/// [`PublicGroup::process_message()`] as
161/// [`ProcessedMessageContent::UnresolvedAppDataCommit`]. Inspect the proposals
162/// via [`Self::app_data_update_proposals()`], compute the updates with the
163/// help of [`MlsGroup::app_data_dictionary_updater()`] (or
164/// [`PublicGroup::app_data_dictionary_updater()`]) and resume staging via
165/// [`MlsGroup::stage_app_data_commit()`] (or
166/// [`PublicGroup::stage_app_data_commit()`]).
167///
168/// The message signature has already been verified at this point. Dropping
169/// this value discards the commit.
170///
171/// [`PublicGroup::process_message()`]: crate::group::public_group::PublicGroup::process_message
172/// [`PublicGroup::app_data_dictionary_updater()`]: crate::group::public_group::PublicGroup::app_data_dictionary_updater
173/// [`PublicGroup::stage_app_data_commit()`]: crate::group::public_group::PublicGroup::stage_app_data_commit
174#[cfg(feature = "extensions-draft")]
175pub struct UnresolvedAppDataCommit {
176    content: AuthenticatedContent,
177    /// The AppDataUpdate proposals covered by the commit, with proposals sent
178    /// by reference already resolved from the proposal store, sorted by
179    /// component id.
180    proposals: Vec<AppDataUpdateProposal>,
181    /// The lifetime policy the commit was processed with, which also applies
182    /// when it is staged.
183    lifetime_policy: LeafNodeLifetimePolicy,
184    #[cfg(feature = "virtual-clients-draft")]
185    vc_commit_material: Option<crate::components::vc_derivation_info::VcCommitMaterial>,
186}
187
188#[cfg(feature = "extensions-draft")]
189impl UnresolvedAppDataCommit {
190    /// Constructs an [`UnresolvedAppDataCommit`] from verified content and the
191    /// covered AppDataUpdate proposals. Used by public-group processing, which
192    /// carries no virtual-clients material.
193    pub(crate) fn new(
194        content: AuthenticatedContent,
195        proposals: Vec<AppDataUpdateProposal>,
196        lifetime_policy: LeafNodeLifetimePolicy,
197    ) -> Self {
198        Self {
199            content,
200            proposals,
201            lifetime_policy,
202            #[cfg(feature = "virtual-clients-draft")]
203            vc_commit_material: None,
204        }
205    }
206
207    /// The lifetime policy the commit was processed with.
208    pub(crate) fn lifetime_policy(&self) -> LeafNodeLifetimePolicy {
209        self.lifetime_policy
210    }
211
212    /// Consumes the commit and returns the verified [`AuthenticatedContent`],
213    /// so that [`PublicGroup::stage_app_data_commit`] can resume staging.
214    ///
215    /// [`PublicGroup::stage_app_data_commit`]: crate::group::public_group::PublicGroup::stage_app_data_commit
216    pub(crate) fn into_content(self) -> AuthenticatedContent {
217        self.content
218    }
219
220    /// Returns the AppDataUpdate proposals covered by the commit, sorted by
221    /// component id. Proposals that were committed by reference have already
222    /// been resolved from the proposal store.
223    pub fn app_data_update_proposals(&self) -> impl Iterator<Item = &AppDataUpdateProposal> {
224        self.proposals.iter()
225    }
226}
227
228#[cfg(feature = "extensions-draft")]
229impl core::fmt::Debug for UnresolvedAppDataCommit {
230    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
231        let mut debug_struct = f.debug_struct("UnresolvedAppDataCommit");
232        debug_struct
233            .field("content", &self.content)
234            .field("proposals", &self.proposals);
235        // vc_commit_material holds secret key material, so only the epoch id
236        // is printed.
237        #[cfg(feature = "virtual-clients-draft")]
238        debug_struct.field(
239            "vc_derivation_epoch_id",
240            &self
241                .vc_commit_material
242                .as_ref()
243                .map(|material| &material.epoch_id),
244        );
245        debug_struct.finish_non_exhaustive()
246    }
247}
248
249impl MlsGroup {
250    /// Parses incoming messages from the DS. Checks for syntactic errors and
251    /// makes some semantic checks as well. If the input is an encrypted
252    /// message, it will be decrypted. This processing function does syntactic
253    /// and semantic validation of the message. It returns a [ProcessedMessage]
254    /// enum.
255    ///
256    #[cfg_attr(
257        feature = "extensions-draft",
258        doc = "A commit covering AppDataUpdate proposals is returned as\n\
259        [`ProcessedMessageContent::UnresolvedAppDataCommit`], since the\n\
260        application has to interpret the proposals before the commit can be\n\
261        staged via [`MlsGroup::stage_app_data_commit()`].\n"
262    )]
263    /// # Errors:
264    /// Returns an [`ProcessMessageError`] when the validation checks fail
265    /// with the exact reason of the failure.
266    #[openmls_traits::maybe_async]
267    pub async fn process_message<Provider: OpenMlsProvider>(
268        &mut self,
269        provider: &Provider,
270        message: impl Into<ProtocolMessage>,
271    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
272        self.process_message_with_lifetime_policy(provider, message, LeafNodeLifetimePolicy::Verify)
273            .await
274    }
275
276    /// Like [`Self::process_message`], but checks the lifetimes of the key
277    /// packages in Add proposals under `lifetime_policy`.
278    /// [`Self::process_message`] uses [`LeafNodeLifetimePolicy::Verify`].
279    ///
280    #[cfg_attr(
281        feature = "extensions-draft",
282        doc = "If the call returns a [`ProcessedMessageContent::UnresolvedAppDataCommit`],\n\
283        [`MlsGroup::stage_app_data_commit()`] checks the commit under the same\n\
284        policy.\n"
285    )]
286    #[openmls_traits::maybe_async]
287    pub async fn process_message_with_lifetime_policy<Provider: OpenMlsProvider>(
288        &mut self,
289        provider: &Provider,
290        message: impl Into<ProtocolMessage>,
291        lifetime_policy: LeafNodeLifetimePolicy,
292    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
293        match self.unprotect_message(provider, message).await? {
294            UnprotectedMessage::Unverified {
295                message,
296                ratchet_update,
297            } => {
298                self.process_unverified_message(provider, *message, ratchet_update, lifetime_policy)
299                    .await
300            }
301            // The content cannot be decrypted and the sender claim is unauthenticated,
302            // so we surface OwnPrivateMessage and skip all further processing.
303            UnprotectedMessage::OwnPrivateMessage {
304                epoch,
305                authenticated_data,
306            } => {
307                let credential = self.credential()?.clone();
308                #[cfg_attr(not(feature = "extensions-draft"), allow(unused_mut))]
309                let mut processed = ProcessedMessage::new(
310                    self.group_id().clone(),
311                    epoch,
312                    Sender::Member(self.own_leaf_index()),
313                    authenticated_data,
314                    ProcessedMessageContent::OwnPrivateMessage,
315                    credential,
316                    #[cfg(feature = "virtual-clients-draft")]
317                    None,
318                );
319                #[cfg(feature = "extensions-draft")]
320                if self.context().safe_aad_required() {
321                    processed
322                        .try_attach_safe_aad()
323                        .map_err(|_| ProcessMessageError::MalformedSafeAad)?;
324                }
325                Ok(processed)
326            }
327        }
328    }
329
330    #[cfg(feature = "extensions-draft")]
331    /// Returns a new helper struct for updating the app data
332    pub fn app_data_dictionary_updater<'a>(&'a self) -> AppDataDictionaryUpdater<'a> {
333        AppDataDictionaryUpdater::new(self.context().app_data_dict())
334    }
335
336    /// Parses and deprotects incoming messages from the DS. Checks for syntactic errors, but only
337    /// performs limited semantic checks.
338    #[openmls_traits::maybe_async]
339    pub(crate) async fn unprotect_message<Provider: OpenMlsProvider>(
340        &mut self,
341        provider: &Provider,
342        message: impl Into<ProtocolMessage>,
343    ) -> Result<UnprotectedMessage, ProcessMessageError<Provider::StorageError>> {
344        // Make sure we are still a member of the group
345        if !self.is_active() {
346            return Err(ProcessMessageError::GroupStateError(
347                MlsGroupStateError::UseAfterEviction,
348            ));
349        }
350        let message = message.into();
351
352        // Check that handshake messages are compatible with the incoming wire format policy
353        if !message.is_external()
354            && message.is_handshake_message()
355            && !self
356                .configuration()
357                .wire_format_policy()
358                .incoming()
359                .is_compatible_with(message.wire_format())
360        {
361            return Err(ProcessMessageError::IncompatibleWireFormat);
362        }
363
364        // Parse the message
365        let sender_ratchet_configuration = *self.configuration().sender_ratchet_configuration();
366
367        let epoch = message.epoch();
368
369        // Resolve the emulator reuse-guard context for `PrivateMessage`
370        // before calling `decrypt_message` so storage errors surface as
371        // `ProcessMessageError::StorageError`. `PublicMessage` carries no
372        // `reuse_guard`, so the lookup is skipped for it. The binding is
373        // looked up at the epoch the message was sent in: a delayed message
374        // from a past epoch must be deprotected with the derivation epoch state
375        // that was bound then, not the latest one.
376        #[cfg(feature = "virtual-clients-draft")]
377        let derivation_state = if let ProtocolMessage::PrivateMessage(private_message) = &message {
378            self.vc_derivation_state_at_epoch(provider.storage(), private_message.epoch())
379                .await
380                .map_err(|e| match e {
381                    super::VcDerivationStateError::Storage(e) => {
382                        ProcessMessageError::StorageError(e)
383                    }
384                    super::VcDerivationStateError::MissingDerivationEpochState => {
385                        ProcessMessageError::ValidationError(
386                            crate::group::ValidationError::UnableToDecrypt(
387                                crate::framing::errors::MessageDecryptionError::VirtualClientsError(
388                                    crate::components::vc_derivation_info::VirtualClientsError::MissingDerivationEpochState,
389                                ),
390                            ),
391                        )
392                    }
393                })?
394        } else {
395            None
396        };
397        #[cfg(feature = "virtual-clients-draft")]
398        let emulator_ctx: Option<crate::framing::EmulatorReuseGuardCtx<'_>> = derivation_state
399            .as_ref()
400            .map(|state| state.reuse_guard_inputs());
401
402        // Checks the following semantic validation:
403        //  - ValSem002
404        //  - ValSem003
405        //  - ValSem006
406        //  - ValSem007 MembershipTag presence
407        let decrypt_result = self.decrypt_message(
408            provider.crypto(),
409            message,
410            &sender_ratchet_configuration,
411            #[cfg(feature = "virtual-clients-draft")]
412            emulator_ctx.as_ref(),
413        )?;
414
415        let (decrypted_message, ratchet_update) = match decrypt_result {
416            InboundDecryptionResult::Decrypted {
417                message,
418                ratchet_update,
419            } => (message, ratchet_update),
420            // Own private messages short-circuit here: there is no content
421            // to parse or verify.
422            InboundDecryptionResult::OwnPrivateMessage {
423                epoch,
424                authenticated_data,
425            } => {
426                return Ok(UnprotectedMessage::OwnPrivateMessage {
427                    epoch,
428                    authenticated_data,
429                });
430            }
431        };
432
433        let unverified_message = self
434            .public_group
435            .parse_message(decrypted_message, &self.message_secrets_store)
436            .map_err(ProcessMessageError::from)?;
437
438        Ok(UnprotectedMessage::Unverified {
439            message: Box::new(unverified_message),
440            ratchet_update: ratchet_update.map(|update| EpochRatchetUpdate { epoch, update }),
441        })
442    }
443
444    /// Stores a standalone proposal in the internal [ProposalStore]
445    #[openmls_traits::maybe_async]
446    pub async fn store_pending_proposal<Storage: StorageProvider>(
447        &mut self,
448        storage: &Storage,
449        proposal: QueuedProposal,
450    ) -> Result<(), Storage::Error> {
451        storage
452            .queue_proposal(self.group_id(), &proposal.proposal_reference(), &proposal)
453            .await?;
454        // Store the proposal in in the internal ProposalStore
455        self.proposal_store_mut().add(proposal);
456
457        Ok(())
458    }
459
460    /// Returns true if there are pending proposals queued in the proposal store.
461    pub fn has_pending_proposals(&self) -> bool {
462        !self.proposal_store().is_empty()
463    }
464
465    /// Creates a Commit message that covers the pending proposals that are
466    /// currently stored in the group's [ProposalStore]. The Commit message is
467    /// created even if there are no valid pending proposals.
468    ///
469    /// Returns an error if there is a pending commit. Otherwise it returns a
470    /// tuple of `Commit, Option<Welcome>, Option<GroupInfo>`, where `Commit`
471    /// and [`Welcome`] are MlsMessages of the type [`MlsMessageOut`].
472    ///
473    /// Under the `virtual-clients-draft` feature this function is unavailable.
474    /// Use [`MlsGroup::commit_builder`], whose
475    /// [`CommitMessageBundle::confirmation`] surfaces the handshake confirmation
476    /// data.
477    ///
478    /// [`Welcome`]: crate::messages::Welcome
479    /// [`CommitMessageBundle::confirmation`]: crate::group::CommitMessageBundle::confirmation
480    // FIXME: #1217
481    #[cfg(any(not(feature = "virtual-clients-draft"), feature = "test-utils", test))]
482    #[allow(clippy::type_complexity)]
483    #[openmls_traits::maybe_async]
484    pub async fn commit_to_pending_proposals<Provider: OpenMlsProvider>(
485        &mut self,
486        provider: &Provider,
487        signer: &impl Signer,
488    ) -> Result<
489        (MlsMessageOut, Option<MlsMessageOut>, Option<GroupInfo>),
490        CommitToPendingProposalsError<Provider::StorageError>,
491    > {
492        self.is_operational()?;
493
494        // Build and stage the commit using the commit builder
495        let (commit, welcome, group_info) = self
496            .commit_builder()
497            // This forces committing to the proposals in the proposal store:
498            .consume_proposal_store(true)
499            .load_psks(provider.storage())
500            .await?
501            .build(provider.crypto(), signer, |_| true)?
502            .stage_commit(provider)
503            .await?
504            .into_contents();
505
506        Ok((
507            commit,
508            // Turn the [`Welcome`] to an [`MlsMessageOut`], if there is one
509            welcome.map(|welcome| MlsMessageOut::from_welcome(welcome, self.version())),
510            group_info,
511        ))
512    }
513
514    /// Merge a [StagedCommit] into the group after inspection. As this advances
515    /// the epoch of the group, it also clears any pending commits.
516    #[openmls_traits::maybe_async]
517    pub async fn merge_staged_commit<Provider: OpenMlsProvider>(
518        &mut self,
519        provider: &Provider,
520        staged_commit: StagedCommit,
521    ) -> Result<(), MergeCommitError<Provider::StorageError>> {
522        // A commit containing a ReInit proposal reinitializes the group: once
523        // merged, the group is suspended (RFC 9420 §11.2). Detect it before
524        // `staged_commit` is consumed by `merge_commit` below. A validated
525        // commit carries at most one ReInit and no other proposals alongside it.
526        let is_reinit = staged_commit.reinit_proposal().is_some();
527
528        // Check if we were removed from the group
529        if staged_commit.self_removed() {
530            self.group_state = MlsGroupState::Inactive;
531        }
532        provider
533            .storage()
534            .write_group_state(self.group_id(), &self.group_state)
535            .await
536            .map_err(MergeCommitError::StorageError)?;
537
538        // Update the per-epoch emulation bindings. Self-removal drops them,
539        // along with the group's own derivation-epoch log. Otherwise the epoch
540        // the commit moves the group into is bound to the derivation epoch of
541        // the commit's VC leaf, or, if the commit does not install a new VC
542        // leaf, to the binding of the current epoch, since the VC leaf stays
543        // active across commits by other members. Either way the derivation
544        // epochs that lost their last reference are released.
545        #[cfg(feature = "virtual-clients-draft")]
546        if staged_commit.self_removed() {
547            self.drop_all_vc_derivation_epoch_references(provider.storage())
548                .await
549                .map_err(|e| {
550                    log::error!("vc: drop derivation epoch references on self-removal: {e:?}");
551                    MergeCommitError::StorageError(e)
552                })?;
553        } else {
554            use crate::components::vc_derivation_info::{EpochId, VcEmulationBinding};
555
556            let epoch_id = match staged_commit.vc_derivation_epoch_id.clone() {
557                Some(epoch_id) => Some(epoch_id),
558                None => provider
559                    .storage()
560                    .vc_emulation_binding(self.group_id(), &self.epoch())
561                    .await
562                    .map_err(MergeCommitError::StorageError)?
563                    .map(VcEmulationBinding::into_epoch_id),
564            };
565            if let Some(epoch_id) = epoch_id {
566                // Keep one binding per retained message-secrets epoch plus
567                // the new current one, so bindings age out in lockstep
568                // with the message secrets they are needed for.
569                let max_entries = self.message_secrets_store.max_epochs.saturating_add(1);
570                crate::components::vc_derivation_info::write_vc_emulation_binding_with_pruning(
571                    provider.storage(),
572                    self.group_id(),
573                    staged_commit.epoch(),
574                    epoch_id,
575                    max_entries,
576                )
577                .await
578                .map_err(|e| {
579                    log::error!("vc: persist emulation binding at merge failed: {e:?}");
580                    MergeCommitError::StorageError(e)
581                })?;
582                // The epochs whose bindings just aged out lost a reference, so
583                // sweep the ones that are now unreferenced.
584                provider
585                    .storage()
586                    .delete_unreferenced_vc_derivation_epoch_states::<EpochId>()
587                    .await
588                    .map_err(|e| {
589                        log::error!("vc: release unbound derivation epochs at merge: {e:?}");
590                        MergeCommitError::StorageError(e)
591                    })?;
592            }
593        }
594
595        // Merge staged commit
596        self.merge_commit(provider, staged_commit).await?;
597
598        // Extract and store the resumption psk for the current epoch
599        let resumption_psk = self.group_epoch_secrets().resumption_psk();
600        self.resumption_psk_store
601            .add(self.context().epoch(), resumption_psk.clone());
602        provider
603            .storage()
604            .write_resumption_psk_store(self.group_id(), &self.resumption_psk_store)
605            .await
606            .map_err(MergeCommitError::StorageError)?;
607
608        // Delete own KeyPackageBundles
609        self.own_leaf_nodes.clear();
610        provider
611            .storage()
612            .delete_own_leaf_nodes(self.group_id())
613            .await
614            .map_err(MergeCommitError::StorageError)?;
615
616        // Delete a potential pending commit
617        self.clear_pending_commit(provider.storage())
618            .await
619            .map_err(MergeCommitError::StorageError)?;
620
621        // If this commit reinitialized the group, suspend it now that the commit
622        // is merged: the group becomes inactive (like eviction) so it can no
623        // longer be used for regular operations. Its resumption PSK for this
624        // (final) epoch was stored above and is what the successor group mixes
625        // in via [`CommitBuilder::reinit`] / [`StagedWelcome::build_from_reinit`].
626        if is_reinit {
627            self.group_state = MlsGroupState::Inactive;
628            provider
629                .storage()
630                .write_group_state(self.group_id(), &self.group_state)
631                .await
632                .map_err(MergeCommitError::StorageError)?;
633        }
634
635        Ok(())
636    }
637
638    /// Merges the pending [`StagedCommit`] if there is one, and
639    /// clears the field by setting it to `None`.
640    #[openmls_traits::maybe_async]
641    pub async fn merge_pending_commit<Provider: OpenMlsProvider>(
642        &mut self,
643        provider: &Provider,
644    ) -> Result<(), MergePendingCommitError<Provider::StorageError>> {
645        match &self.group_state {
646            MlsGroupState::PendingCommit(_) => {
647                let old_state = mem::replace(&mut self.group_state, MlsGroupState::Operational);
648                if let MlsGroupState::PendingCommit(pending_commit_state) = old_state {
649                    self.merge_staged_commit(provider, (*pending_commit_state).into())
650                        .await?;
651                }
652                Ok(())
653            }
654            MlsGroupState::Inactive => Err(MlsGroupStateError::UseAfterEviction)?,
655            MlsGroupState::Operational => Ok(()),
656        }
657    }
658
659    /// Resolve a commit's virtual-clients derivation info to the per-commit
660    /// `OperationSecret` the receiver needs in order to recreate the path of a
661    /// commit sent by a sibling emulator client, plus the `EpochId` the
662    /// commit binds the group to on merge.
663    ///
664    /// See [`is_sibling_vc_commit`] for the precondition the caller must
665    /// check before invoking this helper. Sibling commits come in two
666    /// shapes:
667    ///
668    ///   * own-leaf VC commits, where a sibling emulator committed through our
669    ///     shared higher-level leaf
670    ///   * sibling-resync external commits, where a sibling emulator joined this
671    ///     higher-level group externally onto a leaf of their own,
672    ///     inline-removing our previous leaf.
673    ///
674    /// Returns `Ok(None)` when the commit carries no virtual-clients
675    /// derivation-info entry on its update-path leaf (path-less commits, or
676    /// commits without an `app_data_dictionary`). Otherwise:
677    ///   - looks up the per-epoch `VcDerivationEpochState` and operation secret
678    ///     tree registered for the commit's derivation epoch,
679    ///   - decrypts the wrapped `DerivationInfoTbe` with the AEAD key/nonce
680    ///     derived from the epoch encryption key and the path leaf's
681    ///     serialized encryption key,
682    ///   - derives the operation secret positionally from the tree at the
683    ///     sender's emulation-leaf coordinates and persists the advanced
684    ///     tree,
685    ///   - returns the resulting `OperationSecret` and `EpochId`.
686    ///
687    /// A generation the tree reports as already consumed fails with
688    /// `OperationGenerationConsumed`. Operation secrets are consume-once,
689    /// matching the semantics of regular PrivateMessage decryption.
690    #[cfg(feature = "virtual-clients-draft")]
691    #[openmls_traits::maybe_async]
692    pub(super) async fn load_vc_commit_material<Provider: OpenMlsProvider>(
693        &self,
694        provider: &Provider,
695        commit: &Commit,
696    ) -> Result<Option<crate::components::vc_derivation_info::VcCommitMaterial>, StageCommitError>
697    {
698        use tls_codec::Serialize as _;
699
700        use crate::{
701            components::vc_derivation_info::{
702                VcDerivationEpochState, VirtualClientOperationType, VirtualClientsError,
703            },
704            components::vc_operation_tree::OperationSecretTree,
705            treesync::node::leaf_node::LeafNodeSource,
706        };
707
708        let Some(path) = commit.path.as_ref() else {
709            return Ok(None);
710        };
711        let Some(derivation_info) = path.leaf_node().vc_derivation_info()? else {
712            return Ok(None);
713        };
714
715        let epoch_id = derivation_info.epoch_id();
716        let storage = provider.storage();
717        let state: VcDerivationEpochState = storage
718            .vc_derivation_epoch_state(epoch_id)
719            .await
720            .map_err(|e| {
721                log::error!("vc: load derivation epoch state failed: {e:?}");
722                VirtualClientsError::StorageError
723            })?
724            .ok_or(VirtualClientsError::MissingDerivationEpochState)?;
725        let mut operation_tree: OperationSecretTree = storage
726            .vc_operation_tree(epoch_id)
727            .await
728            .map_err(|e| {
729                log::error!("vc: load operation tree failed: {e:?}");
730                VirtualClientsError::StorageError
731            })?
732            .ok_or(VirtualClientsError::MissingOperationTree)?;
733        // The receiver uses the derivation epoch's AEAD key and ciphersuite
734        // for `DerivationInfoTbe`. The sender's emulation leaf index travels
735        // on the wire, so it doesn't have to come from storage on this side.
736        let (_state_leaf_index, epoch_encryption_key, emulation_ciphersuite) = state.into_parts();
737
738        let crypto = provider.crypto();
739        let leaf_encryption_key = path
740            .leaf_node()
741            .encryption_key()
742            .tls_serialize_detached()
743            .map_err(VirtualClientsError::from)?;
744        // The operation type is not on the wire. It is inferred from the
745        // carrying leaf's source: key-package leaves map to `KeyPackage`,
746        // update and commit leaves map to `LeafNode`. Only `LeafNode` is
747        // wired up today, and an update-path leaf always has a commit
748        // source. It selects the tagless `DerivationInfoTbe` variant the
749        // plaintext decodes into.
750        let operation_type = match path.leaf_node().leaf_node_source() {
751            LeafNodeSource::KeyPackage(_) => {
752                log::error!("vc: key-package leaf on an update path");
753                return Err(VirtualClientsError::DerivationInfoMalformed.into());
754            }
755            LeafNodeSource::Update | LeafNodeSource::Commit(_) => {
756                VirtualClientOperationType::LeafNode
757            }
758        };
759        let tbe = derivation_info.decrypt(
760            crypto,
761            emulation_ciphersuite,
762            &epoch_encryption_key,
763            &leaf_encryption_key,
764            operation_type,
765        )?;
766        // Carried by an external commit's leaf only; `None` for own-leaf
767        // (regular) VC commits. A sibling uses it as the new epoch's external
768        // init secret instead of decapsulating from the previous epoch's
769        // `external_secret`.
770        let external_init_secret = tbe.external_init_secret().cloned();
771        // The operation context for `LeafNode` operations is the
772        // higher-level group's id.
773        let operation_context = self.group_id().as_slice().to_vec();
774
775        // An already-consumed generation propagates as a hard error here:
776        // operation secrets are consume-once, like the per-generation keys
777        // of regular PrivateMessage decryption.
778        let operation_secret = operation_tree.derive_operation_secret(
779            crypto,
780            emulation_ciphersuite,
781            epoch_id,
782            tbe.leaf_index(),
783            operation_type,
784            tbe.generation(),
785            &operation_context,
786        )?;
787        // Persist the advanced tree immediately, before any key material is
788        // derived from the secret.
789        storage
790            .write_vc_operation_tree(epoch_id, &operation_tree)
791            .await
792            .map_err(|e| {
793                log::error!("vc: persist advanced operation tree failed: {e:?}");
794                VirtualClientsError::StorageError
795            })?;
796
797        Ok(Some(
798            crate::components::vc_derivation_info::VcCommitMaterial {
799                epoch_id: epoch_id.clone(),
800                operation_secret,
801                external_init_secret,
802            },
803        ))
804    }
805
806    /// Helper function to read decryption keypairs.
807    #[openmls_traits::maybe_async]
808    pub(super) async fn read_decryption_keypairs(
809        &self,
810        provider: &impl OpenMlsProvider,
811        own_leaf_nodes: &[LeafNode],
812    ) -> Result<(Vec<EncryptionKeyPair>, Vec<EncryptionKeyPair>), StageCommitError> {
813        // All keys from the previous epoch are potential decryption keypairs.
814        let old_epoch_keypairs =
815            self.read_epoch_keypairs(provider.storage())
816                .await
817                .map_err(|e| {
818                    log::error!("Error reading epoch keypairs: {e:?}");
819                    StageCommitError::MissingDecryptionKey
820                })?;
821
822        // If we are processing an update proposal that originally came from
823        // us, the keypair corresponding to the leaf in the update is also a
824        // potential decryption keypair.
825        let mut leaf_node_keypairs = Vec::with_capacity(own_leaf_nodes.len());
826        for leaf_node in own_leaf_nodes {
827            let keypair = EncryptionKeyPair::read(provider, leaf_node.encryption_key())
828                .await
829                .ok_or(StageCommitError::MissingDecryptionKey)?;
830            leaf_node_keypairs.push(keypair);
831        }
832
833        Ok((old_epoch_keypairs, leaf_node_keypairs))
834    }
835
836    /// Stages a Commit covering AppDataUpdate proposals, after the application
837    /// has interpreted the proposals and computed the resulting
838    /// [`AppDataUpdates`].
839    ///
840    /// The returned [`StagedCommit`] can be inspected and merged into the
841    /// group's state using [`MlsGroup::merge_staged_commit()`].
842    #[cfg(feature = "extensions-draft")]
843    #[openmls_traits::maybe_async]
844    pub async fn stage_app_data_commit<Provider: OpenMlsProvider>(
845        &self,
846        provider: &Provider,
847        unresolved_commit: UnresolvedAppDataCommit,
848        app_data_dict_updates: Option<AppDataUpdates>,
849    ) -> Result<StagedCommit, StageCommitError> {
850        let content = unresolved_commit.content;
851        let lifetime_policy = unresolved_commit.lifetime_policy;
852        #[cfg(feature = "virtual-clients-draft")]
853        let vc_commit_material = unresolved_commit.vc_commit_material;
854
855        let (old_epoch_keypairs, leaf_node_keypairs) = self
856            .read_decryption_keypairs(provider, &self.own_leaf_nodes)
857            .await?;
858
859        self.stage_commit_with_app_data_updates(
860            &content,
861            old_epoch_keypairs,
862            leaf_node_keypairs,
863            app_data_dict_updates,
864            provider,
865            lifetime_policy,
866            #[cfg(feature = "virtual-clients-draft")]
867            vc_commit_material,
868        )
869        .await
870    }
871
872    /// Resolves a [`ProcessedMessage`] carrying an
873    /// [`ProcessedMessageContent::UnresolvedAppDataCommit`]: stages the commit
874    /// with the application-computed [`AppDataUpdates`] and returns the same
875    /// message with the resulting [`StagedCommit`] as regular
876    /// [`ProcessedMessageContent::StagedCommitMessage`] content. All other
877    /// message fields (sender, credential, authenticated data) are preserved.
878    ///
879    /// Use this instead of [`MlsGroup::stage_app_data_commit()`] when the
880    /// caller needs the resolved commit in [`ProcessedMessage`] form, e.g. to
881    /// keep a single code path for commits with and without AppDataUpdate
882    /// proposals.
883    ///
884    /// Returns an error if the message content is not an unresolved app data
885    /// commit; the message is consumed either way.
886    #[cfg(feature = "extensions-draft")]
887    #[openmls_traits::maybe_async]
888    pub async fn resolve_app_data_commit<Provider: OpenMlsProvider>(
889        &self,
890        provider: &Provider,
891        processed_message: ProcessedMessage,
892        app_data_dict_updates: Option<AppDataUpdates>,
893    ) -> Result<ProcessedMessage, ResolveAppDataCommitError> {
894        let (unresolved_commit, with_staged_commit) =
895            processed_message.split_unresolved_app_data_commit()?;
896        let staged_commit = self
897            .stage_app_data_commit(provider, unresolved_commit, app_data_dict_updates)
898            .await?;
899        Ok(with_staged_commit(staged_commit))
900    }
901
902    /// This processing function does most of the semantic verifications.
903    /// It returns a [ProcessedMessage] enum.
904    ///
905    /// Checks the following semantic validation:
906    ///  - ValSem008
907    ///  - ValSem010
908    ///  - ValSem101
909    ///  - ValSem102
910    ///  - ValSem104
911    ///  - ValSem106
912    ///  - ValSem107
913    ///  - ValSem108
914    ///  - ValSem110
915    ///  - ValSem111
916    ///  - ValSem112
917    ///  - ValSem113: All Proposals: The proposal type must be supported by all
918    ///    members of the group
919    ///  - ValSem200
920    ///  - ValSem201
921    ///  - ValSem202: Path must be the right length
922    ///  - ValSem203: Path secrets must decrypt correctly
923    ///  - ValSem204: Public keys from Path must be verified and match the
924    ///    private keys from the direct path
925    ///  - ValSem205
926    ///
927    /// Applies and persists `ratchet_update` only if processing succeeds.
928    #[openmls_traits::maybe_async]
929    pub(crate) async fn process_unverified_message<Provider: OpenMlsProvider>(
930        &mut self,
931        provider: &Provider,
932        unverified_message: UnverifiedMessage,
933        ratchet_update: Option<EpochRatchetUpdate>,
934        lifetime_policy: LeafNodeLifetimePolicy,
935    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
936        // Checks the following semantic validation:
937        //  - ValSem010
938        //  - ValSem246 (as part of ValSem010)
939        //  - https://validation.openmls.tech/#valn1302
940        //  - https://validation.openmls.tech/#valn1304
941        let verified = unverified_message.verify(
942            self.ciphersuite(),
943            provider.crypto(),
944            self.version(),
945            lifetime_policy,
946        )?;
947
948        let processed = self
949            .process_verified_message(provider, verified, lifetime_policy)
950            .await?;
951
952        if let Some(ratchet_update) = ratchet_update {
953            self.apply_ratchet_update(provider, ratchet_update).await?;
954        }
955
956        Ok(processed)
957    }
958
959    /// Applies a sender ratchet change from decrypting a PrivateMessage and
960    /// persists the message secrets.
961    #[openmls_traits::maybe_async]
962    async fn apply_ratchet_update<Provider: OpenMlsProvider>(
963        &mut self,
964        provider: &Provider,
965        ratchet_update: EpochRatchetUpdate,
966    ) -> Result<(), ProcessMessageError<Provider::StorageError>> {
967        let sender_ratchet_configuration = *self.configuration().sender_ratchet_configuration();
968        self.message_secrets_for_epoch_mut(ratchet_update.epoch)
969            .and_then(|message_secrets| {
970                message_secrets
971                    .secret_tree_mut()
972                    .apply_decryption_update(ratchet_update.update, &sender_ratchet_configuration)
973            })
974            .map_err(|_| {
975                LibraryError::custom("Message secrets of a decrypted message are missing")
976            })?;
977        provider
978            .storage()
979            .write_message_secrets(self.group_id(), &self.message_secrets_store)
980            .await
981            .map_err(ProcessMessageError::StorageError)
982    }
983
984    #[openmls_traits::maybe_async]
985    async fn process_verified_message<Provider: OpenMlsProvider>(
986        &self,
987        provider: &Provider,
988        verified: VerifiedMessage,
989        lifetime_policy: LeafNodeLifetimePolicy,
990    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
991        #[cfg_attr(not(feature = "extensions-draft"), allow(unused_mut))]
992        let mut processed = match verified.content.sender() {
993            Sender::Member(_) | Sender::NewMemberProposal | Sender::NewMemberCommit => {
994                self.process_internal_authenticated_content(
995                    provider,
996                    verified.content,
997                    verified.credential,
998                    lifetime_policy,
999                    #[cfg(feature = "virtual-clients-draft")]
1000                    verified.emulator_sender_leaf_index,
1001                )
1002                .await?
1003            }
1004            Sender::External(_) => self.process_external_authenticated_content(
1005                provider,
1006                verified.content,
1007                verified.credential,
1008            )?,
1009        };
1010        #[cfg(feature = "extensions-draft")]
1011        if self.context().safe_aad_required() {
1012            processed
1013                .try_attach_safe_aad()
1014                .map_err(|_| ProcessMessageError::MalformedSafeAad)?;
1015        }
1016        Ok(processed)
1017    }
1018
1019    #[openmls_traits::maybe_async]
1020    async fn process_internal_authenticated_content<Provider: OpenMlsProvider>(
1021        &self,
1022        provider: &Provider,
1023        content: AuthenticatedContent,
1024        credential: Credential,
1025        lifetime_policy: LeafNodeLifetimePolicy,
1026        #[cfg(feature = "virtual-clients-draft")] emulator_sender_leaf_index: Option<LeafNodeIndex>,
1027    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
1028        let sender = content.sender().clone();
1029        let authenticated_data = content.authenticated_data().to_owned();
1030        let epoch = content.epoch();
1031
1032        let content = match content.content() {
1033            FramedContentBody::Application(application_message) => {
1034                ProcessedMessageContent::ApplicationMessage(ApplicationMessage::new(
1035                    application_message.as_slice().to_owned(),
1036                ))
1037            }
1038            FramedContentBody::Proposal(_) => {
1039                let proposal = Box::new(QueuedProposal::from_authenticated_content_by_ref(
1040                    self.ciphersuite(),
1041                    provider.crypto(),
1042                    content,
1043                )?);
1044
1045                if matches!(sender, Sender::NewMemberProposal) {
1046                    ProcessedMessageContent::ExternalJoinProposalMessage(proposal)
1047                } else {
1048                    ProcessedMessageContent::ProposalMessage(proposal)
1049                }
1050            }
1051            FramedContentBody::Commit(commit) => {
1052                let is_own_commit =
1053                    matches!(&sender, Sender::Member(member) if member == &self.own_leaf_index());
1054
1055                if is_own_commit {
1056                    let received_tag = content
1057                        .confirmation_tag()
1058                        .ok_or(StageCommitError::ConfirmationTagMissing)?;
1059                    if self.matches_pending_commit(received_tag) {
1060                        // The Commit is our pending commit this client got
1061                        // fanned out by the delivery service: surface
1062                        // `OwnPendingCommit` so the caller merges the pending
1063                        // commit instead of staging the fanned-out Commit.
1064                        return Ok(ProcessedMessage::new(
1065                            self.group_id().clone(),
1066                            epoch,
1067                            sender,
1068                            authenticated_data,
1069                            ProcessedMessageContent::OwnPendingCommit,
1070                            credential,
1071                            #[cfg(feature = "virtual-clients-draft")]
1072                            emulator_sender_leaf_index,
1073                        ));
1074                    }
1075                }
1076
1077                // Load virtual-client derivation info when this commit was
1078                // authored by a sibling emulator through a leaf shared with us.
1079                // The pending-commit match above already ran, so an own commit
1080                // echoed back by the delivery service never reaches this load
1081                // and no operation-secret generation is consumed for it. A
1082                // sibling's commit never matches our pending commit's
1083                // confirmation tag, so sibling commits still take this path.
1084                // The receiver only loads the material when the commit shape
1085                // lets it identify itself as a sibling:
1086                //
1087                // * `Sender::Member(idx)` with `idx == own_leaf_index`: the
1088                //   sender committed through our shared higher-level leaf, so
1089                //   we are a sibling.
1090                // * `Sender::NewMemberCommit` with an inline `Remove(own_leaf)`:
1091                //   the sender is a sibling joining externally and the
1092                //   auto-Remove targets our previous leaf, so we are the
1093                //   sibling being resynced.
1094                #[cfg(feature = "virtual-clients-draft")]
1095                let (vc_commit_material, is_own_commit) = {
1096                    let vc_commit_material =
1097                        if is_sibling_vc_commit(commit, &sender, self.own_leaf_index()) {
1098                            self.load_vc_commit_material(provider, commit).await?
1099                        } else {
1100                            None
1101                        };
1102
1103                    let is_own_commit = is_own_commit && vc_commit_material.is_none();
1104
1105                    (vc_commit_material, is_own_commit)
1106                };
1107
1108                // An own Commit that did not match the pending commit above
1109                // cannot be staged when it carries an UpdatePath: we cannot
1110                // decrypt a path we encrypted to the other members. A Commit
1111                // without an UpdatePath carries no author-private material and
1112                // falls through to staging (a sibling's Commit without an
1113                // UpdatePath, or our own commit replayed after the pending
1114                // commit was cleared).
1115                if is_own_commit && commit.path.is_some() {
1116                    return Err(StageCommitError::OwnCommitMismatch.into());
1117                }
1118
1119                // A commit covering AppDataUpdate proposals cannot be staged
1120                // immediately: the proposals contain diffs in an
1121                // application-defined format, so the application has to
1122                // interpret them and supply the resulting dictionary entries
1123                // first. The verified content is handed back to the caller,
1124                // who resumes staging via `MlsGroup::stage_app_data_commit`.
1125                #[cfg(feature = "extensions-draft")]
1126                {
1127                    let app_data_update_proposals =
1128                        committed_app_data_update_proposals(commit, self.proposal_store());
1129                    if !app_data_update_proposals.is_empty() {
1130                        let unresolved_commit = UnresolvedAppDataCommit {
1131                            content,
1132                            proposals: app_data_update_proposals,
1133                            lifetime_policy,
1134                            #[cfg(feature = "virtual-clients-draft")]
1135                            vc_commit_material,
1136                        };
1137                        return Ok(ProcessedMessage::new(
1138                            self.group_id().clone(),
1139                            epoch,
1140                            sender,
1141                            authenticated_data,
1142                            ProcessedMessageContent::UnresolvedAppDataCommit(Box::new(
1143                                unresolved_commit,
1144                            )),
1145                            credential,
1146                            #[cfg(feature = "virtual-clients-draft")]
1147                            emulator_sender_leaf_index,
1148                        ));
1149                    }
1150                }
1151
1152                // Since this is a commit, we need to load the private key material we need for decryption.
1153                let (old_epoch_keypairs, leaf_node_keypairs) = self
1154                    .read_decryption_keypairs(provider, &self.own_leaf_nodes)
1155                    .await?;
1156
1157                let staged_commit = self
1158                    .stage_commit(
1159                        &content,
1160                        old_epoch_keypairs,
1161                        leaf_node_keypairs,
1162                        provider,
1163                        lifetime_policy,
1164                        #[cfg(feature = "virtual-clients-draft")]
1165                        vc_commit_material,
1166                    )
1167                    .await?;
1168
1169                ProcessedMessageContent::StagedCommitMessage(Box::new(staged_commit))
1170            }
1171        };
1172
1173        Ok(ProcessedMessage::new(
1174            self.group_id().clone(),
1175            epoch,
1176            sender,
1177            authenticated_data,
1178            content,
1179            credential,
1180            #[cfg(feature = "virtual-clients-draft")]
1181            emulator_sender_leaf_index,
1182        ))
1183    }
1184
1185    ///  - ValSem240
1186    ///  - ValSem241
1187    ///  - ValSem242
1188    ///  - ValSem244
1189    ///  - ValSem246 (as part of ValSem010)
1190    fn process_external_authenticated_content<Provider: OpenMlsProvider>(
1191        &self,
1192        provider: &Provider,
1193        content: AuthenticatedContent,
1194        credential: Credential,
1195    ) -> Result<ProcessedMessage, ProcessMessageError<Provider::StorageError>> {
1196        #[cfg(feature = "virtual-clients-draft")]
1197        let emulator_sender_leaf_index: Option<crate::binary_tree::LeafNodeIndex> = None;
1198        let sender = content.sender().clone();
1199        let data = content.authenticated_data().to_owned();
1200
1201        debug_assert!(matches!(sender, Sender::External(_)));
1202
1203        // https://validation.openmls.tech/#valn1501
1204        match content.content() {
1205            FramedContentBody::Application(_) => {
1206                Err(ProcessMessageError::UnauthorizedExternalApplicationMessage)
1207            }
1208            // TODO: https://validation.openmls.tech/#valn1502
1209            FramedContentBody::Proposal(Proposal::GroupContextExtensions(_)) => {
1210                let content = ProcessedMessageContent::ProposalMessage(Box::new(
1211                    QueuedProposal::from_authenticated_content_by_ref(
1212                        self.ciphersuite(),
1213                        provider.crypto(),
1214                        content,
1215                    )?,
1216                ));
1217                Ok(ProcessedMessage::new(
1218                    self.group_id().clone(),
1219                    self.context().epoch(),
1220                    sender,
1221                    data,
1222                    content,
1223                    credential,
1224                    #[cfg(feature = "virtual-clients-draft")]
1225                    emulator_sender_leaf_index,
1226                ))
1227            }
1228
1229            FramedContentBody::Proposal(Proposal::Remove(_)) => {
1230                let content = ProcessedMessageContent::ProposalMessage(Box::new(
1231                    QueuedProposal::from_authenticated_content_by_ref(
1232                        self.ciphersuite(),
1233                        provider.crypto(),
1234                        content,
1235                    )?,
1236                ));
1237                Ok(ProcessedMessage::new(
1238                    self.group_id().clone(),
1239                    self.context().epoch(),
1240                    sender,
1241                    data,
1242                    content,
1243                    credential,
1244                    #[cfg(feature = "virtual-clients-draft")]
1245                    emulator_sender_leaf_index,
1246                ))
1247            }
1248            FramedContentBody::Proposal(Proposal::Add(_)) => {
1249                let content = ProcessedMessageContent::ProposalMessage(Box::new(
1250                    QueuedProposal::from_authenticated_content_by_ref(
1251                        self.ciphersuite(),
1252                        provider.crypto(),
1253                        content,
1254                    )?,
1255                ));
1256                Ok(ProcessedMessage::new(
1257                    self.group_id().clone(),
1258                    self.context().epoch(),
1259                    sender,
1260                    data,
1261                    content,
1262                    credential,
1263                    #[cfg(feature = "virtual-clients-draft")]
1264                    emulator_sender_leaf_index,
1265                ))
1266            }
1267            // RFC 9420 §12.1.8 permits external senders to send PreSharedKey
1268            // proposals.
1269            FramedContentBody::Proposal(Proposal::PreSharedKey(_)) => {
1270                let content = ProcessedMessageContent::ProposalMessage(Box::new(
1271                    QueuedProposal::from_authenticated_content_by_ref(
1272                        self.ciphersuite(),
1273                        provider.crypto(),
1274                        content,
1275                    )?,
1276                ));
1277                Ok(ProcessedMessage::new(
1278                    self.group_id().clone(),
1279                    self.context().epoch(),
1280                    sender,
1281                    data,
1282                    content,
1283                    credential,
1284                    #[cfg(feature = "virtual-clients-draft")]
1285                    emulator_sender_leaf_index,
1286                ))
1287            }
1288            // RFC 9420 §12.1.8.2 permits external senders to send ReInit
1289            // proposals.
1290            FramedContentBody::Proposal(Proposal::ReInit(_)) => {
1291                let content = ProcessedMessageContent::ProposalMessage(Box::new(
1292                    QueuedProposal::from_authenticated_content_by_ref(
1293                        self.ciphersuite(),
1294                        provider.crypto(),
1295                        content,
1296                    )?,
1297                ));
1298                Ok(ProcessedMessage::new(
1299                    self.group_id().clone(),
1300                    self.context().epoch(),
1301                    sender,
1302                    data,
1303                    content,
1304                    credential,
1305                    #[cfg(feature = "virtual-clients-draft")]
1306                    emulator_sender_leaf_index,
1307                ))
1308            }
1309            // TODO #151/#106
1310            FramedContentBody::Proposal(_) => Err(ProcessMessageError::UnsupportedProposalType),
1311            FramedContentBody::Commit(_) => {
1312                Err(ProcessMessageError::UnauthorizedExternalCommitMessage)
1313            }
1314        }
1315    }
1316
1317    /// Performs framing validation and, if necessary, decrypts the given message.
1318    ///
1319    /// Returns the [`InboundDecryptionResult`] if processing is successful, or a
1320    /// [`ValidationError`] if it is not.
1321    ///
1322    /// Checks the following semantic validation:
1323    ///  - ValSem002
1324    ///  - ValSem003
1325    ///  - ValSem006
1326    ///  - ValSem007 MembershipTag presence
1327    ///  - https://validation.openmls.tech/#valn1202
1328    pub(crate) fn decrypt_message(
1329        &mut self,
1330        crypto: &impl OpenMlsCrypto,
1331        message: ProtocolMessage,
1332        sender_ratchet_configuration: &SenderRatchetConfiguration,
1333        #[cfg(feature = "virtual-clients-draft")] emulator_ctx: Option<
1334            &crate::framing::EmulatorReuseGuardCtx<'_>,
1335        >,
1336    ) -> Result<InboundDecryptionResult, ValidationError> {
1337        // Checks the following semantic validation:
1338        //  - ValSem002
1339        //  - ValSem003
1340        self.public_group.validate_framing(&message)?;
1341
1342        let epoch = message.epoch();
1343
1344        // Checks the following semantic validation:
1345        //  - ValSem006
1346        //  - ValSem007 MembershipTag presence
1347        match message {
1348            ProtocolMessage::PublicMessage(public_message) => {
1349                // If the message is older than the current epoch, we need to fetch the correct secret tree first.
1350                let message_secrets =
1351                    self.message_secrets_for_epoch(epoch).map_err(|e| match e {
1352                        SecretTreeError::TooDistantInThePast => ValidationError::NoPastEpochData,
1353                        _ => LibraryError::custom(
1354                            "Unexpected error while retrieving message secrets for epoch.",
1355                        )
1356                        .into(),
1357                    })?;
1358                DecryptedMessage::from_inbound_public_message(
1359                    *public_message,
1360                    message_secrets,
1361                    message_secrets.serialized_context().to_vec(),
1362                    crypto,
1363                    self.ciphersuite(),
1364                )
1365                .map(|message| InboundDecryptionResult::Decrypted {
1366                    message,
1367                    ratchet_update: None,
1368                })
1369            }
1370            ProtocolMessage::PrivateMessage(ciphertext) => {
1371                // If the message is older than the current epoch, we need to fetch the correct secret tree first
1372                DecryptedMessage::from_inbound_ciphertext(
1373                    ciphertext,
1374                    crypto,
1375                    self,
1376                    sender_ratchet_configuration,
1377                    #[cfg(feature = "virtual-clients-draft")]
1378                    emulator_ctx,
1379                )
1380            }
1381        }
1382    }
1383}
1384
1385/// Collects the AppDataUpdate proposals covered by a commit, sorted by
1386/// component id.
1387///
1388/// Proposals sent by reference are resolved from the proposal store. A
1389/// reference that cannot be resolved is skipped here: staging fails on it
1390/// later with the regular missing-proposal error, so it does not need to be
1391/// surfaced at detection time.
1392#[cfg(feature = "extensions-draft")]
1393pub(crate) fn committed_app_data_update_proposals(
1394    commit: &Commit,
1395    proposal_store: &ProposalStore,
1396) -> Vec<AppDataUpdateProposal> {
1397    use crate::messages::proposals::ProposalOrRef;
1398
1399    let mut proposals: Vec<AppDataUpdateProposal> = commit
1400        .proposals
1401        .iter()
1402        .filter_map(|proposal_or_ref| match proposal_or_ref {
1403            ProposalOrRef::Proposal(proposal) => match proposal.as_ref() {
1404                Proposal::AppDataUpdate(proposal) => Some(proposal.as_ref().clone()),
1405                _ => None,
1406            },
1407            ProposalOrRef::Reference(reference) => proposal_store
1408                .proposals()
1409                .find(|queued_proposal| {
1410                    queued_proposal.proposal_reference_ref() == reference.as_ref()
1411                })
1412                .and_then(|queued_proposal| match queued_proposal.proposal() {
1413                    Proposal::AppDataUpdate(proposal) => Some(proposal.as_ref().clone()),
1414                    _ => None,
1415                }),
1416        })
1417        .collect();
1418
1419    proposals.sort_by_key(|proposal| proposal.component_id());
1420    proposals
1421}
1422
1423/// Determines from the commit's shape whether the receiver is a sibling virtual
1424/// client of the sender of a virtual-clients commit.
1425///
1426/// Returns `true` for:
1427///   * own-leaf commits (`Sender::Member(idx)` with `idx == own_leaf_index`),
1428///     where receiver and sender share the higher-level leaf
1429///   * sibling-resync external commits (`Sender::NewMemberCommit` whose
1430///     proposal list inlines a `Remove` of `own_leaf_index`.
1431///
1432/// `false` for everything else.
1433#[cfg(feature = "virtual-clients-draft")]
1434fn is_sibling_vc_commit(
1435    commit: &Commit,
1436    sender: &super::Sender,
1437    own_leaf_index: crate::binary_tree::LeafNodeIndex,
1438) -> bool {
1439    use crate::messages::proposals::{Proposal, ProposalOrRef};
1440
1441    match sender {
1442        super::Sender::Member(idx) => *idx == own_leaf_index,
1443        super::Sender::NewMemberCommit => commit.proposals.iter().any(|p| {
1444            matches!(
1445                p,
1446                ProposalOrRef::Proposal(boxed)
1447                    if matches!(boxed.as_ref(), Proposal::Remove(r) if r.removed() == own_leaf_index)
1448            )
1449        }),
1450        _ => false,
1451    }
1452}