Skip to main content

openmls/group/mls_group/
creation.rs

1use errors::NewGroupError;
2use openmls_traits::{crypto::OpenMlsCrypto, storage::StorageProvider as StorageProviderTrait};
3
4use super::{builder::MlsGroupBuilder, *};
5use crate::{
6    credentials::CredentialWithKey,
7    extensions::Extensions,
8    group::{
9        commit_builder::external_commits::ExternalCommitBuilder,
10        errors::{ExportSecretError, ExternalCommitError, WelcomeError},
11        reinit::ReInitInfo,
12    },
13    key_packages::KeyPackage,
14    messages::{
15        group_info::{GroupInfo, VerifiableGroupInfo},
16        Welcome,
17    },
18    schedule::{
19        psk::{
20            load_psks, store::ResumptionPskStore, PreSharedKeyId, Psk, ResumptionPsk,
21            ResumptionPskUsage,
22        },
23        EpochSecretsResult,
24    },
25    storage::OpenMlsProvider,
26    treesync::{
27        errors::{DerivePathError, PublicTreeError},
28        node::leaf_node::{Capabilities, LeafNodeParameters},
29        RatchetTreeIn,
30    },
31};
32
33#[cfg(feature = "virtual-clients-draft")]
34use crate::{
35    ciphersuite::hash_ref::KeyPackageRef,
36    component::ComponentId,
37    components::vc_derivation_info::{
38        load_vc_epoch_state_and_tree, register_vc_derivation_epoch,
39        write_vc_emulation_binding_with_pruning, DerivationInfoTbe, EpochId,
40        RetainedKeyPackageMaterial, VcDerivationEpochParams, VcDerivationEpochState,
41        VcWelcomeMaterial, VirtualClientOperationType, VirtualClientsError,
42    },
43    framing::{mls_auth_content::AuthenticatedContent, ProtocolMessage, SafeAad, Sender},
44    group::{
45        config::PastEpochDeletionPolicy,
46        errors::{
47            ProcessMessageError, StageCommitError, VcExternalCommitJoinError,
48            VcGroupCreationJoinError,
49        },
50        mls_group::processing::{
51            committed_app_data_update_proposals, AppDataDictionaryUpdater, AppDataUpdates,
52        },
53        public_group::{errors::ApplyAppDataUpdateError, PublicGroup},
54    },
55    key_packages::has_last_resort_marker,
56    messages::proposals::{AppDataUpdateProposal, AppEphemeralProposal, Proposal, ProposalOrRef},
57    prelude::mls_content::FramedContentBody,
58    schedule::{EpochSecrets, InitSecret},
59    treesync::node::leaf_node::LeafNodeSource,
60};
61
62impl MlsGroup {
63    // === Group creation ===
64
65    /// Creates a builder which can be used to configure and build
66    /// a new [`MlsGroup`].
67    pub fn builder() -> MlsGroupBuilder {
68        MlsGroupBuilder::new()
69    }
70
71    /// Creates a new group with the creator as the only member (and a random
72    /// group ID).
73    #[openmls_traits::maybe_async]
74    pub async fn new<Provider: OpenMlsProvider>(
75        provider: &Provider,
76        signer: &impl Signer,
77        mls_group_create_config: &MlsGroupCreateConfig,
78        credential_with_key: CredentialWithKey,
79    ) -> Result<Self, NewGroupError<Provider::StorageError>> {
80        MlsGroupBuilder::new()
81            .build_internal(
82                provider,
83                signer,
84                credential_with_key,
85                Some(mls_group_create_config.clone()),
86            )
87            .await
88    }
89
90    /// Creates a new group with a given group ID with the creator as the only
91    /// member.
92    #[openmls_traits::maybe_async]
93    pub async fn new_with_group_id<Provider: OpenMlsProvider>(
94        provider: &Provider,
95        signer: &impl Signer,
96        mls_group_create_config: &MlsGroupCreateConfig,
97        group_id: GroupId,
98        credential_with_key: CredentialWithKey,
99    ) -> Result<Self, NewGroupError<Provider::StorageError>> {
100        MlsGroupBuilder::new()
101            .with_group_id(group_id)
102            .build_internal(
103                provider,
104                signer,
105                credential_with_key,
106                Some(mls_group_create_config.clone()),
107            )
108            .await
109    }
110
111    /// Join an existing group through an External Commit.
112    /// The resulting [`MlsGroup`] instance starts off with a pending
113    /// commit (the external commit, which adds this client to the group).
114    /// Merging this commit is necessary for this [`MlsGroup`] instance to
115    /// function properly, as, for example, this client is not yet part of the
116    /// tree. As a result, it is not possible to clear the pending commit. If
117    /// the external commit was rejected due to an epoch change, the
118    /// [`MlsGroup`] instance has to be discarded and a new one has to be
119    /// created using this function based on the latest `ratchet_tree` and
120    /// group info. For more information on the external init process,
121    /// please see Section 11.2.1 in the MLS specification.
122    ///
123    /// Note: If there is a group member in the group with the same identity as
124    /// us, this will create a remove proposal.
125    #[allow(clippy::too_many_arguments)]
126    #[deprecated(
127        since = "0.7.1",
128        note = "Use the `MlsGroup::external_commit_builder` instead."
129    )]
130    #[openmls_traits::maybe_async]
131    pub async fn join_by_external_commit<Provider: OpenMlsProvider>(
132        provider: &Provider,
133        signer: &impl Signer,
134        ratchet_tree: Option<RatchetTreeIn>,
135        verifiable_group_info: VerifiableGroupInfo,
136        mls_group_config: &MlsGroupJoinConfig,
137        capabilities: Option<Capabilities>,
138        extensions: Option<Extensions<LeafNode>>,
139        aad: &[u8],
140        credential_with_key: CredentialWithKey,
141    ) -> Result<(Self, MlsMessageOut, Option<GroupInfo>), ExternalCommitError<Provider::StorageError>>
142    {
143        // `None` has to stay unset rather than become an empty `Capabilities`,
144        // so the leaf's own capabilities get derived from it.
145        let mut leaf_node_parameters =
146            LeafNodeParameters::builder().with_extensions(extensions.unwrap_or_default());
147        if let Some(capabilities) = capabilities {
148            leaf_node_parameters = leaf_node_parameters.with_capabilities(capabilities);
149        }
150        let leaf_node_parameters = leaf_node_parameters.build();
151
152        let mut external_commit_builder = ExternalCommitBuilder::new()
153            .with_aad(aad.to_vec())
154            .with_config(mls_group_config.clone());
155
156        if let Some(ratchet_tree) = ratchet_tree {
157            external_commit_builder = external_commit_builder.with_ratchet_tree(ratchet_tree)
158        }
159
160        let (mls_group, commit_message_bundle) = external_commit_builder
161            .build_group(provider, verifiable_group_info, credential_with_key)?
162            .leaf_node_parameters(leaf_node_parameters)
163            .load_psks(provider.storage())
164            .await
165            .map_err(|e| {
166                log::error!("Error loading PSKs for external commit: {e:?}");
167                LibraryError::custom("Error loading PSKs for external commit")
168            })?
169            .build(provider.rand(), provider.crypto(), signer, |_| true)?
170            .finalize(provider)
171            .await?;
172
173        let (commit, _, group_info) = commit_message_bundle.into_contents();
174
175        Ok((mls_group, commit, group_info))
176    }
177}
178
179impl ProcessedWelcome {
180    /// Creates a new processed [`Welcome`] message , which can be
181    /// inspected before creating a [`StagedWelcome`].
182    ///
183    /// This does not require a ratchet tree yet.
184    ///
185    /// [`Welcome`]: crate::messages::Welcome
186    #[openmls_traits::maybe_async]
187    pub async fn new_from_welcome<Provider: OpenMlsProvider>(
188        provider: &Provider,
189        mls_group_config: &MlsGroupJoinConfig,
190        welcome: Welcome,
191    ) -> Result<Self, WelcomeError<Provider::StorageError>> {
192        Self::new_from_welcome_inner(provider, mls_group_config, welcome, None).await
193    }
194
195    /// Like [`ProcessedWelcome::new_from_welcome`], but allows injecting a
196    /// resumption PSK secret that is not held in storage.
197    ///
198    /// This is used for subgroup branching (RFC 9420 §11.3) and
199    /// reinitialization (RFC 9420 §11.2): the branch resp. reinit PSK secret
200    /// comes from another group. See
201    /// [`StagedWelcome::build_from_branch`] and
202    /// [`StagedWelcome::build_from_reinit`].
203    #[openmls_traits::maybe_async]
204    pub(crate) async fn new_from_welcome_inner<Provider: OpenMlsProvider>(
205        provider: &Provider,
206        mls_group_config: &MlsGroupJoinConfig,
207        welcome: Welcome,
208        resumption_info: Option<&ResumptionInfo>,
209    ) -> Result<Self, WelcomeError<Provider::StorageError>> {
210        let (resumption_psk_store, key_material, group_secrets) =
211            decrypt_group_secrets(provider, mls_group_config, &welcome).await?;
212
213        finish_processed_welcome(
214            provider,
215            mls_group_config,
216            welcome.ciphersuite(),
217            resumption_psk_store,
218            key_material,
219            group_secrets,
220            &welcome,
221            resumption_info,
222        )
223        .await
224    }
225
226    /// Get a reference to the GroupInfo in this Welcome message.
227    ///
228    /// **NOTE:** The group info contains **unverified** values. Use with caution.
229    pub fn unverified_group_info(&self) -> &VerifiableGroupInfo {
230        &self.verifiable_group_info
231    }
232
233    /// Get a reference to the PSKs in this Welcome message.
234    ///
235    /// **NOTE:** The group info contains **unverified** values. Use with caution.
236    pub fn psks(&self) -> &[PreSharedKeyId] {
237        &self.group_secrets.psks
238    }
239
240    /// Consume the `ProcessedWelcome` and combine it with the ratchet tree into
241    /// a `StagedWelcome`.
242    #[openmls_traits::maybe_async]
243    pub async fn into_staged_welcome<Provider: OpenMlsProvider>(
244        self,
245        provider: &Provider,
246        ratchet_tree: Option<RatchetTreeIn>,
247    ) -> Result<StagedWelcome, WelcomeError<Provider::StorageError>> {
248        self.into_staged_welcome_inner(
249            provider,
250            ratchet_tree,
251            LeafNodeLifetimePolicy::Verify,
252            false,
253        )
254        .await
255    }
256
257    /// Consume the `ProcessedWelcome` and combine it with the ratchet tree into
258    /// a `StagedWelcome`.
259    #[openmls_traits::maybe_async]
260    pub(crate) async fn into_staged_welcome_inner<Provider: OpenMlsProvider>(
261        mut self,
262        provider: &Provider,
263        ratchet_tree: Option<RatchetTreeIn>,
264        validate_lifetimes: LeafNodeLifetimePolicy,
265        replace_old_group: bool,
266    ) -> Result<StagedWelcome, WelcomeError<Provider::StorageError>> {
267        // Check if we need to replace an old group
268        if !replace_old_group
269            && MlsGroup::load(provider.storage(), self.verifiable_group_info.group_id())
270                .await
271                .map_err(WelcomeError::StorageError)?
272                .is_some()
273        {
274            return Err(WelcomeError::GroupAlreadyExists);
275        }
276
277        // Build the ratchet tree and group
278
279        // Set nodes either from the extension or from the `nodes_option`.
280        // If we got a ratchet tree extension in the welcome, we enable it for
281        // this group. Note that this is not strictly necessary. But there's
282        // currently no other mechanism to enable the extension.
283        let ratchet_tree = match self.verifiable_group_info.extensions().ratchet_tree() {
284            Some(extension) => extension.ratchet_tree().clone(),
285            None => match ratchet_tree {
286                Some(ratchet_tree) => ratchet_tree,
287                None => return Err(WelcomeError::MissingRatchetTree),
288            },
289        };
290
291        // Since there is currently only the external pub extension, there is no
292        // group info extension of interest here.
293        let (public_group, _group_info_extensions) = PublicGroup::from_ratchet_tree(
294            provider.crypto(),
295            ratchet_tree,
296            self.verifiable_group_info.clone(),
297            ProposalStore::new(),
298            validate_lifetimes,
299        )?;
300
301        // Find our own leaf in the tree. On the bundle path this is the leaf
302        // whose signature key matches the local KeyPackage. On the
303        // virtual-client path there is no local signature key, so the leaf is
304        // located by its derived encryption key and validated against the
305        // derivation epoch's derivation info.
306        let own_leaf_index = match &self.key_material.inner() {
307            WelcomeKeyMaterialInner::KeyPackage(key_package_bundle) => {
308                // Check that the leaf node of the added key package supports all extensions in
309                // the group context.
310                // https://validation.openmls.tech/#valn1415
311                let added_leaf_supports_all_group_context_extensions = public_group
312                    .group_context()
313                    .extensions()
314                    .iter()
315                    .all(|extension| {
316                        key_package_bundle
317                            .key_package
318                            .leaf_node()
319                            .supports_extension(&extension.extension_type())
320                    });
321                if !added_leaf_supports_all_group_context_extensions {
322                    return Err(WelcomeError::UnsupportedExtensions);
323                }
324
325                public_group
326                    .members()
327                    .find_map(|m| {
328                        if m.signature_key
329                            == key_package_bundle
330                                .key_package()
331                                .leaf_node()
332                                .signature_key()
333                                .as_slice()
334                        {
335                            Some(m.index)
336                        } else {
337                            None
338                        }
339                    })
340                    .ok_or(WelcomeError::PublicTreeError(
341                        PublicTreeError::MalformedTree,
342                    ))?
343            }
344            #[cfg(feature = "virtual-clients-draft")]
345            WelcomeKeyMaterialInner::VirtualClient(material) => {
346                find_and_validate_vc_own_leaf(provider, &public_group, material).await?
347            }
348        };
349
350        struct KeyScheduleResult {
351            group_epoch_secrets: GroupEpochSecrets,
352            message_secrets: MessageSecrets,
353            #[cfg(feature = "extensions-draft")]
354            application_exporter: ApplicationExportSecret,
355        }
356        let KeyScheduleResult {
357            group_epoch_secrets,
358            message_secrets,
359            #[cfg(feature = "extensions-draft")]
360                application_exporter: application_export_secret,
361        } = {
362            let serialized_group_context = public_group
363                .group_context()
364                .tls_serialize_detached()
365                .map_err(LibraryError::missing_bound_check)?;
366
367            let EpochSecretsResult {
368                epoch_secrets,
369                #[cfg(feature = "extensions-draft")]
370                application_exporter,
371            } = self.epoch_secrets;
372
373            let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
374                serialized_group_context,
375                public_group.tree_size(),
376                own_leaf_index,
377            );
378
379            KeyScheduleResult {
380                group_epoch_secrets,
381                message_secrets,
382                #[cfg(feature = "extensions-draft")]
383                application_exporter,
384            }
385        };
386
387        let confirmation_tag = message_secrets
388            .confirmation_key()
389            .tag(
390                provider.crypto(),
391                self.ciphersuite,
392                public_group.group_context().confirmed_transcript_hash(),
393            )
394            .map_err(LibraryError::unexpected_crypto_error)?;
395
396        // Verify confirmation tag
397        // https://validation.openmls.tech/#valn1411
398        if &confirmation_tag != public_group.confirmation_tag() {
399            log::error!("Confirmation tag mismatch");
400            log_crypto!(trace, "  Got:      {:x?}", confirmation_tag);
401            log_crypto!(trace, "  Expected: {:x?}", public_group.confirmation_tag());
402
403            // in some tests we need to be able to proceed despite the tag being wrong,
404            // e.g. to test whether a later validation check is performed correctly.
405            if !crate::skip_validation::is_disabled::confirmation_tag() {
406                return Err(WelcomeError::ConfirmationTagMismatch);
407            }
408        }
409
410        let message_secrets_store = MessageSecretsStore::new_with_secret(
411            &PastEpochDeletionPolicy::MaxEpochs(0),
412            message_secrets,
413        );
414
415        // Extract and store the resumption PSK for the current epoch.
416        let resumption_psk = group_epoch_secrets.resumption_psk();
417        self.resumption_psk_store
418            .add(public_group.group_context().epoch(), resumption_psk.clone());
419
420        let welcome_sender_index = self.verifiable_group_info.signer();
421        let path_keypairs = if let Some(path_secret) = self.group_secrets.path_secret {
422            let (path_keypairs, _commit_secret) = public_group
423                .derive_path_secrets(
424                    provider.crypto(),
425                    self.ciphersuite,
426                    path_secret,
427                    welcome_sender_index,
428                    own_leaf_index,
429                )
430                .map_err(|e| match e {
431                    DerivePathError::LibraryError(e) => e.into(),
432                    DerivePathError::PublicKeyMismatch => {
433                        WelcomeError::PublicTreeError(PublicTreeError::PublicKeyMismatch)
434                    }
435                })?;
436            Some(path_keypairs)
437        } else {
438            None
439        };
440
441        let staged_welcome = StagedWelcome {
442            mls_group_config: self.mls_group_config,
443            public_group,
444            group_epoch_secrets,
445            own_leaf_index,
446            message_secrets_store,
447            #[cfg(feature = "extensions-draft")]
448            application_export_secret,
449            resumption_psk_store: self.resumption_psk_store,
450            verifiable_group_info: self.verifiable_group_info,
451            key_material: self.key_material,
452            path_keypairs,
453            #[cfg(feature = "virtual-clients-draft")]
454            emulation_group: false,
455        };
456
457        Ok(staged_welcome)
458    }
459
460    /// Exports a secret from the epoch of the group that is joined
461    /// using this [`ProcessedWelcome`].
462    /// Returns [`ExportSecretError::KeyLengthTooLong`] if the requested
463    /// key length is too long.
464    pub fn export_secret<CryptoProvider: OpenMlsCrypto>(
465        &self,
466        crypto: &CryptoProvider,
467        label: &str,
468        context: &[u8],
469        key_length: usize,
470    ) -> Result<ExportedSecret<ProcessedWelcomeExport>, ExportSecretError> {
471        if key_length > u16::MAX as usize {
472            log::error!("Got a key that is larger than u16::MAX");
473            return Err(ExportSecretError::KeyLengthTooLong);
474        }
475
476        Ok(ExportedSecret::new(
477            self.epoch_secrets
478                .epoch_secrets
479                .exporter_secret()
480                .derive_exported_secret(self.ciphersuite, crypto, label, context, key_length)
481                .map_err(LibraryError::unexpected_crypto_error)?,
482        ))
483    }
484
485    /// Retrieve a reference to the own [`KeyPackage`] that was retrieved from local storage as
486    /// part of [`Welcome`] processing, and is used to build the group
487    pub fn own_key_package(&self) -> Option<&KeyPackage> {
488        self.key_material
489            .key_package_bundle()
490            .map(|bundle| bundle.key_package())
491    }
492}
493
494impl StagedWelcome {
495    /// Creates a new staged welcome from a [`Welcome`] message. Returns an error
496    /// ([`WelcomeError::NoMatchingKeyPackage`]) if no [`KeyPackage`]
497    /// can be found.
498    /// Note: calling this function will consume the key material for decrypting the [`Welcome`]
499    /// message, even if the caller does not turn the [`StagedWelcome`] into an [`MlsGroup`].
500    /// A virtual client's key material is only consumed by [`Self::into_group`].
501    ///
502    /// [`Welcome`]: crate::messages::Welcome
503    #[openmls_traits::maybe_async]
504    pub async fn new_from_welcome<Provider: OpenMlsProvider>(
505        provider: &Provider,
506        mls_group_config: &MlsGroupJoinConfig,
507        welcome: Welcome,
508        ratchet_tree: Option<RatchetTreeIn>,
509    ) -> Result<Self, WelcomeError<Provider::StorageError>> {
510        let processed_welcome =
511            ProcessedWelcome::new_from_welcome(provider, mls_group_config, welcome).await?;
512
513        processed_welcome
514            .into_staged_welcome(provider, ratchet_tree)
515            .await
516    }
517
518    /// Similar to [`StagedWelcome::new_from_welcome`] but as a builder.
519    ///
520    /// The builder allows to set the ratchet tree, skip leaf node lifetime
521    /// validation, and get the [`ProcessedWelcome`] for inspection before staging.
522    #[openmls_traits::maybe_async]
523    pub async fn build_from_welcome<'a, Provider: OpenMlsProvider>(
524        provider: &'a Provider,
525        mls_group_config: &MlsGroupJoinConfig,
526        welcome: Welcome,
527    ) -> Result<JoinBuilder<'a, Provider>, WelcomeError<Provider::StorageError>> {
528        let processed_welcome =
529            ProcessedWelcome::new_from_welcome(provider, mls_group_config, welcome).await?;
530
531        // processed_welcome.into_staged_welcome(provider, ratchet_tree)
532        Ok(JoinBuilder::new(provider, processed_welcome))
533    }
534
535    /// Builder to create a [`StagedWelcome`] for a subgroup branched from a
536    /// parent group, as described in [RFC 9420 §11.3].
537    ///
538    /// The parent group's parameters are provided via `branch_info`, which the
539    /// parent exports with
540    /// [`MlsGroup::branch_info`](crate::group::MlsGroup::branch_info).
541    ///
542    /// In addition to the regular [`StagedWelcome::build_from_welcome`]
543    /// processing, this uses the parent's resumption PSK secret (which is
544    /// required to derive the subgroup's key schedule from the branch PSK) and
545    /// enforces the receiver-side checks the RFC mandates when joining a branched
546    /// subgroup.
547    ///
548    /// The branch PSK carried in the `Welcome` must reference the same parent
549    /// group and epoch as the supplied `branch_info`.
550    ///
551    /// The remaining checks run when [`JoinBuilder::build`] is called:
552    ///
553    /// * the protocol version and ciphersuite match the parent group,
554    /// * the subgroup is at epoch 1, and
555    /// * every member of the subgroup matches a member of the parent group
556    ///   (unless disabled via [`JoinBuilder::check_members`]).
557    ///
558    /// Matching members is left to the application by the RFC; here we use
559    /// credential equality for equivalent identifiers.
560    ///
561    /// If the receiver does not yet know which parent epoch the branch was taken
562    /// from (its own view of the parent group may have advanced), use
563    /// [`StagedWelcome::process_resuming_welcome`] to read the parent reference
564    /// from the `Welcome` first and then pick the matching `branch_info`.
565    /// This one-shot method is a convenience for callers who already know the
566    /// parent and epoch.
567    ///
568    /// [RFC 9420 §11.3]: https://www.rfc-editor.org/rfc/rfc9420.html#name-subgroup-branching
569    #[openmls_traits::maybe_async]
570    pub async fn build_from_branch<'a, Provider: OpenMlsProvider>(
571        provider: &'a Provider,
572        mls_group_config: &MlsGroupJoinConfig,
573        welcome: Welcome,
574        branch_info: BranchInfo,
575    ) -> Result<JoinBuilder<'a, Provider>, WelcomeError<Provider::StorageError>> {
576        Self::process_resuming_welcome(provider, mls_group_config, welcome)
577            .await?
578            .build_from_branch(provider, branch_info)
579            .await
580    }
581
582    /// Builder to create a [`StagedWelcome`] for a reinit of a
583    /// predecessor group, as described in [RFC 9420 §11.2].
584    ///
585    /// The predecessor group's parameters are provided via `reinit_info`, which the
586    /// predecessor exports with
587    /// [`MlsGroup::reinit_info`](crate::group::MlsGroup::reinit_info).
588    ///
589    /// In addition to the regular [`StagedWelcome::build_from_welcome`]
590    /// processing, this uses the predecessor's resumption PSK secret (which is
591    /// required to derive the new key schedule from the reinit PSK) and
592    /// enforces the receiver-side checks the RFC mandates when joining a
593    /// reinitialized group.
594    ///
595    /// The reinit PSK carried in the `Welcome` must reference the same predecessor
596    /// group and epoch as the supplied `reinit_info`.
597    ///
598    /// The remaining checks run when [`JoinBuilder::build`] is called:
599    ///
600    /// * the protocol version, ciphersuite, group_id, and extensions match the
601    ///   reinit proposal in the predecessor,
602    /// * the welcome is at epoch 1, and
603    /// * the set of member credentials is identical to the predecessor
604    ///   (unless disabled via [`JoinBuilder::check_members`]).
605    ///
606    /// Matching members is left to the application by the RFC; here we use
607    /// credential equality for equivalent identifiers.
608    ///
609    /// If the receiver does not yet know which predecessor group is being reinitialized,
610    /// use [`StagedWelcome::process_resuming_welcome`] to read the psk_id
611    /// from the `Welcome` first and then pick the matching `reinit_info`.
612    /// This one-shot method is a convenience for callers that already know the
613    /// predecessor.
614    ///
615    /// [RFC 9420 §11.2]: https://www.rfc-editor.org/rfc/rfc9420.html#name-reinitialization
616    #[openmls_traits::maybe_async]
617    pub async fn build_from_reinit<'a, Provider: OpenMlsProvider>(
618        provider: &'a Provider,
619        mls_group_config: &MlsGroupJoinConfig,
620        welcome: Welcome,
621        reinit_info: ReInitInfo,
622    ) -> Result<JoinBuilder<'a, Provider>, WelcomeError<Provider::StorageError>> {
623        Self::process_resuming_welcome(provider, mls_group_config, welcome)
624            .await?
625            .build_from_reinit(provider, reinit_info)
626            .await
627    }
628
629    /// Decrypt a `Welcome`'s group secrets so its branch or reinit reference can be
630    /// inspected before selecting the matching [`BranchInfo`] or [`ReInitInfo`].
631    ///
632    /// Call [`PendingResumingWelcome::required_resumption_secret`] to read the parent
633    /// or predecessor `(group_id, epoch)` the group derives from (RFC 9420 §8.4),
634    /// select the [`BranchInfo`] or [`ReInitInfo`] for that source, then finish
635    /// with [`PendingResumingWelcome::build_from_branch`] or [`PendingResumingWelcome::build_from_reinit`].
636    ///
637    /// If [`PendingResumingWelcome::required_resumption_secret`] returns [`None`] the [`Welcome`]
638    /// is not a branch or reinit welcome and must be completed with [`PendingResumingWelcome::build`].
639    #[openmls_traits::maybe_async]
640    pub async fn process_resuming_welcome<Provider: OpenMlsProvider>(
641        provider: &Provider,
642        mls_group_config: &MlsGroupJoinConfig,
643        welcome: Welcome,
644    ) -> Result<PendingResumingWelcome, WelcomeError<Provider::StorageError>> {
645        let (resumption_psk_store, key_material, group_secrets) =
646            decrypt_group_secrets(provider, mls_group_config, &welcome).await?;
647
648        Ok(PendingResumingWelcome {
649            mls_group_config: mls_group_config.clone(),
650            ciphersuite: welcome.ciphersuite(),
651            welcome,
652            resumption_psk_store,
653            key_material,
654            group_secrets,
655        })
656    }
657
658    /// Returns the [`LeafNodeIndex`] of the group member that authored the [`Welcome`] message.
659    ///
660    /// [`Welcome`]: crate::messages::Welcome
661    pub fn welcome_sender_index(&self) -> LeafNodeIndex {
662        self.verifiable_group_info.signer()
663    }
664
665    /// Returns the [`LeafNode`] of the group member that authored the [`Welcome`] message.
666    ///
667    /// [`Welcome`]: crate::messages::Welcome
668    pub fn welcome_sender(&self) -> Result<&LeafNode, LibraryError> {
669        let sender_index = self.welcome_sender_index();
670        self.public_group
671            .leaf(sender_index)
672            .ok_or_else(|| LibraryError::custom("no leaf with given welcome sender index exists"))
673    }
674
675    /// Returns the leaf index of the client in this welcome's [`PublicGroup`].
676    pub fn own_leaf_index(&self) -> LeafNodeIndex {
677        self.own_leaf_index
678    }
679
680    /// Returns the leaf node of the client in this welcome's [`PublicGroup`].
681    pub fn own_leaf_node(&self) -> Option<&LeafNode> {
682        self.public_group.leaf(self.own_leaf_index())
683    }
684
685    /// Get the [`GroupContext`] of this welcome's [`PublicGroup`].
686    pub fn group_context(&self) -> &GroupContext {
687        self.public_group.group_context()
688    }
689
690    /// Get an iterator over all [`Member`]s of this welcome's [`PublicGroup`].
691    pub fn members(&self) -> impl Iterator<Item = Member> + '_ {
692        self.public_group.members()
693    }
694
695    /// Get the [`ApplicationExportSecret`] of this welcome.
696    #[cfg(feature = "extensions-draft")]
697    pub fn application_export_secret(&self) -> &ApplicationExportSecret {
698        &self.application_export_secret
699    }
700
701    /// Join the group as an emulation group of a virtual client. See
702    /// [`MlsGroupCreateConfigBuilder::emulation_group`] for what an emulation
703    /// group is.
704    ///
705    /// Nothing on the wire marks a group as an emulation group, so a joiner has
706    /// to set this itself. Joining an emulation group without it leaves the
707    /// virtual client's secrets underived.
708    ///
709    /// [`MlsGroupCreateConfigBuilder::emulation_group`]: crate::group::MlsGroupCreateConfigBuilder::emulation_group
710    #[cfg(feature = "virtual-clients-draft")]
711    pub fn emulation_group(mut self, emulation_group: bool) -> Self {
712        self.emulation_group = emulation_group;
713        self
714    }
715
716    /// Consumes the [`StagedWelcome`] and returns the respective [`MlsGroup`].
717    #[openmls_traits::maybe_async]
718    pub async fn into_group<Provider: OpenMlsProvider>(
719        self,
720        provider: &Provider,
721    ) -> Result<MlsGroup, WelcomeError<Provider::StorageError>> {
722        // If we got a path secret, derive the path (which also checks if the
723        // public keys match) and store the derived keys in the key store.
724        let group_keypairs = if let Some(path_keypairs) = self.path_keypairs {
725            let mut keypairs = vec![self.key_material.encryption_key_pair()];
726            keypairs.extend_from_slice(&path_keypairs);
727            keypairs
728        } else {
729            vec![self.key_material.encryption_key_pair()]
730        };
731
732        #[cfg(feature = "extensions-draft")]
733        #[cfg_attr(not(feature = "virtual-clients-draft"), allow(unused_mut))]
734        let mut application_export_tree =
735            ApplicationExportTree::new(self.application_export_secret);
736
737        // The epoch the Welcome hands us is a derivation epoch of the emulation
738        // group: the commit that created it added us, so it changed membership.
739        #[cfg(feature = "virtual-clients-draft")]
740        if self.emulation_group {
741            register_vc_derivation_epoch(
742                provider.crypto(),
743                provider.storage(),
744                Some(&mut application_export_tree),
745                VcDerivationEpochParams::for_public_group(
746                    &self.public_group,
747                    self.own_leaf_index,
748                    self.mls_group_config
749                        .vc_derivation_epoch_retention_policy()
750                        .clone(),
751                ),
752            )
753            .await?;
754        }
755
756        // A join via a virtual-client KeyPackage lands on a leaf shared with
757        // sibling emulator clients. Bind the joined epoch to the leaf's
758        // derivation epoch, as an external-commit join does, so that messages
759        // siblings send from the shared leaf can be deprotected instead of
760        // being mistaken for our own echo.
761        #[cfg(feature = "virtual-clients-draft")]
762        if let Some(derivation_info) = self
763            .public_group
764            .leaf(self.own_leaf_index)
765            .map(LeafNode::vc_derivation_info)
766            .transpose()?
767            .flatten()
768        {
769            let epoch_id = derivation_info.epoch_id().clone();
770            let group_id = self.public_group.group_id();
771            provider
772                .storage()
773                .vc_derivation_epoch_state::<_, VcDerivationEpochState>(&epoch_id)
774                .await
775                .map_err(WelcomeError::StorageError)?
776                .ok_or(WelcomeError::VirtualClientsError(
777                    VirtualClientsError::MissingDerivationEpochState,
778                ))?;
779            // Keep one binding per retained message-secrets epoch plus the
780            // current one, matching the other VC group-entry paths.
781            let max_entries = self.message_secrets_store.max_epochs.saturating_add(1);
782            write_vc_emulation_binding_with_pruning(
783                provider.storage(),
784                group_id,
785                self.public_group.group_context().epoch(),
786                epoch_id,
787                max_entries,
788            )
789            .await
790            .map_err(WelcomeError::StorageError)?;
791        }
792
793        let past_epoch_deletion_policy = self.mls_group_config.past_epoch_deletion_policy().clone();
794
795        let mut mls_group = MlsGroup {
796            mls_group_config: self.mls_group_config,
797            own_leaf_nodes: vec![],
798            aad: vec![],
799            #[cfg(feature = "extensions-draft")]
800            safe_aad: SafeAad::empty(),
801            group_state: MlsGroupState::Operational,
802            public_group: self.public_group,
803            group_epoch_secrets: self.group_epoch_secrets,
804            own_leaf_index: self.own_leaf_index,
805            message_secrets_store: self.message_secrets_store,
806            resumption_psk_store: self.resumption_psk_store,
807            #[cfg(feature = "extensions-draft")]
808            application_export_tree: Some(application_export_tree),
809            #[cfg(feature = "virtual-clients-draft")]
810            emulation_group: self.emulation_group,
811        };
812
813        mls_group
814            .store_epoch_keypairs(provider.storage(), group_keypairs.as_slice())
815            .await
816            .map_err(WelcomeError::StorageError)?;
817        // resize the store
818        mls_group.resize_message_secrets_store(&past_epoch_deletion_policy);
819
820        // A join through a virtual client's KeyPackage binds the joined epoch
821        // to the KeyPackage's derivation epoch. The binding takes over the
822        // epoch reference from the retained KeyPackage material, which
823        // `keys_for_welcome` left in storage for that purpose. (a bound group
824        // is required for the reuse-guard MUST). The material of a last resort
825        // KeyPackage is kept, mirroring how `keys_for_welcome` keeps a last
826        // resort KeyPackage bundle.
827        #[cfg(feature = "virtual-clients-draft")]
828        if let Some(material) = self.key_material.vc_welcome_material() {
829            let max_entries = mls_group.message_secrets_store.max_epochs.saturating_add(1);
830            write_vc_emulation_binding_with_pruning(
831                provider.storage(),
832                mls_group.group_id(),
833                mls_group.epoch(),
834                material.epoch_id.clone(),
835                max_entries,
836            )
837            .await
838            .map_err(WelcomeError::StorageError)?;
839            if !material.last_resort {
840                provider
841                    .storage()
842                    .delete_retained_key_package_material(&material.key_package_ref)
843                    .await
844                    .map_err(WelcomeError::StorageError)?;
845            }
846        }
847
848        // A virtual client's own KeyPackage comes with retained material too.
849        // The binding written for the joined leaf took over its epoch
850        // reference, so the KeyPackage is consumed now.
851        #[cfg(feature = "virtual-clients-draft")]
852        if let Some(key_package_bundle) = self.key_material.key_package_bundle() {
853            if !key_package_bundle.key_package().last_resort()
854                && join_consumes_key_package(key_package_bundle)?
855            {
856                provider
857                    .storage()
858                    .delete_key_package(
859                        &key_package_bundle
860                            .key_package()
861                            .hash_ref(provider.crypto())?,
862                    )
863                    .await
864                    .map_err(WelcomeError::StorageError)?;
865            }
866        }
867
868        mls_group
869            .store(provider.storage())
870            .await
871            .map_err(WelcomeError::StorageError)?;
872
873        Ok(mls_group)
874    }
875
876    /// Exports a secret from the epoch of the group that is joined
877    /// using this [`StagedWelcome`].
878    /// Returns [`ExportSecretError::KeyLengthTooLong`] if the requested
879    /// key length is too long.
880    pub fn export_secret<CryptoProvider: OpenMlsCrypto>(
881        &self,
882        crypto: &CryptoProvider,
883        label: &str,
884        context: &[u8],
885        key_length: usize,
886    ) -> Result<ExportedSecret<StagedWelcomeExport>, ExportSecretError> {
887        if key_length > u16::MAX as usize {
888            log::error!("Got a key that is larger than u16::MAX");
889            return Err(ExportSecretError::KeyLengthTooLong);
890        }
891
892        Ok(ExportedSecret::new(
893            self.group_epoch_secrets
894                .exporter_secret()
895                .derive_exported_secret(
896                    self.group_context().ciphersuite(),
897                    crypto,
898                    label,
899                    context,
900                    key_length,
901                )
902                .map_err(LibraryError::unexpected_crypto_error)?,
903        ))
904    }
905}
906
907/// A `Welcome` whose group secrets have been decrypted, but whose [`GroupInfo`]
908/// has not.
909///
910/// This lets a receiver read which parent group and epoch the group branches from before
911/// committing to a [`BranchInfo`], or the [`ReInitInfo`] of the predecessor.
912/// The decrypted state is carried here and reused when finishing the join.
913/// Create it with [`StagedWelcome::process_resuming_welcome`], read the PSK
914/// reference with [`Self::required_resumption_secret`], then finish with
915/// [`Self::build_from_branch`], [`Self::build_from_reinit`], or [`Self::build`].
916pub struct PendingResumingWelcome {
917    mls_group_config: MlsGroupJoinConfig,
918    ciphersuite: Ciphersuite,
919    welcome: Welcome,
920    resumption_psk_store: ResumptionPskStore,
921    key_material: WelcomeKeyMaterial,
922    group_secrets: GroupSecrets,
923}
924
925impl PendingResumingWelcome {
926    /// The PSK pointing to the parent group and epoch for branch or old group and final epoch for reinit, if any.
927    ///
928    /// The returned [`ResumptionPsk`] has a `usage` of either [`Reinit`](ResumptionPskUsage::Reinit) or [`Branch`](ResumptionPskUsage::Branch).
929    pub fn required_resumption_secret(&self) -> Option<&ResumptionPsk> {
930        for psk_id in &self.group_secrets.psks {
931            if let Psk::Resumption(resumption_psk) = &psk_id.psk {
932                match resumption_psk.usage {
933                    ResumptionPskUsage::Reinit | ResumptionPskUsage::Branch => {
934                        return Some(resumption_psk)
935                    }
936                    _ => {}
937                }
938            }
939        }
940        None
941    }
942
943    /// Finish processing without injecting a PSK.
944    ///
945    /// Use this method if the welcome does not need a PSK, indicated by [`Self::required_resumption_secret`] returning [`None`].
946    ///
947    /// This has the same effect as [`ProcessedWelcome::new_from_welcome`]
948    #[openmls_traits::maybe_async]
949    pub async fn build<Provider: OpenMlsProvider>(
950        self,
951        provider: &Provider,
952    ) -> Result<ProcessedWelcome, WelcomeError<Provider::StorageError>> {
953        let processed_welcome: ProcessedWelcome = finish_processed_welcome(
954            provider,
955            &self.mls_group_config,
956            self.ciphersuite,
957            self.resumption_psk_store,
958            self.key_material,
959            self.group_secrets,
960            &self.welcome,
961            None,
962        )
963        .await?;
964
965        Ok(processed_welcome)
966    }
967
968    /// Prepare the reinit join with the selected [`ReInitInfo`].
969    ///
970    /// The reinit PSK's reference is checked against `reinit_info` (see
971    /// [`StagedWelcome::build_from_reinit`]); a `reinit_info` from the wrong
972    /// group or epoch fails with [`WelcomeError::ReInitPredecessorMismatch`]. The
973    /// remaining receiver checks run when [`JoinBuilder::build`] is called.
974    #[openmls_traits::maybe_async]
975    pub async fn build_from_reinit<'a, Provider: OpenMlsProvider>(
976        self,
977        provider: &'a Provider,
978        reinit_info: ReInitInfo,
979    ) -> Result<JoinBuilder<'a, Provider>, WelcomeError<Provider::StorageError>> {
980        let resumption_info = ResumptionInfo::ReInit(reinit_info);
981        let processed_welcome = finish_processed_welcome(
982            provider,
983            &self.mls_group_config,
984            self.ciphersuite,
985            self.resumption_psk_store,
986            self.key_material,
987            self.group_secrets,
988            &self.welcome,
989            Some(&resumption_info),
990        )
991        .await?;
992
993        Ok(JoinBuilder::new(provider, processed_welcome).with_resumption_info(resumption_info))
994    }
995
996    /// Prepare the subgroup-branch join with the selected [`BranchInfo`].
997    ///
998    /// The branch PSK's parent reference is checked against `branch_info` (see
999    /// [`StagedWelcome::build_from_branch`]); a `branch_info` from the wrong
1000    /// parent epoch fails with [`WelcomeError::SubgroupParentMismatch`]. The
1001    /// remaining receiver checks run when [`JoinBuilder::build`] is called.
1002    #[openmls_traits::maybe_async]
1003    pub async fn build_from_branch<'a, Provider: OpenMlsProvider>(
1004        self,
1005        provider: &'a Provider,
1006        branch_info: BranchInfo,
1007    ) -> Result<JoinBuilder<'a, Provider>, WelcomeError<Provider::StorageError>> {
1008        let resumption_info = ResumptionInfo::Branch(branch_info);
1009        let processed_welcome = finish_processed_welcome(
1010            provider,
1011            &self.mls_group_config,
1012            self.ciphersuite,
1013            self.resumption_psk_store,
1014            self.key_material,
1015            self.group_secrets,
1016            &self.welcome,
1017            Some(&resumption_info),
1018        )
1019        .await?;
1020
1021        Ok(JoinBuilder::new(provider, processed_welcome).with_resumption_info(resumption_info))
1022    }
1023}
1024
1025#[derive(Debug)]
1026pub(crate) enum ResumptionInfo {
1027    ReInit(ReInitInfo),
1028    Branch(BranchInfo),
1029}
1030
1031impl ResumptionInfo {
1032    pub(crate) fn member_credentials(&self) -> &[Credential] {
1033        match self {
1034            ResumptionInfo::Branch(branch_info) => branch_info.member_credentials(),
1035            ResumptionInfo::ReInit(reinit_info) => reinit_info.member_credentials(),
1036        }
1037    }
1038}
1039
1040/// Decrypt a `Welcome`'s `GroupSecrets`.
1041///
1042/// This is the first half of welcome processing, shared between the regular
1043/// join and the subgroup-branch peek (see [`PendingResumingWelcome`]). It consumes
1044/// the matching (non-last-resort) key package from storage via
1045/// [`keys_for_welcome`] and decrypts the encrypted group secrets addressed to
1046/// it. A virtual client's KeyPackage and retained virtual-client material are
1047/// read but not consumed, see [`keys_for_welcome`].
1048#[openmls_traits::maybe_async]
1049async fn decrypt_group_secrets<Provider: OpenMlsProvider>(
1050    provider: &Provider,
1051    mls_group_config: &MlsGroupJoinConfig,
1052    welcome: &Welcome,
1053) -> Result<
1054    (ResumptionPskStore, WelcomeKeyMaterial, GroupSecrets),
1055    WelcomeError<<Provider as OpenMlsProvider>::StorageError>,
1056> {
1057    let ciphersuite = welcome.ciphersuite();
1058    // Check this before touching any stored key material: `keys_for_welcome`
1059    // consumes a matching (non-last-resort) key package.
1060    provider
1061        .crypto()
1062        .supports(ciphersuite)
1063        .map_err(|_| WelcomeError::UnsupportedCiphersuite(ciphersuite))?;
1064
1065    let (resumption_psk_store, key_material) =
1066        keys_for_welcome(mls_group_config, welcome, provider).await?;
1067
1068    let Some(egs) =
1069        welcome.find_encrypted_group_secret(key_material.key_package_ref(provider.crypto())?)
1070    else {
1071        return Err(WelcomeError::JoinerSecretNotFound);
1072    };
1073
1074    // This check seems to be superfluous from the perspective of the RFC, but still doesn't
1075    // seem like a bad idea. There is no local KeyPackage to compare against on the
1076    // virtual-client path, where the derived material is implicitly the welcome's ciphersuite.
1077    if let Some(key_package_bundle) = key_material.key_package_bundle() {
1078        if welcome.ciphersuite() != key_package_bundle.key_package().ciphersuite() {
1079            let e = WelcomeError::CiphersuiteMismatch;
1080            log::debug!("new_from_welcome {e:?}");
1081            return Err(e);
1082        }
1083    }
1084
1085    let group_secrets = GroupSecrets::try_from_ciphertext(
1086        key_material.init_private_key(),
1087        egs.encrypted_group_secrets(),
1088        welcome.encrypted_group_info(),
1089        ciphersuite,
1090        provider.crypto(),
1091    )?;
1092
1093    // Validate PSKs
1094    PreSharedKeyId::validate_in_welcome(&group_secrets.psks, ciphersuite)?;
1095
1096    Ok((resumption_psk_store, key_material, group_secrets))
1097}
1098
1099/// Finish processing a `Welcome` from its already-decrypted `GroupSecrets`.
1100///
1101/// This is the second half of welcome processing (the tail of
1102/// [`ProcessedWelcome::new_from_welcome_inner`]): it derives the key schedule,
1103/// decrypts the group info, and runs the capability/ciphersuite checks,
1104/// producing a [`ProcessedWelcome`]. It still needs the `welcome` for its
1105/// encrypted group info.
1106#[allow(clippy::too_many_arguments)]
1107#[openmls_traits::maybe_async]
1108async fn finish_processed_welcome<Provider: OpenMlsProvider>(
1109    provider: &Provider,
1110    mls_group_config: &MlsGroupJoinConfig,
1111    ciphersuite: Ciphersuite,
1112    resumption_psk_store: ResumptionPskStore,
1113    key_material: WelcomeKeyMaterial,
1114    group_secrets: GroupSecrets,
1115    welcome: &Welcome,
1116    resumption_info: Option<&ResumptionInfo>,
1117) -> Result<ProcessedWelcome, WelcomeError<<Provider as OpenMlsProvider>::StorageError>> {
1118    let foreign_psk = if let Some(resumption_info) = resumption_info {
1119        // For subgroup branching and reinit, include the parent/predecessor group's resumption PSK.
1120        match resumption_info {
1121            ResumptionInfo::Branch(branch_info) => {
1122                // When joining a subgroup branch, the branch resumption
1123                // PSK carried in the Welcome must reference the same parent group and
1124                // epoch the receiver is branching from.
1125                let parent_psk_id = group_secrets.psks.iter().find(|id| {
1126                    matches!(id.psk(), Psk::Resumption(r) if r.usage() == ResumptionPskUsage::Branch
1127                            && r.psk_group_id() == branch_info.group_id()
1128                            && r.psk_epoch() == branch_info.epoch()
1129                    )
1130                });
1131                if let Some(psk_id) = parent_psk_id {
1132                    Some((psk_id, branch_info.resumption_psk_secret().clone()))
1133                } else {
1134                    return Err(WelcomeError::SubgroupParentMismatch);
1135                }
1136            }
1137            ResumptionInfo::ReInit(reinit_info) => {
1138                // When joining a reinit, the resumption psk must match the `group_id` and final epoch of the old group.
1139                let predecessor_psk_id = group_secrets.psks.iter().find(|id| {
1140                    matches!(id.psk(), Psk::Resumption(r) if r.usage() == ResumptionPskUsage::Reinit
1141                        && r.psk_group_id() == reinit_info.old_group_id()
1142                        && r.psk_epoch() == reinit_info.old_group_epoch()
1143                    )
1144                });
1145                if let Some(psk_id) = predecessor_psk_id {
1146                    Some((psk_id, reinit_info.resumption_psk_secret().clone()))
1147                } else {
1148                    return Err(WelcomeError::ReInitPredecessorMismatch);
1149                }
1150            }
1151        }
1152    } else {
1153        None
1154    };
1155
1156    let psk_secret = {
1157        // We are joining the group, so there is no resumption PSK history and we don't know the group_id yet.
1158        // Therefore, resumption PSKs of usage `Application` cannot be resolved and `group_id` is `None`.
1159        let psks = load_psks(
1160            provider.storage(),
1161            &resumption_psk_store,
1162            None,
1163            foreign_psk,
1164            &group_secrets.psks,
1165        )
1166        .await?;
1167
1168        PskSecret::new(provider.crypto(), ciphersuite, psks)?
1169    };
1170
1171    // prepare the key schedule
1172    let mut key_schedule = KeySchedule::init(
1173        ciphersuite,
1174        provider.crypto(),
1175        &group_secrets.joiner_secret,
1176        psk_secret,
1177    )?;
1178
1179    // derive the keys for decrypting the group info
1180    let (welcome_key, welcome_nonce) = key_schedule
1181        .welcome(provider.crypto(), ciphersuite)
1182        .map_err(|_| LibraryError::custom("Using the key schedule in the wrong state"))?
1183        .derive_welcome_key_nonce(provider.crypto(), ciphersuite)
1184        .map_err(LibraryError::unexpected_crypto_error)?;
1185
1186    let verifiable_group_info = VerifiableGroupInfo::try_from_ciphertext(
1187        &welcome_key,
1188        &welcome_nonce,
1189        welcome.encrypted_group_info(),
1190        &[],
1191        provider.crypto(),
1192    )?;
1193
1194    let serialized_group_context = verifiable_group_info
1195        .group_context()
1196        .tls_serialize_detached()
1197        .map_err(LibraryError::missing_bound_check)?;
1198
1199    key_schedule.add_context(provider.crypto(), &serialized_group_context)?;
1200
1201    let epoch_secrets = key_schedule.epoch_secrets(provider.crypto(), ciphersuite)?;
1202
1203    // On the bundle path, check the required capabilities and the
1204    // ciphersuite against the local KeyPackage. On the virtual-client path
1205    // there is no local KeyPackage: these are checked in staging against
1206    // the own tree leaf instead.
1207    if let Some(key_package_bundle) = key_material.key_package_bundle() {
1208        if let Some(required_capabilities) =
1209            verifiable_group_info.extensions().required_capabilities()
1210        {
1211            // Also check that our key package actually supports the extensions.
1212            // As per the spec, the sender must have checked this. But you never know.
1213            key_package_bundle
1214                .key_package()
1215                .leaf_node()
1216                .capabilities()
1217                .supports_required_capabilities(required_capabilities)?;
1218        }
1219
1220        // https://validation.openmls.tech/#valn1404
1221        // Verify that the cipher_suite in the GroupInfo matches the cipher_suite in the
1222        // KeyPackage.
1223        if verifiable_group_info.ciphersuite() != key_package_bundle.key_package().ciphersuite() {
1224            let e = WelcomeError::CiphersuiteMismatch;
1225            log::debug!("new_from_welcome {e:?}");
1226            return Err(e);
1227        }
1228    }
1229
1230    Ok(ProcessedWelcome {
1231        mls_group_config: mls_group_config.clone(),
1232        ciphersuite,
1233        group_secrets,
1234        epoch_secrets,
1235        verifiable_group_info,
1236        resumption_psk_store,
1237        key_material,
1238    })
1239}
1240
1241/// Read keys for decrypting the welcome message.
1242#[openmls_traits::maybe_async]
1243async fn keys_for_welcome<Provider: OpenMlsProvider>(
1244    mls_group_config: &MlsGroupJoinConfig,
1245    welcome: &Welcome,
1246    provider: &Provider,
1247) -> Result<
1248    (ResumptionPskStore, WelcomeKeyMaterial),
1249    WelcomeError<<Provider as OpenMlsProvider>::StorageError>,
1250> {
1251    let resumption_psk_store = ResumptionPskStore::new(mls_group_config.number_of_resumption_psks);
1252
1253    for egs in welcome.secrets() {
1254        let hash_ref = egs.new_member();
1255        if let Some(key_package_bundle) = provider
1256            .storage()
1257            .key_package(&hash_ref)
1258            .await
1259            .map_err(WelcomeError::StorageError)?
1260        {
1261            let key_package_bundle: KeyPackageBundle = key_package_bundle;
1262            if key_package_bundle.key_package().last_resort() {
1263                log::debug!("KeyPackage has a last-resort marker, not deleting");
1264            } else if !join_consumes_key_package(&key_package_bundle)? {
1265                provider
1266                    .storage()
1267                    .delete_key_package(
1268                        &key_package_bundle.key_package.hash_ref(provider.crypto())?,
1269                    )
1270                    .await
1271                    .map_err(WelcomeError::StorageError)?;
1272            }
1273            return Ok((
1274                resumption_psk_store,
1275                WelcomeKeyMaterial::with_key_package_bundle(key_package_bundle),
1276            ));
1277        }
1278
1279        #[cfg(feature = "virtual-clients-draft")]
1280        if let Some(material) =
1281            resolve_vc_welcome_material(provider, welcome.ciphersuite(), &hash_ref).await?
1282        {
1283            // The retained material stays in storage for now.
1284            return Ok((
1285                resumption_psk_store,
1286                WelcomeKeyMaterial::with_vc_welcome_material(material),
1287            ));
1288        }
1289    }
1290
1291    Err(WelcomeError::NoMatchingKeyPackage)
1292}
1293
1294/// Returns whether [`StagedWelcome::into_group`] rather than
1295/// [`keys_for_welcome`] deletes the (non-last-resort) `key_package_bundle`.
1296///
1297/// That is the case for a virtual client's KeyPackage. Deleting it also deletes
1298/// its retained material, which keeps the derivation epoch alive that the join
1299/// binds the group to. Like a sibling's retained material, it has to stay until
1300/// the group is bound.
1301fn join_consumes_key_package<StorageError>(
1302    key_package_bundle: &KeyPackageBundle,
1303) -> Result<bool, WelcomeError<StorageError>> {
1304    #[cfg(feature = "virtual-clients-draft")]
1305    {
1306        Ok(key_package_bundle
1307            .key_package()
1308            .leaf_node()
1309            .vc_derivation_info()?
1310            .is_some())
1311    }
1312    #[cfg(not(feature = "virtual-clients-draft"))]
1313    {
1314        let _ = key_package_bundle;
1315        Ok(false)
1316    }
1317}
1318
1319/// Try to derive virtual-client welcome material for `hash_ref`. Returns
1320/// `None` if no [`RetainedKeyPackageMaterial`] is stored for the ref, so the
1321/// caller can keep scanning the welcome's encrypted group secrets.
1322///
1323/// On a match this reconstructs the per-KeyPackage seed pinned in the retained
1324/// material at upload-processing time, and
1325/// derives the init and leaf-encryption keypairs from the seed under the
1326/// Welcome's ciphersuite. It does not touch the operation tree: the batch
1327/// generation was already consumed once when the upload was processed, and the
1328/// seed is enough to reproduce the keys.
1329///
1330/// [`RetainedKeyPackageMaterial`]: RetainedKeyPackageMaterial
1331#[cfg(feature = "virtual-clients-draft")]
1332#[openmls_traits::maybe_async]
1333pub(crate) async fn resolve_vc_welcome_material<Provider: OpenMlsProvider>(
1334    provider: &Provider,
1335    ciphersuite: Ciphersuite,
1336    hash_ref: &KeyPackageRef,
1337) -> Result<Option<VcWelcomeMaterial>, WelcomeError<<Provider as OpenMlsProvider>::StorageError>> {
1338    let storage = provider.storage();
1339    let Some(material) = storage
1340        .retained_key_package_material::<_, RetainedKeyPackageMaterial>(hash_ref)
1341        .await
1342        .map_err(WelcomeError::StorageError)?
1343    else {
1344        return Ok(None);
1345    };
1346
1347    if material.key_package_ciphersuite != ciphersuite {
1348        return Err(WelcomeError::CiphersuiteMismatch);
1349    }
1350
1351    // The seed is imported into the KeyPackage's ciphersuite at
1352    // upload-processing time. The init and leaf-encryption keys are derived
1353    // from it under the KeyPackage's own (the welcome's) ciphersuite.
1354    let crypto = provider.crypto();
1355    let init_key_pair = material
1356        .key_package_seed_secret
1357        .derive_init_key_secret(crypto, ciphersuite)?
1358        .generate_init_key_pair(crypto, ciphersuite)?;
1359    let encryption_keypair = material
1360        .key_package_seed_secret
1361        .derive_encryption_key_secret(crypto, ciphersuite)?
1362        .generate_encryption_key_pair(crypto, ciphersuite)?;
1363
1364    Ok(Some(VcWelcomeMaterial {
1365        key_package_ref: hash_ref.clone(),
1366        epoch_id: material.epoch_id,
1367        leaf_index: material.leaf_index,
1368        generation: material.generation,
1369        key_package_index: material.key_package_index,
1370        init_private_key: init_key_pair.private,
1371        init_key: init_key_pair.public.into(),
1372        encryption_keypair,
1373        last_resort: has_last_resort_marker(&material.key_package_extensions),
1374    }))
1375}
1376
1377/// Find and validate the virtual client's own leaf in the ratchet tree.
1378///
1379/// A virtual client has no signature key of its own, so the leaf is located by
1380/// the derivation info the VC sender embedded under [`VC_COMPONENT_ID`]: the
1381/// leaf whose cleartext `epoch_id` equals the material's and whose
1382/// `encryption_key` equals the key derived in the first welcome stage. That
1383/// leaf's encrypted [`DerivationInfoTbe`] is then decrypted with the derivation
1384/// epoch state and its `leaf_index`, `generation`, and `key_package_index`
1385/// must equal the material's.
1386///
1387/// [`VC_COMPONENT_ID`]: crate::components::vc_derivation_info::VC_COMPONENT_ID
1388/// [`DerivationInfoTbe`]: crate::components::vc_derivation_info::DerivationInfoTbe
1389#[cfg(feature = "virtual-clients-draft")]
1390#[openmls_traits::maybe_async]
1391async fn find_and_validate_vc_own_leaf<Provider: OpenMlsProvider>(
1392    provider: &Provider,
1393    public_group: &PublicGroup,
1394    material: &VcWelcomeMaterial,
1395) -> Result<LeafNodeIndex, WelcomeError<<Provider as OpenMlsProvider>::StorageError>> {
1396    use tls_codec::Serialize as _;
1397
1398    let crypto = provider.crypto();
1399    let derived_encryption_key = material.encryption_keypair.public_key().as_slice().to_vec();
1400
1401    let own_index = public_group
1402        .members()
1403        .find(|m| m.encryption_key == derived_encryption_key)
1404        .map(|m| m.index)
1405        .ok_or(WelcomeError::PublicTreeError(
1406            PublicTreeError::MalformedTree,
1407        ))?;
1408
1409    let own_leaf = public_group
1410        .leaf(own_index)
1411        .ok_or(WelcomeError::PublicTreeError(
1412            PublicTreeError::MalformedTree,
1413        ))?;
1414
1415    let derivation_info = own_leaf
1416        .vc_derivation_info()?
1417        .ok_or(VirtualClientsError::VcComponentNotListed)?;
1418    if derivation_info.epoch_id() != &material.epoch_id {
1419        log::error!("vc: welcome leaf epoch id does not match the retained material");
1420        return Err(VirtualClientsError::DerivationInfoMalformed.into());
1421    }
1422
1423    let state: VcDerivationEpochState = provider
1424        .storage()
1425        .vc_derivation_epoch_state(&material.epoch_id)
1426        .await
1427        .map_err(|e| {
1428            log::error!("vc: load derivation epoch state in welcome staging failed: {e:?}");
1429            VirtualClientsError::StorageError
1430        })?
1431        .ok_or(VirtualClientsError::MissingDerivationEpochState)?;
1432    let (_state_leaf_index, epoch_encryption_key, emulation_ciphersuite) = state.into_parts();
1433
1434    let leaf_encryption_key = own_leaf
1435        .encryption_key()
1436        .tls_serialize_detached()
1437        .map_err(VirtualClientsError::from)?;
1438    // A KeyPackage leaf carries the `KeyPackage` variant of the tagless
1439    // select, so it decodes with `key_package_index` present.
1440    let tbe = derivation_info.decrypt(
1441        crypto,
1442        emulation_ciphersuite,
1443        &epoch_encryption_key,
1444        &leaf_encryption_key,
1445        VirtualClientOperationType::KeyPackage,
1446    )?;
1447
1448    let DerivationInfoTbe::KeyPackage {
1449        leaf_index,
1450        generation,
1451        key_package_index,
1452    } = tbe
1453    else {
1454        log::error!("vc: welcome leaf derivation info is not a key-package variant");
1455        return Err(VirtualClientsError::DerivationInfoMalformed.into());
1456    };
1457    if leaf_index != material.leaf_index
1458        || generation != material.generation
1459        || key_package_index != material.key_package_index
1460    {
1461        log::error!("vc: welcome leaf derivation info does not match the retained material");
1462        return Err(VirtualClientsError::DerivationInfoMalformed.into());
1463    }
1464
1465    Ok(own_index)
1466}
1467
1468#[cfg(feature = "virtual-clients-draft")]
1469impl MlsGroup {
1470    /// Returns a new [`VcExternalCommitJoinBuilder`] for joining a
1471    /// higher-level group as a virtual client's sibling emulator client, by
1472    /// processing another sibling's external commit.
1473    pub fn vc_external_commit_join_builder() -> VcExternalCommitJoinBuilder {
1474        VcExternalCommitJoinBuilder::new()
1475    }
1476
1477    /// Bootstrap a virtual client's sibling emulator client into a higher-level
1478    /// group the virtual client created, when this client is not yet a member.
1479    ///
1480    /// The creator emulator client built the group with
1481    /// [`MlsGroupBuilder::vc_emulation`], its `key_package`-sourced leaf key
1482    /// material derived from a `key_package` operation secret. Sharing the same
1483    /// derivation epoch (`epoch_id`), this client reconstructs the epoch-0 state:
1484    /// it verifies the GroupInfo and single-leaf ratchet tree (which may instead
1485    /// travel in the GroupInfo's `ratchet_tree` extension), rederives the creator
1486    /// leaf's key material from the shared operation secret tree, and derives the
1487    /// same epoch-0 `epoch_secret` from the creator's KeyPackage seed. No secret
1488    /// travels on the wire. On success the returned group sits at epoch 0 with
1489    /// this client on the shared virtual-client leaf (index 0).
1490    ///
1491    /// [`MlsGroupBuilder::vc_emulation`]: crate::group::MlsGroupBuilder::vc_emulation
1492    #[openmls_traits::maybe_async]
1493    pub async fn vc_join_at_creation<Provider: OpenMlsProvider>(
1494        provider: &Provider,
1495        join_config: &MlsGroupJoinConfig,
1496        verifiable_group_info: VerifiableGroupInfo,
1497        ratchet_tree: Option<RatchetTreeIn>,
1498        epoch_id: EpochId,
1499    ) -> Result<MlsGroup, VcGroupCreationJoinError<Provider::StorageError>> {
1500        use tls_codec::Serialize as _;
1501
1502        type Error<S> = VcGroupCreationJoinError<S>;
1503
1504        // Resolve the ratchet tree (from the GroupInfo extension or the
1505        // argument) and verify the GroupInfo and tree.
1506        let ratchet_tree = match verifiable_group_info.extensions().ratchet_tree() {
1507            Some(extension) => extension.ratchet_tree().clone(),
1508            None => ratchet_tree.ok_or(Error::MissingRatchetTree)?,
1509        };
1510        let (public_group, group_info) = PublicGroup::from_ratchet_tree(
1511            provider.crypto(),
1512            ratchet_tree,
1513            verifiable_group_info,
1514            ProposalStore::new(),
1515            LeafNodeLifetimePolicy::default(),
1516        )?;
1517        let ciphersuite = public_group.ciphersuite();
1518
1519        // The created group consists of exactly the creator's leaf at index 0.
1520        if public_group.members().count() != 1 {
1521            return Err(Error::NotASingleLeafTree);
1522        }
1523        let creator_index = LeafNodeIndex::new(0);
1524        let creator_leaf = public_group
1525            .leaf(creator_index)
1526            .ok_or(Error::NotASingleLeafTree)?;
1527
1528        // A virtual client's group-creation leaf is key_package-sourced.
1529        let LeafNodeSource::KeyPackage(_) = creator_leaf.leaf_node_source() else {
1530            return Err(Error::CreatorLeafNotKeyPackageSourced);
1531        };
1532
1533        // Read the creator leaf's derivation info and check the derivation epoch.
1534        let derivation_info = creator_leaf
1535            .vc_derivation_info()?
1536            .ok_or(Error::MissingDerivationInfo)?;
1537        if derivation_info.epoch_id() != &epoch_id {
1538            return Err(Error::EpochIdMismatch);
1539        }
1540
1541        // Load the derivation epoch state and operation tree.
1542        let (state, mut operation_tree) = load_vc_epoch_state_and_tree(provider, &epoch_id).await?;
1543        let (_leaf_index, epoch_encryption_key, emulation_ciphersuite) = state.into_parts();
1544
1545        // Decrypt the derivation info (KeyPackage case) and read the batch index
1546        // the creator's seed was derived under.
1547        let leaf_encryption_key = creator_leaf
1548            .encryption_key()
1549            .tls_serialize_detached()
1550            .map_err(VirtualClientsError::from)?;
1551        let tbe = derivation_info.decrypt(
1552            provider.crypto(),
1553            emulation_ciphersuite,
1554            &epoch_encryption_key,
1555            &leaf_encryption_key,
1556            VirtualClientOperationType::KeyPackage,
1557        )?;
1558        let DerivationInfoTbe::KeyPackage {
1559            leaf_index,
1560            generation,
1561            key_package_index,
1562        } = tbe
1563        else {
1564            // Decrypting with the KeyPackage operation type always yields the
1565            // KeyPackage variant.
1566            return Err(LibraryError::custom("unexpected derivation info variant").into());
1567        };
1568
1569        // Rederive the creator's KeyPackage seed positionally from the shared
1570        // operation tree, then the creator leaf's encryption keypair from that
1571        // seed. The `key_package` operation context is empty. The advanced tree
1572        // is persisted only after the confirmation tag verifies, so a corrupted
1573        // GroupInfo naming the genuine creator leaf does not burn this sibling's
1574        // generation.
1575        let operation_secret = operation_tree.derive_operation_secret(
1576            provider.crypto(),
1577            emulation_ciphersuite,
1578            &epoch_id,
1579            leaf_index,
1580            VirtualClientOperationType::KeyPackage,
1581            generation,
1582            b"",
1583        )?;
1584        let key_package_seed = operation_secret.derive_key_package_seed_secret(
1585            provider.crypto(),
1586            ciphersuite,
1587            key_package_index,
1588        )?;
1589        let leaf_keypair = key_package_seed
1590            .derive_encryption_key_secret(provider.crypto(), ciphersuite)?
1591            .generate_encryption_key_pair(provider.crypto(), ciphersuite)?;
1592        if leaf_keypair.public_key() != creator_leaf.encryption_key() {
1593            return Err(Error::LeafKeyMismatch);
1594        }
1595
1596        // Derive epoch-0 secrets from the same KeyPackage seed and verify the
1597        // GroupInfo's confirmation tag against them. A mismatch means the
1598        // reconstruction did not reproduce the creator's epoch secrets.
1599        let serialized_group_context = public_group
1600            .group_context()
1601            .tls_serialize_detached()
1602            .map_err(LibraryError::missing_bound_check)?;
1603        let epoch_secret =
1604            key_package_seed.derive_group_creation_secret(provider.crypto(), ciphersuite)?;
1605        let epoch_secrets =
1606            EpochSecrets::from_epoch_secret(provider.crypto(), ciphersuite, epoch_secret)
1607                .map_err(LibraryError::unexpected_crypto_error)?;
1608        let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
1609            serialized_group_context,
1610            public_group.tree_size(),
1611            creator_index,
1612        );
1613        let expected_confirmation_tag = message_secrets
1614            .confirmation_key()
1615            .tag(
1616                provider.crypto(),
1617                ciphersuite,
1618                public_group.group_context().confirmed_transcript_hash(),
1619            )
1620            .map_err(LibraryError::unexpected_crypto_error)?;
1621        if &expected_confirmation_tag != group_info.confirmation_tag() {
1622            return Err(Error::ConfirmationTagMismatch);
1623        }
1624
1625        // The reconstruction reproduced the creator's secrets, so this is a
1626        // genuine sibling-created group: persist the advanced operation tree.
1627        provider
1628            .storage()
1629            .write_vc_operation_tree(&epoch_id, &operation_tree)
1630            .await
1631            .map_err(Error::StorageError)?;
1632
1633        let message_secrets_store = MessageSecretsStore::new_with_secret(
1634            join_config.past_epoch_deletion_policy(),
1635            message_secrets,
1636        );
1637        let mut resumption_psk_store =
1638            ResumptionPskStore::new(join_config.number_of_resumption_psks);
1639        resumption_psk_store.add(
1640            public_group.group_context().epoch(),
1641            group_epoch_secrets.resumption_psk().clone(),
1642        );
1643
1644        // Bind epoch 0 of the created group to the derivation epoch so later
1645        // VC operations in this group resolve the right derivation epoch state.
1646        // Written before the group itself, so an error between the writes
1647        // cannot leave a loadable group without a binding (a bound group is
1648        // required for the reuse-guard MUST).
1649        let max_entries = message_secrets_store.max_epochs.saturating_add(1);
1650        write_vc_emulation_binding_with_pruning(
1651            provider.storage(),
1652            public_group.group_id(),
1653            public_group.group_context().epoch(),
1654            epoch_id,
1655            max_entries,
1656        )
1657        .await
1658        .map_err(Error::StorageError)?;
1659
1660        let mls_group = MlsGroup {
1661            mls_group_config: join_config.clone(),
1662            own_leaf_nodes: vec![],
1663            aad: vec![],
1664            #[cfg(feature = "extensions-draft")]
1665            safe_aad: SafeAad::empty(),
1666            group_state: MlsGroupState::Operational,
1667            public_group,
1668            group_epoch_secrets,
1669            own_leaf_index: creator_index,
1670            message_secrets_store,
1671            resumption_psk_store,
1672            #[cfg(feature = "extensions-draft")]
1673            application_export_tree: None,
1674            #[cfg(feature = "virtual-clients-draft")]
1675            emulation_group: false,
1676        };
1677        mls_group
1678            .store(provider.storage())
1679            .await
1680            .map_err(Error::StorageError)?;
1681        mls_group
1682            .store_epoch_keypairs(provider.storage(), &[leaf_keypair])
1683            .await
1684            .map_err(Error::StorageError)?;
1685
1686        Ok(mls_group)
1687    }
1688}
1689
1690/// Builder for bootstrapping a virtual client's sibling emulator client into
1691/// a higher-level group by processing another sibling's external commit,
1692/// when this client is not yet a member of that group.
1693///
1694/// The first emulator client joined the higher-level group via an external
1695/// commit. A second emulator client (this one), sharing the same emulation
1696/// epoch, reconstructs the resulting group state from that commit.
1697///
1698/// The join happens in two steps. [`Self::process_commit`] rebuilds the
1699/// prior-epoch group and verifies the commit, returning a
1700/// [`StagedVcExternalCommitJoin`]. The application inspects the verified
1701/// proposals it exposes, resolves any AppDataUpdate proposals, and completes
1702/// the join with [`StagedVcExternalCommitJoin::into_group`].
1703#[cfg(feature = "virtual-clients-draft")]
1704#[derive(Debug, Default)]
1705pub struct VcExternalCommitJoinBuilder {
1706    join_config: MlsGroupJoinConfig,
1707    ratchet_tree: Option<RatchetTreeIn>,
1708    lifetime_policy: LeafNodeLifetimePolicy,
1709}
1710
1711#[cfg(feature = "virtual-clients-draft")]
1712impl VcExternalCommitJoinBuilder {
1713    /// Creates a new [`VcExternalCommitJoinBuilder`] with default values.
1714    pub fn new() -> Self {
1715        Self::default()
1716    }
1717
1718    /// Specifies the configuration to use for the joined group.
1719    pub fn with_config(mut self, join_config: MlsGroupJoinConfig) -> Self {
1720        self.join_config = join_config;
1721        self
1722    }
1723
1724    /// Specifies the prior-epoch ratchet tree. This is only used if the
1725    /// ratchet tree is not provided in the [`VerifiableGroupInfo`]
1726    /// extensions. A ratchet tree must be provided, either in the
1727    /// [`VerifiableGroupInfo`] extensions or via this method.
1728    pub fn with_ratchet_tree(mut self, ratchet_tree: RatchetTreeIn) -> Self {
1729        self.ratchet_tree = Some(ratchet_tree);
1730        self
1731    }
1732
1733    /// Skip the validation of lifetimes in leaf nodes in the ratchet tree.
1734    /// Note that only the leaf nodes are checked that were never updated.
1735    ///
1736    /// By default they are validated.
1737    pub fn skip_lifetime_validation(mut self) -> Self {
1738        self.lifetime_policy = LeafNodeLifetimePolicy::Skip;
1739        self
1740    }
1741
1742    /// Rebuilds the higher-level group at the epoch *before* the external
1743    /// commit from `verifiable_group_info` (and the ratchet tree, taken from
1744    /// the GroupInfo's `ratchet_tree` extension or
1745    /// [`Self::with_ratchet_tree`]), and verifies `external_commit` against
1746    /// it: the GroupInfo signature and tree, the commit's signature and
1747    /// external-commit shape, and that the commit's derivation info
1748    /// references the shared emulation epoch `epoch_id`.
1749    ///
1750    /// Nothing is consumed or persisted at this point. Dropping the returned
1751    /// [`StagedVcExternalCommitJoin`] discards the join without advancing
1752    /// the shared operation secret tree.
1753    #[openmls_traits::maybe_async]
1754    pub async fn process_commit<Provider: OpenMlsProvider>(
1755        self,
1756        provider: &Provider,
1757        verifiable_group_info: VerifiableGroupInfo,
1758        external_commit: impl Into<ProtocolMessage>,
1759        epoch_id: EpochId,
1760    ) -> Result<StagedVcExternalCommitJoin, VcExternalCommitJoinError<Provider::StorageError>> {
1761        type Error<S> = VcExternalCommitJoinError<S>;
1762
1763        let Self {
1764            join_config,
1765            ratchet_tree,
1766            lifetime_policy,
1767        } = self;
1768
1769        // Resolve the prior-epoch ratchet tree (from the GroupInfo extension
1770        // or the builder) and rebuild the prior-epoch public group.
1771        let ratchet_tree = match verifiable_group_info.extensions().ratchet_tree() {
1772            Some(extension) => extension.ratchet_tree().clone(),
1773            None => ratchet_tree.ok_or(Error::MissingRatchetTree)?,
1774        };
1775        let (public_group, _group_info) = PublicGroup::from_ratchet_tree(
1776            provider.crypto(),
1777            ratchet_tree,
1778            verifiable_group_info,
1779            ProposalStore::new(),
1780            lifetime_policy,
1781        )?;
1782
1783        // Assemble a transient group at the prior epoch. Its epoch secrets are
1784        // never used cryptographically here: the external commit carries the
1785        // external init secret and the operation secret tree supplies the path,
1786        // so a random init-secret stub is sufficient. The own leaf index is the
1787        // leftmost free index, where the committing sibling installs the shared
1788        // virtual-client leaf.
1789        let ciphersuite = public_group.ciphersuite();
1790        let serialized_group_context = public_group
1791            .group_context()
1792            .tls_serialize_detached()
1793            .map_err(LibraryError::missing_bound_check)?;
1794        let own_leaf_index = public_group.leftmost_free_index(std::iter::empty())?;
1795        let init_secret = InitSecret::random(ciphersuite, provider.rand())
1796            .map_err(LibraryError::unexpected_crypto_error)?;
1797        let epoch_secrets =
1798            EpochSecrets::with_init_secret(provider.crypto(), ciphersuite, init_secret)
1799                .map_err(LibraryError::unexpected_crypto_error)?;
1800        let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
1801            serialized_group_context,
1802            public_group.tree_size(),
1803            LeafNodeIndex::new(0u32),
1804        );
1805        // Do not retain the synthetic prior-epoch secrets used only to stage
1806        // this external commit.
1807        let message_secrets_store = MessageSecretsStore::new_with_secret(
1808            &PastEpochDeletionPolicy::MaxEpochs(0),
1809            message_secrets,
1810        );
1811        let resumption_psk_store = ResumptionPskStore::new(join_config.number_of_resumption_psks);
1812        let mut group = MlsGroup {
1813            mls_group_config: join_config,
1814            own_leaf_nodes: vec![],
1815            aad: vec![],
1816            #[cfg(feature = "extensions-draft")]
1817            safe_aad: SafeAad::empty(),
1818            group_state: MlsGroupState::Operational,
1819            public_group,
1820            group_epoch_secrets,
1821            own_leaf_index,
1822            message_secrets_store,
1823            resumption_psk_store,
1824            #[cfg(feature = "extensions-draft")]
1825            application_export_tree: None,
1826            // A virtual client joins a higher-level group here, never its own
1827            // emulation group.
1828            emulation_group: false,
1829        };
1830
1831        // Parse and verify the external commit against the prior-epoch group.
1832        // A PrivateMessage claiming our own leaf cannot be an external commit.
1833        let processing::UnprotectedMessage::Unverified {
1834            message: unverified,
1835            ..
1836        } = group.unprotect_message(provider, external_commit).await?
1837        else {
1838            return Err(Error::NotAnExternalCommit);
1839        };
1840        let verified = unverified
1841            .verify(
1842                group.ciphersuite(),
1843                provider.crypto(),
1844                group.version(),
1845                // An external commit carries no Add proposals.
1846                LeafNodeLifetimePolicy::Verify,
1847            )
1848            .map_err(ProcessMessageError::from)?;
1849        if !matches!(verified.content.sender(), Sender::NewMemberCommit) {
1850            return Err(Error::NotAnExternalCommit);
1851        }
1852        let content = verified.content;
1853        let FramedContentBody::Commit(commit) = content.content() else {
1854            return Err(Error::NotAnExternalCommit);
1855        };
1856
1857        // Check the commit's derivation info without consuming an operation
1858        // secret generation: presence and the emulation epoch binding are
1859        // validated here, decryption and the consume-once secret derivation
1860        // happen in `StagedVcExternalCommitJoin::into_group`.
1861        let derivation_info = commit
1862            .path
1863            .as_ref()
1864            .map(|path| path.leaf_node().vc_derivation_info())
1865            .transpose()?
1866            .flatten()
1867            .ok_or(Error::MissingDerivationInfo)?;
1868        if derivation_info.epoch_id() != &epoch_id {
1869            return Err(Error::EpochIdMismatch);
1870        }
1871
1872        // The AppDataUpdate proposals covered by the commit, for the
1873        // application to resolve before completing the join. The transient
1874        // group's proposal store is empty, so only by-value proposals
1875        // resolve. An external commit cannot reference proposals a
1876        // non-member could hold.
1877        let app_data_update_proposals =
1878            committed_app_data_update_proposals(commit, group.proposal_store());
1879
1880        Ok(StagedVcExternalCommitJoin {
1881            group,
1882            content,
1883            app_data_update_proposals,
1884            app_data_updates: None,
1885        })
1886    }
1887}
1888
1889/// A verified sibling external commit, ready to be joined. Returned by
1890/// [`VcExternalCommitJoinBuilder::process_commit`].
1891///
1892/// The commit's signature has been verified against the prior-epoch group,
1893/// so the proposals exposed here are authenticated. If the commit covers
1894/// AppDataUpdate proposals, the application must interpret them (with the
1895/// help of [`Self::app_data_dictionary_updater`]) and supply the resulting
1896/// [`AppDataUpdates`] via [`Self::with_app_data_dictionary_updates`] before
1897/// calling [`Self::into_group`], exactly as it would for
1898/// [`MlsGroup::resolve_app_data_commit`] when processing the same commit as
1899/// a member.
1900///
1901/// Dropping this value discards the join. No operation secret generation is
1902/// consumed before [`Self::into_group`], so a discarded join can be started
1903/// over by processing the same commit again.
1904#[cfg(feature = "virtual-clients-draft")]
1905pub struct StagedVcExternalCommitJoin {
1906    /// Transient reconstruction of the group at the prior epoch.
1907    group: MlsGroup,
1908    /// The verified commit content.
1909    content: AuthenticatedContent,
1910    /// The by-value AppDataUpdate proposals covered by the commit, sorted by
1911    /// component id.
1912    app_data_update_proposals: Vec<AppDataUpdateProposal>,
1913    /// The application-resolved updates for the commit's AppDataUpdate
1914    /// proposals, if any.
1915    app_data_updates: Option<AppDataUpdates>,
1916}
1917
1918#[cfg(feature = "virtual-clients-draft")]
1919impl StagedVcExternalCommitJoin {
1920    /// Returns the [`GroupContext`] of the group at the epoch *before* the
1921    /// external commit. The commit's changes (including any AppDataUpdate
1922    /// proposals) are not applied to it. The joined group's context is
1923    /// available on the [`MlsGroup`] returned by [`Self::into_group`].
1924    pub fn prior_group_context(&self) -> &GroupContext {
1925        self.group.context()
1926    }
1927
1928    /// Returns an iterator over the [`Member`]s of the group at the epoch
1929    /// *before* the external commit. The commit's changes are not applied:
1930    /// the committing sibling's virtual-client leaf is absent and members
1931    /// the commit inline-removes are still present.
1932    pub fn prior_members(&self) -> impl Iterator<Item = Member> + '_ {
1933        self.group.members()
1934    }
1935
1936    /// Returns the AppDataUpdate proposals covered by the commit, sorted by
1937    /// component id. The application interprets them to compute the
1938    /// [`AppDataUpdates`] that [`Self::into_group`] requires.
1939    pub fn app_data_update_proposals(&self) -> impl Iterator<Item = &AppDataUpdateProposal> {
1940        self.app_data_update_proposals.iter()
1941    }
1942
1943    /// Returns the AppEphemeral proposals for `component_id` that the commit
1944    /// carries by value, in the order they appear in the commit, for example
1945    /// to decide how to follow the join. Unlike
1946    /// [`PublicMessageIn::unverified_app_ephemeral_proposals`], the returned
1947    /// data is authenticated: the commit's signature has been verified.
1948    ///
1949    /// [`PublicMessageIn::unverified_app_ephemeral_proposals`]:
1950    ///     crate::framing::PublicMessageIn::unverified_app_ephemeral_proposals
1951    pub fn app_ephemeral_proposals_for_component_id(
1952        &self,
1953        component_id: ComponentId,
1954    ) -> impl Iterator<Item = &AppEphemeralProposal> {
1955        let proposals = match self.content.content() {
1956            FramedContentBody::Commit(commit) => commit.proposals.as_slice(),
1957            // `process_commit` only constructs staged joins from commits.
1958            _ => &[],
1959        };
1960        proposals
1961            .iter()
1962            .filter_map(move |proposal_or_ref| match proposal_or_ref {
1963                ProposalOrRef::Proposal(proposal) => match proposal.as_ref() {
1964                    Proposal::AppEphemeral(app_ephemeral)
1965                        if app_ephemeral.component_id() == component_id =>
1966                    {
1967                        Some(app_ephemeral.as_ref())
1968                    }
1969                    _ => None,
1970                },
1971                ProposalOrRef::Reference(_) => None,
1972            })
1973    }
1974
1975    /// Returns a helper for computing the [`AppDataUpdates`], seeded with
1976    /// the app data dictionary of the prior-epoch group context.
1977    pub fn app_data_dictionary_updater(&self) -> AppDataDictionaryUpdater<'_> {
1978        AppDataDictionaryUpdater::new(self.group.context().app_data_dict())
1979    }
1980
1981    /// Sets the [`AppDataUpdates`] that contain the changes made by the
1982    /// commit's AppDataUpdate proposals. Updates must be set exactly when
1983    /// the commit covers AppDataUpdate proposals.
1984    pub fn with_app_data_dictionary_updates(&mut self, app_data_updates: Option<AppDataUpdates>) {
1985        self.app_data_updates = app_data_updates;
1986    }
1987
1988    /// Completes the join and returns the joined [`MlsGroup`]. If the commit
1989    /// covers AppDataUpdate proposals, the resolved updates must have been
1990    /// set via [`Self::with_app_data_dictionary_updates`]. Absent updates
1991    /// are rejected before the consume-once operation secret generation is
1992    /// spent, so the join can be started over. Updates that do not reproduce
1993    /// the committing sibling's dictionary fail with a confirmation tag
1994    /// mismatch after the generation is consumed, so they should be computed
1995    /// deterministically from the proposals rather than guessed.
1996    #[openmls_traits::maybe_async]
1997    pub async fn into_group<Provider: OpenMlsProvider>(
1998        self,
1999        provider: &Provider,
2000    ) -> Result<MlsGroup, VcExternalCommitJoinError<Provider::StorageError>> {
2001        type Error<S> = VcExternalCommitJoinError<S>;
2002
2003        let Self {
2004            mut group,
2005            content,
2006            app_data_update_proposals,
2007            app_data_updates,
2008        } = self;
2009
2010        // An application that has not resolved the commit's AppDataUpdate
2011        // proposals yet is rejected before the operation secret generation
2012        // is consumed, so it can compute the updates and process the commit
2013        // again. Staging repeats this check. Superfluous updates are only
2014        // rejected there.
2015        if !app_data_update_proposals.is_empty() && app_data_updates.is_none() {
2016            return Err(StageCommitError::ApplyAppDataUpdateError(
2017                ApplyAppDataUpdateError::MissingAppDataUpdates,
2018            )
2019            .into());
2020        }
2021
2022        let FramedContentBody::Commit(commit) = content.content() else {
2023            // `process_commit` only constructs staged joins from commits.
2024            return Err(LibraryError::custom("staged join without commit content").into());
2025        };
2026
2027        // Recover the sibling-VC commit material (operation secret + emulation
2028        // epoch id + carried external init secret) from the leaf's derivation
2029        // info, then stage and merge the commit through the sibling-VC path.
2030        let material = group
2031            .load_vc_commit_material(provider, commit)
2032            .await?
2033            .ok_or(Error::MissingDerivationInfo)?;
2034        let staged = group
2035            .stage_commit_with_app_data_updates(
2036                &content,
2037                vec![],
2038                vec![],
2039                app_data_updates,
2040                provider,
2041                // An external commit carries no Add proposals.
2042                LeafNodeLifetimePolicy::Verify,
2043                Some(material),
2044            )
2045            .await?;
2046        group.merge_staged_commit(provider, staged).await?;
2047        let deletion_policy = group.mls_group_config.past_epoch_deletion_policy().clone();
2048        group.resize_message_secrets_store(&deletion_policy);
2049        group
2050            .store(provider.storage())
2051            .await
2052            .map_err(Error::StorageError)?;
2053        Ok(group)
2054    }
2055}
2056
2057/// How the lifetime of a leaf node is checked.
2058#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
2059pub enum LeafNodeLifetimePolicy {
2060    /// Check the lifetime against the current time.
2061    #[default]
2062    Verify,
2063
2064    /// Do not check the lifetime.
2065    Skip,
2066
2067    /// Check the lifetime against the given time, in seconds since the Unix
2068    /// epoch, instead of the current time.
2069    VerifyAt(u64),
2070}
2071
2072/// Builder for joining a group.
2073///
2074/// Create this with [`StagedWelcome::build_from_welcome`].
2075pub struct JoinBuilder<'a, Provider: OpenMlsProvider> {
2076    provider: &'a Provider,
2077    processed_welcome: ProcessedWelcome,
2078    ratchet_tree: Option<RatchetTreeIn>,
2079    validate_lifetimes: LeafNodeLifetimePolicy,
2080    replace_old_group: bool,
2081    /// Set when joining a subgroup branch (see [`StagedWelcome::build_from_branch`]),
2082    /// or when joining a reinitialized group (see [`StagedWelcome::build_from_reinit`]).
2083    /// Triggers the receiver checks in [`Self::build`].
2084    resumption_info: Option<ResumptionInfo>,
2085    /// Whether to check the new group's members against the parent or old
2086    /// group by credential. Only relevant when [`Self::resumption_info`] is set.
2087    /// Defaults to `true`.
2088    check_members: bool,
2089}
2090
2091impl<'a, Provider: OpenMlsProvider> JoinBuilder<'a, Provider> {
2092    /// Create a new builder for the [`JoinBuilder`].
2093    pub fn new(provider: &'a Provider, processed_welcome: ProcessedWelcome) -> Self {
2094        Self {
2095            provider,
2096            processed_welcome,
2097            ratchet_tree: None,
2098            replace_old_group: false,
2099            validate_lifetimes: LeafNodeLifetimePolicy::Verify,
2100            resumption_info: None,
2101            check_members: true,
2102        }
2103    }
2104
2105    /// Seed this builder with the parent group's [`BranchInfo`] or predecessor's [`ReInitInfo`],
2106    /// turning it into a subgroup-branch join (see [`StagedWelcome::build_from_branch`]) or
2107    /// reinit join (see [`StagedWelcome::build_from_reinit`]).
2108    fn with_resumption_info(mut self, resumption_info: ResumptionInfo) -> Self {
2109        self.resumption_info = Some(resumption_info);
2110        self
2111    }
2112    /// When joining a subgroup branch or a reinitialized group, controls
2113    /// whether [`Self::build`] checks the new group's members by credential
2114    /// equality. Defaults to `true`.
2115    ///
2116    /// **Note**: This is a shortcut for members that are equivalent when credentials
2117    /// are equal. For more complex member equivalence conditions, the application must disable
2118    /// this and perform the equivalence check itself.
2119    ///
2120    /// For a subgroup branch, every subgroup member must also be a member of
2121    /// the parent group (receiver check (c)). For a reinit, the new group's
2122    /// member credentials must be identical to the old group's.
2123    ///
2124    /// This has no effect on a regular (non-branch, non-reinit) join.
2125    pub fn check_members(mut self, check_members: bool) -> Self {
2126        self.check_members = check_members;
2127        self
2128    }
2129
2130    /// The ratchet tree to use for the new group.
2131    pub fn with_ratchet_tree(mut self, ratchet_tree: RatchetTreeIn) -> Self {
2132        self.ratchet_tree = Some(ratchet_tree);
2133        self
2134    }
2135
2136    /// Instruct the builder to replace any existing group with the same ID.
2137    pub fn replace_old_group(mut self) -> Self {
2138        self.replace_old_group = true;
2139        self
2140    }
2141
2142    /// Skip the validation of lifetimes in leaf nodes in the ratchet tree.
2143    /// Note that only the leaf nodes are checked that were never updated.
2144    ///
2145    /// By default they are validated.
2146    pub fn skip_lifetime_validation(mut self) -> Self {
2147        self.validate_lifetimes = LeafNodeLifetimePolicy::Skip;
2148        self
2149    }
2150
2151    /// Sets how the lifetimes of leaf nodes in the ratchet tree are checked.
2152    /// [`Self::skip_lifetime_validation`] is the same as passing
2153    /// [`LeafNodeLifetimePolicy::Skip`].
2154    pub fn leaf_node_lifetime_policy(mut self, lifetime_policy: LeafNodeLifetimePolicy) -> Self {
2155        self.validate_lifetimes = lifetime_policy;
2156        self
2157    }
2158
2159    /// Get a reference to the [`ProcessedWelcome`].
2160    ///
2161    /// Use this to inspect the [`Welcome`] message before validation.
2162    pub fn processed_welcome(&self) -> &ProcessedWelcome {
2163        &self.processed_welcome
2164    }
2165
2166    /// Build the [`StagedWelcome`].
2167    #[openmls_traits::maybe_async]
2168    pub async fn build(self) -> Result<StagedWelcome, WelcomeError<Provider::StorageError>> {
2169        // Receiver checks (a) and (b): when joining a subgroup branch, the
2170        // version and ciphersuite must match the parent group, and the subgroup
2171        // must be at epoch 1.
2172        match &self.resumption_info {
2173            Some(ResumptionInfo::Branch(branch_info)) => {
2174                let group_info = self.processed_welcome.unverified_group_info();
2175                if group_info.group_context().protocol_version() != branch_info.version()
2176                    || group_info.ciphersuite() != branch_info.ciphersuite()
2177                {
2178                    return Err(WelcomeError::SubgroupParameterMismatch);
2179                }
2180                if group_info.group_context().epoch().as_u64() != 1 {
2181                    return Err(WelcomeError::SubgroupEpochInvalid);
2182                }
2183            }
2184            Some(ResumptionInfo::ReInit(reinit_info)) => {
2185                // RFC 9420 §11.2 receiver checks: the successor's parameters must match
2186                // the ReInit proposal, and it must be at epoch 1.
2187                let group_info = self.processed_welcome.unverified_group_info();
2188                let group_context = group_info.group_context();
2189                let reinit_proposal = reinit_info.proposal();
2190                // https://validation.openmls.tech/#valn1413 (parameters match the ReInit
2191                // proposal).
2192                if group_context.protocol_version() != reinit_proposal.version()
2193                    || group_context.ciphersuite() != reinit_proposal.ciphersuite()
2194                    || group_context.group_id() != reinit_proposal.group_id()
2195                    || group_context.extensions() != reinit_proposal.extensions()
2196                {
2197                    return Err(WelcomeError::ReInitParameterMismatch);
2198                }
2199                // https://validation.openmls.tech/#valn1412 (reinit/branch PSK => epoch 1).
2200                if group_context.epoch().as_u64() != 1 {
2201                    return Err(WelcomeError::ReInitEpochInvalid);
2202                }
2203            }
2204            None => {}
2205        }
2206
2207        let staged_welcome = self
2208            .processed_welcome
2209            .into_staged_welcome_inner(
2210                self.provider,
2211                self.ratchet_tree,
2212                self.validate_lifetimes,
2213                self.replace_old_group,
2214            )
2215            .await?;
2216
2217        // Receiver check (c): every LeafNode in the subgroup must
2218        // match a LeafNode in the parent group. For a reinit, the members
2219        // must be identical to the old group's.
2220        // Member equivalence is an application responsibility.
2221        // This is a shortcut for a simple case, matching credentials with multiset semantics.
2222        if self.check_members {
2223            if let Some(resumption_info) = &self.resumption_info {
2224                let mut unseen_old_credentials: Vec<_> =
2225                    resumption_info.member_credentials().to_vec();
2226                for new_member in staged_welcome.members() {
2227                    if let Some(parent_index) = unseen_old_credentials
2228                        .iter()
2229                        .position(|m| m == &new_member.credential)
2230                    {
2231                        unseen_old_credentials.swap_remove(parent_index);
2232                    } else {
2233                        // The new group contains a member the source group doesn't.
2234                        return match resumption_info {
2235                            ResumptionInfo::Branch(_) => Err(WelcomeError::SubgroupLeafMismatch),
2236                            ResumptionInfo::ReInit(_) => Err(WelcomeError::ReInitLeafMismatch),
2237                        };
2238                    }
2239                }
2240                if matches!(resumption_info, ResumptionInfo::ReInit(_))
2241                    && !unseen_old_credentials.is_empty()
2242                {
2243                    // The predecessor contained a member that is missing in the new group.
2244                    return Err(WelcomeError::ReInitLeafMismatch);
2245                }
2246            }
2247        }
2248
2249        Ok(staged_welcome)
2250    }
2251}