Skip to main content

openmls/group/mls_group/
builder.rs

1use openmls_traits::{crypto::OpenMlsCrypto, signatures::Signer, types::Ciphersuite};
2use tls_codec::Serialize;
3
4#[cfg(feature = "extensions-draft")]
5use crate::schedule::application_export_tree::ApplicationExportTree;
6use crate::{
7    binary_tree::{array_representation::TreeSize, LeafNodeIndex},
8    credentials::CredentialWithKey,
9    error::LibraryError,
10    extensions::Extensions,
11    group::{
12        config::PastEpochDeletionPolicy, past_secrets::MessageSecretsStore,
13        public_group::errors::PublicGroupBuildError, BranchInfo, CommitBuilderStageError,
14        CommitMessageBundle, CreateCommitError, GroupContext, GroupId, LeafNodeLifetimePolicy,
15        MlsGroup, MlsGroupCreateConfig, MlsGroupCreateConfigBuilder, MlsGroupState, NewGroupError,
16        PublicGroup, ReInitInfo, WireFormatPolicy,
17    },
18    key_packages::{KeyPackage, Lifetime},
19    schedule::{
20        psk::{load_psks, store::ResumptionPskStore, PskSecret},
21        EpochSecretsResult, InitSecret, JoinerSecret, KeySchedule, PreSharedKeyId,
22    },
23    storage::OpenMlsProvider,
24    tree::sender_ratchet::SenderRatchetConfiguration,
25    treesync::{
26        errors::LeafNodeValidationError,
27        node::leaf_node::{Capabilities, CapabilitiesPolicy, LeafNode},
28    },
29};
30
31#[cfg(feature = "virtual-clients-draft")]
32use crate::treesync::node::leaf_node::{resolve_capabilities, LeafNodeConstraints};
33
34/// Builder struct for an [`MlsGroup`].
35#[derive(Default, Debug)]
36pub struct MlsGroupBuilder {
37    group_id: Option<GroupId>,
38    mls_group_create_config_builder: MlsGroupCreateConfigBuilder,
39    replace_old_group: bool,
40    psk_ids: Vec<PreSharedKeyId>,
41    /// The emulation group to create this group as a virtual client of. The
42    /// derivation epoch is resolved from its state when [`Self::build`] runs.
43    #[cfg(feature = "virtual-clients-draft")]
44    vc_emulation_group_id: Option<GroupId>,
45}
46
47impl MlsGroupBuilder {
48    pub(super) fn new() -> Self {
49        Self::default()
50    }
51
52    /// Sets the group ID of the [`MlsGroup`].
53    pub fn with_group_id(mut self, group_id: GroupId) -> Self {
54        self.group_id = Some(group_id);
55        self
56    }
57
58    /// Create the group as a virtual client of the emulation group named by
59    /// `emulation_group_id`.
60    ///
61    /// The group is created from the newest derivation epoch of the emulation
62    /// group, which is what the draft requires of every new virtual-client
63    /// operation. The epoch is resolved when [`Self::build`] runs, against the
64    /// emulation group's state at that point.
65    ///
66    /// The creator's leaf is `key_package`-sourced and its key material is
67    /// derived from a fresh `key_package` operation secret of that epoch (so
68    /// sibling emulator clients can reconstruct it), and the epoch-0
69    /// `epoch_secret` is derived from the same KeyPackage seed rather than
70    /// transmitted. Siblings bootstrap into the group with
71    /// [`MlsGroup::vc_join_at_creation`].
72    ///
73    /// [`MlsGroup::vc_join_at_creation`]: crate::group::MlsGroup::vc_join_at_creation
74    #[cfg(feature = "virtual-clients-draft")]
75    pub fn vc_emulation(mut self, emulation_group_id: &GroupId) -> Self {
76        self.vc_emulation_group_id = Some(emulation_group_id.clone());
77        self
78    }
79
80    /// Instruct the builder to replace any existing group with the same ID.
81    pub fn replace_old_group(mut self) -> Self {
82        self.replace_old_group = true;
83        self
84    }
85
86    /// Turn this builder into a [`BranchGroupBuilder`] to build a sub-group
87    /// [RFC 9420 §11.3].
88    ///
89    /// The parent group's parameters are provided via `branch_info`, which the
90    /// parent exports with
91    /// [`MlsGroup::branch_info`](crate::group::MlsGroup::branch_info). The
92    /// sub-group is created with the parent's ciphersuite. Set any other group
93    /// configuration on this builder before calling `branch`, then create the
94    /// sub-group and its branch commit with
95    /// [`BranchGroupBuilder::build_branch`].
96    ///
97    /// [RFC 9420 §11.3]: https://www.rfc-editor.org/rfc/rfc9420.html#name-subgroup-branching
98    pub fn branch(self, branch_info: BranchInfo) -> BranchGroupBuilder {
99        BranchGroupBuilder {
100            group_builder: self,
101            branch_info,
102            extensions: None,
103            force_self_update: false,
104            lifetime_policy: LeafNodeLifetimePolicy::Verify,
105        }
106    }
107
108    /// Turn this builder into a [`ReInitGroupBuilder`] to build a reinitialized successor
109    /// group [RFC 9420 §11.2].
110    ///
111    /// The reinit parameters are provided via `reinit_info`, which the predecessor
112    /// exports with [`MlsGroup::reinit_info`](crate::group::MlsGroup::reinit_info).
113    /// The successor is created with the ReInit proposal's protocol version, group_id,
114    /// ciphersuite, group_context extensions. Set any other group
115    /// configuration on this builder before calling `reinit`, then create the
116    /// new group and its reinit commit with
117    /// [`ReInitGroupBuilder::build_reinit`].
118    ///
119    /// [RFC 9420 §11.2]: https://www.rfc-editor.org/rfc/rfc9420.html#name-reinitialization
120    pub fn reinit(self, reinit_info: ReInitInfo) -> ReInitGroupBuilder {
121        ReInitGroupBuilder {
122            group_builder: self,
123            reinit_info,
124            force_self_update: false,
125        }
126    }
127
128    /// Build a new group as configured by this builder.
129    #[openmls_traits::maybe_async]
130    pub async fn build<Provider: OpenMlsProvider>(
131        self,
132        provider: &Provider,
133        signer: &impl Signer,
134        credential_with_key: CredentialWithKey,
135    ) -> Result<MlsGroup, NewGroupError<Provider::StorageError>> {
136        self.build_internal(provider, signer, credential_with_key, None)
137            .await
138    }
139
140    /// Build a new group with the given group ID.
141    ///
142    /// If an [`MlsGroupCreateConfig`] is provided, it will be used to configure the
143    /// group. Otherwise, the internal builder is used to build one with the
144    /// parameters set on this builder.
145    ///
146    /// If a group with the same ID already exists in storage and
147    /// `replace_old_group` was not set, an error will be returned.
148    #[openmls_traits::maybe_async]
149    pub(super) async fn build_internal<Provider: OpenMlsProvider>(
150        self,
151        provider: &Provider,
152        signer: &impl Signer,
153        credential_with_key: CredentialWithKey,
154        mls_group_create_config_option: Option<MlsGroupCreateConfig>,
155    ) -> Result<MlsGroup, NewGroupError<Provider::StorageError>> {
156        let mls_group_create_config = mls_group_create_config_option
157            .unwrap_or_else(|| self.mls_group_create_config_builder.build());
158        let group_id = self
159            .group_id
160            .unwrap_or_else(|| GroupId::random(provider.rand()));
161        let ciphersuite = mls_group_create_config.ciphersuite;
162
163        provider
164            .crypto()
165            .supports(ciphersuite)
166            .map_err(|_| NewGroupError::UnsupportedCiphersuite(ciphersuite))?;
167
168        #[cfg(feature = "virtual-clients-draft")]
169        if let Some(emulation_group_id) = &self.vc_emulation_group_id {
170            let epoch_id =
171                crate::components::vc_derivation_info::require_newest_vc_derivation_epoch(
172                    provider.storage(),
173                    emulation_group_id,
174                )
175                .await?;
176            return build_vc_internal(
177                provider,
178                signer,
179                credential_with_key,
180                mls_group_create_config,
181                group_id,
182                self.replace_old_group,
183                epoch_id,
184            )
185            .await;
186        }
187
188        if !self.replace_old_group
189            && MlsGroup::load(provider.storage(), &group_id)
190                .await
191                .map_err(NewGroupError::StorageError)?
192                .is_some()
193        {
194            return Err(NewGroupError::GroupAlreadyExists);
195        }
196
197        let (public_group_builder, commit_secret, leaf_keypair) =
198            PublicGroup::builder(group_id, ciphersuite, credential_with_key)
199                .with_group_context_extensions(
200                    mls_group_create_config.group_context_extensions.clone(),
201                )
202                .with_leaf_node_extensions(mls_group_create_config.leaf_node_extensions.clone())
203                .with_lifetime(*mls_group_create_config.lifetime())
204                .with_capabilities(mls_group_create_config.capabilities.clone())
205                .with_capabilities_policy(mls_group_create_config.capabilities_policy)
206                .get_secrets(provider, signer)
207                .map_err(|e| match e {
208                    PublicGroupBuildError::LibraryError(e) => NewGroupError::LibraryError(e),
209                    PublicGroupBuildError::InvalidExtensions(e) => e.into(),
210                    PublicGroupBuildError::LeafNodeBuild(e) => e.into(),
211                })?;
212
213        let serialized_group_context = public_group_builder
214            .group_context()
215            .tls_serialize_detached()
216            .map_err(LibraryError::missing_bound_check)?;
217
218        // Derive an initial joiner secret based on the commit secret.
219        // Derive an epoch secret from the joiner secret.
220        // We use a random `InitSecret` for initialization.
221        let joiner_secret = JoinerSecret::new(
222            provider.crypto(),
223            ciphersuite,
224            commit_secret,
225            &InitSecret::random(ciphersuite, provider.rand())
226                .map_err(LibraryError::unexpected_crypto_error)?,
227            &serialized_group_context,
228        )
229        .map_err(LibraryError::unexpected_crypto_error)?;
230
231        // TODO(#1357)
232        let mut resumption_psk_store = ResumptionPskStore::new(32);
233
234        // Prepare the PskSecret
235        let psk_secret = load_psks(
236            provider.storage(),
237            &resumption_psk_store,
238            Some(public_group_builder.group_context().group_id()),
239            None,
240            &self.psk_ids,
241        )
242        .await
243        .and_then(|psks| PskSecret::new(provider.crypto(), ciphersuite, psks))
244        .map_err(|e| {
245            log::debug!("Unexpected PSK error: {e:?}");
246            LibraryError::custom("Unexpected PSK error")
247        })?;
248
249        let mut key_schedule =
250            KeySchedule::init(ciphersuite, provider.crypto(), &joiner_secret, psk_secret)?;
251        key_schedule
252            .add_context(provider.crypto(), &serialized_group_context)
253            .map_err(|_| LibraryError::custom("Using the key schedule in the wrong state"))?;
254
255        let EpochSecretsResult {
256            epoch_secrets,
257            #[cfg(feature = "extensions-draft")]
258            application_exporter,
259        } = key_schedule
260            .epoch_secrets(provider.crypto(), ciphersuite)
261            .map_err(|_| LibraryError::custom("Using the key schedule in the wrong state"))?;
262
263        let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
264            serialized_group_context,
265            TreeSize::new(1),
266            LeafNodeIndex::new(0u32),
267        );
268
269        let initial_confirmation_tag = message_secrets
270            .confirmation_key()
271            .tag(provider.crypto(), ciphersuite, &[])
272            .map_err(LibraryError::unexpected_crypto_error)?;
273
274        let message_secrets_store = MessageSecretsStore::new_with_secret(
275            mls_group_create_config
276                .join_config
277                .past_epoch_deletion_policy(),
278            message_secrets,
279        );
280
281        let public_group = public_group_builder
282            .with_confirmation_tag(initial_confirmation_tag)
283            .build(provider.crypto())?;
284
285        // We already add a resumption PSK for epoch 0 to make things more unified.
286        let resumption_psk = group_epoch_secrets.resumption_psk();
287        resumption_psk_store.add(public_group.group_context().epoch(), resumption_psk.clone());
288
289        #[cfg(feature = "extensions-draft")]
290        #[cfg_attr(not(feature = "virtual-clients-draft"), allow(unused_mut))]
291        let mut application_export_tree = ApplicationExportTree::new(application_exporter);
292
293        // The initial epoch of an emulation group is a derivation epoch.
294        #[cfg(feature = "virtual-clients-draft")]
295        if mls_group_create_config.emulation_group {
296            crate::components::vc_derivation_info::register_vc_derivation_epoch(
297                provider.crypto(),
298                provider.storage(),
299                Some(&mut application_export_tree),
300                crate::components::vc_derivation_info::VcDerivationEpochParams::for_public_group(
301                    &public_group,
302                    LeafNodeIndex::new(0),
303                    mls_group_create_config
304                        .join_config
305                        .vc_derivation_epoch_retention_policy()
306                        .clone(),
307                ),
308            )
309            .await?;
310        }
311
312        let mls_group = MlsGroup {
313            mls_group_config: mls_group_create_config.join_config.clone(),
314            own_leaf_nodes: vec![],
315            aad: vec![],
316            #[cfg(feature = "extensions-draft")]
317            safe_aad: crate::framing::SafeAad::empty(),
318            group_state: MlsGroupState::Operational,
319            public_group,
320            group_epoch_secrets,
321            own_leaf_index: LeafNodeIndex::new(0),
322            message_secrets_store,
323            resumption_psk_store,
324            #[cfg(feature = "extensions-draft")]
325            application_export_tree: Some(application_export_tree),
326            #[cfg(feature = "virtual-clients-draft")]
327            emulation_group: mls_group_create_config.emulation_group,
328        };
329
330        mls_group
331            .store(provider.storage())
332            .await
333            .map_err(NewGroupError::StorageError)?;
334        mls_group
335            .store_epoch_keypairs(provider.storage(), &[leaf_keypair])
336            .await
337            .map_err(NewGroupError::StorageError)?;
338
339        Ok(mls_group)
340    }
341
342    // MlsGroupCreateConfigBuilder options
343
344    /// Sets the `wire_format` property of the MlsGroup.
345    pub fn with_wire_format_policy(mut self, wire_format_policy: WireFormatPolicy) -> Self {
346        self.mls_group_create_config_builder = self
347            .mls_group_create_config_builder
348            .wire_format_policy(wire_format_policy);
349        self
350    }
351
352    /// Sets the `padding_size` property of the MlsGroup.
353    pub fn padding_size(mut self, padding_size: usize) -> Self {
354        self.mls_group_create_config_builder = self
355            .mls_group_create_config_builder
356            .padding_size(padding_size);
357        self
358    }
359
360    /// Sets the `max_past_epochs` property of the MlsGroup.
361    /// This allows application messages from previous epochs to be decrypted.
362    ///
363    /// This method overrides the policy set by [`Self::set_past_epoch_deletion_policy()`],
364    /// and is equivalent to setting the past epoch deletion policy to
365    /// `PastEpochDeletionPolicy::MaxEpochs(max_past_epochs)`.
366    ///
367    /// **WARNING**
368    ///
369    ///
370    /// This feature enables the storage of message secrets from past epochs.
371    /// It is a trade-off between functionality and forward secrecy and should only be enabled
372    /// if the Delivery Service cannot guarantee that application messages will be sent in
373    /// the same epoch in which they were generated. The number for `max_epochs` should be
374    /// as low as possible.
375    ///
376    /// NOTE: This function will be deprecated in future releases.
377    pub fn max_past_epochs(mut self, max_past_epochs: usize) -> Self {
378        self.mls_group_create_config_builder = self
379            .mls_group_create_config_builder
380            .max_past_epochs(max_past_epochs);
381        self
382    }
383
384    /// Set the policy for deleting past epoch secrets.
385    ///
386    /// By default, storage of past epoch secrets is disabled.
387    ///
388    /// This method overrides the configuration set by [`Self::max_past_epochs()`].
389    ///
390    /// **WARNING**
391    ///
392    /// This feature enables the storage of message secrets from past epochs.
393    /// It is a trade-off between functionality and forward secrecy and should only be enabled
394    /// if the Delivery Service cannot guarantee that application messages will be sent in
395    /// the same epoch in which they were generated. The number for `max_epochs` should be
396    /// as low as possible.
397    pub fn set_past_epoch_deletion_policy(mut self, policy: PastEpochDeletionPolicy) -> Self {
398        self.mls_group_create_config_builder = self
399            .mls_group_create_config_builder
400            .set_past_epoch_deletion_policy(policy);
401        self
402    }
403
404    /// Sets the derivation-epoch retention policy. See
405    /// [`VcDerivationEpochRetentionPolicy`](crate::group::VcDerivationEpochRetentionPolicy).
406    #[cfg(feature = "virtual-clients-draft")]
407    pub fn set_vc_derivation_epoch_retention_policy(
408        mut self,
409        policy: crate::group::VcDerivationEpochRetentionPolicy,
410    ) -> Self {
411        self.mls_group_create_config_builder = self
412            .mls_group_create_config_builder
413            .set_vc_derivation_epoch_retention_policy(policy);
414        self
415    }
416
417    /// Sets the `number_of_resumption_psks` property of the MlsGroup.
418    pub fn number_of_resumption_psks(mut self, number_of_resumption_psks: usize) -> Self {
419        self.mls_group_create_config_builder = self
420            .mls_group_create_config_builder
421            .number_of_resumption_psks(number_of_resumption_psks);
422        self
423    }
424
425    /// Sets the `use_ratchet_tree_extension` property of the MlsGroup.
426    pub fn use_ratchet_tree_extension(mut self, use_ratchet_tree_extension: bool) -> Self {
427        self.mls_group_create_config_builder = self
428            .mls_group_create_config_builder
429            .use_ratchet_tree_extension(use_ratchet_tree_extension);
430        self
431    }
432
433    /// Sets the `sender_ratchet_configuration` property of the MlsGroup.
434    /// See [`SenderRatchetConfiguration`] for more information.
435    pub fn sender_ratchet_configuration(
436        mut self,
437        sender_ratchet_configuration: SenderRatchetConfiguration,
438    ) -> Self {
439        self.mls_group_create_config_builder = self
440            .mls_group_create_config_builder
441            .sender_ratchet_configuration(sender_ratchet_configuration);
442        self
443    }
444
445    /// Sets the `lifetime` of the group creator's leaf.
446    pub fn lifetime(mut self, lifetime: Lifetime) -> Self {
447        self.mls_group_create_config_builder =
448            self.mls_group_create_config_builder.lifetime(lifetime);
449        self
450    }
451
452    /// Sets the `ciphersuite` of the MlsGroup.
453    pub fn ciphersuite(mut self, ciphersuite: Ciphersuite) -> Self {
454        self.mls_group_create_config_builder = self
455            .mls_group_create_config_builder
456            .ciphersuite(ciphersuite);
457        self
458    }
459
460    /// Sets the initial group context extensions
461    pub fn with_group_context_extensions(mut self, extensions: Extensions<GroupContext>) -> Self {
462        self.mls_group_create_config_builder = self
463            .mls_group_create_config_builder
464            .with_group_context_extensions(extensions);
465        self
466    }
467
468    /// Sets the initial leaf node extensions
469    pub fn with_leaf_node_extensions(
470        mut self,
471        extensions: Extensions<LeafNode>,
472    ) -> Result<Self, LeafNodeValidationError> {
473        self.mls_group_create_config_builder = self
474            .mls_group_create_config_builder
475            .with_leaf_node_extensions(extensions)?;
476        Ok(self)
477    }
478
479    /// Sets the group creator's [`Capabilities`]
480    ///
481    /// See [`MlsGroupCreateConfigBuilder::capabilities`] for what setting them
482    /// explicitly implies.
483    pub fn with_capabilities(mut self, capabilities: Capabilities) -> Self {
484        self.mls_group_create_config_builder = self
485            .mls_group_create_config_builder
486            .capabilities(capabilities);
487        self
488    }
489
490    /// Sets how the group creator's [`Capabilities`] are treated when they
491    /// don't cover what the leaf needs.
492    ///
493    /// See [`MlsGroupCreateConfigBuilder::capabilities_policy`].
494    pub fn with_capabilities_policy(mut self, policy: CapabilitiesPolicy) -> Self {
495        self.mls_group_create_config_builder = self
496            .mls_group_create_config_builder
497            .capabilities_policy(policy);
498        self
499    }
500}
501
502/// Builder that creates a fresh sub-group and its branch commit in a single
503/// step, as described in [RFC 9420 §11.3].
504///
505/// Create this with [`MlsGroupBuilder::branch`].
506///
507/// [RFC 9420 §11.3]: https://www.rfc-editor.org/rfc/rfc9420.html#name-subgroup-branching
508pub struct BranchGroupBuilder {
509    group_builder: MlsGroupBuilder,
510    branch_info: BranchInfo,
511    extensions: Option<Extensions<GroupContext>>,
512    force_self_update: bool,
513    lifetime_policy: LeafNodeLifetimePolicy,
514}
515
516impl BranchGroupBuilder {
517    /// Add a [`GroupContextExtensions`](crate::extensions::Extensions) proposal
518    /// to the branch commit. See
519    /// [`CommitBuilder::propose_group_context_extensions`](crate::group::CommitBuilder::propose_group_context_extensions).
520    pub fn propose_group_context_extensions(
521        mut self,
522        extensions: Extensions<GroupContext>,
523    ) -> Self {
524        self.extensions = Some(extensions);
525        self
526    }
527
528    /// Force a self-update (path) in the branch commit. See
529    /// [`CommitBuilder::force_self_update`](crate::group::CommitBuilder::force_self_update).
530    pub fn force_self_update(mut self, force_self_update: bool) -> Self {
531        self.force_self_update = force_self_update;
532        self
533    }
534
535    /// Sets how the lifetimes of the key packages of the new members are
536    /// checked. See
537    /// [`CommitBuilder::leaf_node_lifetime_policy`](crate::group::CommitBuilder::leaf_node_lifetime_policy).
538    pub fn leaf_node_lifetime_policy(mut self, lifetime_policy: LeafNodeLifetimePolicy) -> Self {
539        self.lifetime_policy = lifetime_policy;
540        self
541    }
542
543    /// Create the sub-group and the branch commit that adds `new_members` to it.
544    ///
545    /// This creates a fresh group with the parent's ciphersuite, adds the branch
546    /// resumption PSK (mixing in the parent's resumption PSK secret), and commits
547    /// the additions (plus any extra proposals set via
548    /// [`Self::propose_group_context_extensions`] / [`Self::force_self_update`]).
549    /// It returns the new (epoch-0) sub-group and the [`CommitMessageBundle`]
550    /// carrying the branch commit and `Welcome`.
551    ///
552    /// The commit is staged but **not** merged: merge it with
553    /// [`MlsGroup::merge_pending_commit`](crate::group::MlsGroup::merge_pending_commit)
554    /// only once the delivery service has confirmed it.
555    #[openmls_traits::maybe_async]
556    pub async fn build_branch<Provider: OpenMlsProvider>(
557        self,
558        provider: &Provider,
559        signer: &impl Signer,
560        credential_with_key: CredentialWithKey,
561        new_members: Vec<KeyPackage>,
562    ) -> Result<(MlsGroup, CommitMessageBundle), BranchError<Provider::StorageError>> {
563        // The sub-group must use the same ciphersuite as the parent group.
564        let group_builder = self
565            .group_builder
566            .ciphersuite(self.branch_info.ciphersuite());
567        let mut group = group_builder
568            .build(provider, signer, credential_with_key)
569            .await?;
570
571        let mut builder = group
572            .commit_builder()
573            .branch(provider.rand(), &self.branch_info)?
574            .propose_adds(new_members)
575            .leaf_node_lifetime_policy(self.lifetime_policy);
576        if let Some(extensions) = self.extensions {
577            builder = builder.propose_group_context_extensions(extensions)?;
578        }
579        if self.force_self_update {
580            builder = builder.force_self_update(true);
581        }
582        let bundle = builder
583            .load_psks(provider.storage())
584            .await?
585            .build(provider.rand(), provider.crypto(), signer, |_| true)?
586            .stage_commit(provider)
587            .await?;
588
589        Ok((group, bundle))
590    }
591}
592
593/// Indicates an error occurred while creating a sub-group branch with
594/// [`BranchGroupBuilder::build_branch`].
595#[derive(Debug, thiserror::Error)]
596pub enum BranchError<StorageError> {
597    /// An error occurred while creating the sub-group.
598    #[error(transparent)]
599    NewGroup(#[from] NewGroupError<StorageError>),
600    /// An error occurred while creating the branch commit.
601    #[error(transparent)]
602    CreateCommit(#[from] CreateCommitError),
603    /// An error occurred while staging the branch commit.
604    #[error(transparent)]
605    CommitBuilderStage(#[from] CommitBuilderStageError<StorageError>),
606}
607
608/// Builder that creates a freshly reinitialized group and its reinit commit in a single
609/// step, as described in [RFC 9420 §11.2].
610///
611/// This overrides the group_id, ciphersuite and group_context.extensions of the group_builder
612/// with value from the ReInit proposal.
613///
614/// Create this with [`MlsGroupBuilder::reinit`].
615///
616/// [RFC 9420 §11.2]: https://www.rfc-editor.org/rfc/rfc9420.html#name-reinitialization
617pub struct ReInitGroupBuilder {
618    group_builder: MlsGroupBuilder,
619    reinit_info: ReInitInfo,
620    force_self_update: bool,
621}
622
623impl ReInitGroupBuilder {
624    /// Force a self-update (path) in the reinit commit. See
625    /// [`CommitBuilder::force_self_update`](crate::group::CommitBuilder::force_self_update).
626    pub fn force_self_update(mut self, force_self_update: bool) -> Self {
627        self.force_self_update = force_self_update;
628        self
629    }
630
631    /// Create the reinitialized group and a reinit commit that adds `members` to it.
632    /// The application must ensure that `members` match the members of the predecessor group,
633    /// otherwise joiners will reject the Welcome, see also [`JoinBuilder::check_members`](crate::group::mls_group::creation::JoinBuilder::check_members).
634    ///
635    /// This creates a fresh group with the ReInit proposal's group_id, ciphersuite and
636    /// group_context.extensions, adds the reinit
637    /// resumption PSK (mixing in the old group's resumption PSK secret), and commits
638    /// the additions (plus [`Self::force_self_update`]).
639    /// It returns the new (epoch-0) group and the [`CommitMessageBundle`]
640    /// carrying the first commit and `Welcome`.
641    ///
642    /// The commit is staged but **not** merged: merge it with
643    /// [`MlsGroup::merge_pending_commit`](crate::group::MlsGroup::merge_pending_commit)
644    /// only once the delivery service has confirmed it.
645    #[openmls_traits::maybe_async]
646    pub async fn build_reinit<Provider: OpenMlsProvider>(
647        self,
648        provider: &Provider,
649        signer: &impl Signer,
650        credential_with_key: CredentialWithKey,
651        members: impl IntoIterator<Item = KeyPackage>,
652    ) -> Result<(MlsGroup, CommitMessageBundle), ReInitError<Provider::StorageError>> {
653        // The group must match the proposal.
654        let ReInitInfo {
655            proposal,
656            old_group_id,
657            old_group_epoch,
658            resumption_psk_secret,
659            member_credentials: _,
660        } = self.reinit_info;
661        let group_builder = self
662            .group_builder
663            .ciphersuite(proposal.ciphersuite)
664            .with_group_id(proposal.group_id)
665            .with_group_context_extensions(proposal.extensions);
666        let mut group = group_builder
667            .build(provider, signer, credential_with_key)
668            .await?;
669
670        let mut commit_builder = group
671            .commit_builder()
672            .reinit(
673                provider.rand(),
674                old_group_id,
675                old_group_epoch,
676                resumption_psk_secret,
677            )?
678            .propose_adds(members);
679        if self.force_self_update {
680            commit_builder = commit_builder.force_self_update(true);
681        }
682        let bundle = commit_builder
683            .load_psks(provider.storage())
684            .await?
685            .build(provider.rand(), provider.crypto(), signer, |_| true)?
686            .stage_commit(provider)
687            .await?;
688
689        Ok((group, bundle))
690    }
691}
692
693/// Indicates an error occurred while creating a reinitialized group with
694/// [`ReInitGroupBuilder::build_reinit`].
695#[derive(Debug, thiserror::Error)]
696pub enum ReInitError<StorageError> {
697    /// An error occurred while creating the sub-group.
698    #[error(transparent)]
699    NewGroup(#[from] NewGroupError<StorageError>),
700    /// An error occurred while creating the reinit commit.
701    #[error(transparent)]
702    CreateCommit(#[from] CreateCommitError),
703    /// An error occurred while staging the reinit commit.
704    #[error(transparent)]
705    CommitBuilderStage(#[from] CommitBuilderStageError<StorageError>),
706}
707
708/// Create a new group with the virtual client as the creator (epoch 0, single
709/// leaf).
710///
711/// The creator's leaf is `key_package`-sourced and its key material is derived
712/// from a fresh `key_package` operation secret of the derivation epoch
713/// `epoch_id` (batch index 0). The epoch-0 `epoch_secret` is derived from the
714/// same KeyPackage seed under the created group's ciphersuite. A sibling
715/// emulator client reconstructs this exact state with
716/// [`MlsGroup::vc_join_at_creation`]: it shares the operation secret tree, so it
717/// rederives the same seed and hence the same epoch secret without any secret
718/// travelling on the wire. Because the `epoch_secret` is derived rather than run
719/// through the joiner key schedule, this path bypasses it entirely.
720///
721/// [`MlsGroup::vc_join_at_creation`]: crate::group::MlsGroup::vc_join_at_creation
722#[cfg(feature = "virtual-clients-draft")]
723#[allow(clippy::too_many_arguments)]
724#[openmls_traits::maybe_async]
725async fn build_vc_internal<Provider: OpenMlsProvider>(
726    provider: &Provider,
727    signer: &impl Signer,
728    credential_with_key: CredentialWithKey,
729    mls_group_create_config: MlsGroupCreateConfig,
730    group_id: GroupId,
731    replace_old_group: bool,
732    epoch_id: crate::components::vc_derivation_info::EpochId,
733) -> Result<MlsGroup, NewGroupError<Provider::StorageError>> {
734    use openmls_traits::storage::StorageProvider as _;
735
736    use crate::{
737        components::vc_derivation_info::{
738            load_vc_epoch_state_and_tree, DerivationInfo, DerivationInfoTbe,
739            VirtualClientOperationType, VirtualClientsError,
740        },
741        schedule::EpochSecrets,
742        treesync::TreeSync,
743    };
744
745    if !replace_old_group
746        && MlsGroup::load(provider.storage(), &group_id)
747            .await
748            .map_err(NewGroupError::StorageError)?
749            .is_some()
750    {
751        return Err(NewGroupError::GroupAlreadyExists);
752    }
753
754    let ciphersuite = mls_group_create_config.ciphersuite;
755    let (capabilities, capabilities_policy) = resolve_capabilities(
756        mls_group_create_config.capabilities.clone(),
757        mls_group_create_config.capabilities_policy,
758    );
759
760    // Validate that the creator's leaf declares `AppDataDictionary` and lists
761    // `VC_COMPONENT_ID` before allocating a generation, so a deterministic
762    // precondition failure does not burn an operation secret.
763    let resolved_dictionary = crate::components::vc_derivation_info::resolve_vc_leaf_dictionary(
764        Some(&capabilities),
765        Some(&mls_group_create_config.leaf_node_extensions),
766        None,
767    )?;
768
769    // Load the derivation epoch state and operation tree, allocate a fresh
770    // `key_package` generation (empty operation context, matching the KeyPackage
771    // batch path), and persist the advanced tree right away. A retried creation
772    // consumes a fresh generation.
773    let (state, mut operation_tree) = load_vc_epoch_state_and_tree(provider, &epoch_id).await?;
774    let (emulation_leaf_index, epoch_encryption_key, emulation_ciphersuite) = state.into_parts();
775    let (generation, operation_secret) = operation_tree.next_operation_secret(
776        provider.crypto(),
777        emulation_ciphersuite,
778        &epoch_id,
779        emulation_leaf_index,
780        VirtualClientOperationType::KeyPackage,
781        b"",
782    )?;
783    provider
784        .storage()
785        .write_vc_operation_tree(&epoch_id, &operation_tree)
786        .await
787        .map_err(NewGroupError::StorageError)?;
788
789    // The creator batch consists of this single derivation and is closed
790    // immediately: no `KeyPackageUpload` is sent and no
791    // `RetainedKeyPackageMaterial` is written, because a creator leaf has no
792    // KeyPackage / KeyPackageRef. Import the per-KeyPackage seed (index 0) under
793    // the created group's ciphersuite, then derive the creator leaf's encryption
794    // keypair and the epoch-0 secret from that seed.
795    let key_package_index = 0;
796    let key_package_seed = operation_secret.derive_key_package_seed_secret(
797        provider.crypto(),
798        ciphersuite,
799        key_package_index,
800    )?;
801    let leaf_encryption_keypair = key_package_seed
802        .derive_encryption_key_secret(provider.crypto(), ciphersuite)?
803        .generate_encryption_key_pair(provider.crypto(), ciphersuite)?;
804    let epoch_secret =
805        key_package_seed.derive_group_creation_secret(provider.crypto(), ciphersuite)?;
806
807    // Wrap the derivation info under the per-epoch AEAD key, bound to the leaf
808    // via its serialized encryption key.
809    let leaf_encryption_key = leaf_encryption_keypair
810        .public_key()
811        .tls_serialize_detached()
812        .map_err(VirtualClientsError::from)?;
813    let tbe = DerivationInfoTbe::KeyPackage {
814        leaf_index: emulation_leaf_index,
815        generation,
816        key_package_index,
817    };
818    let derivation_info = DerivationInfo::encrypt(
819        provider.crypto(),
820        emulation_ciphersuite,
821        &epoch_encryption_key,
822        epoch_id.clone(),
823        &leaf_encryption_key,
824        &tbe,
825    )?;
826    let derivation_info_bytes = derivation_info
827        .tls_serialize_detached()
828        .map_err(VirtualClientsError::from)?;
829    let leaf_extensions = crate::components::vc_derivation_info::merge_vc_derivation_info(
830        Some(&mls_group_create_config.leaf_node_extensions),
831        resolved_dictionary,
832        derivation_info_bytes,
833    )?;
834
835    // Build the single-leaf tree with the derived key_package-sourced leaf.
836    let (treesync, leaf_keypair) = TreeSync::new_vc(
837        provider,
838        signer,
839        ciphersuite,
840        credential_with_key,
841        *mls_group_create_config.lifetime(),
842        capabilities,
843        leaf_extensions,
844        leaf_encryption_keypair,
845        LeafNodeConstraints::from_group_context_extensions(
846            &mls_group_create_config.group_context_extensions,
847        ),
848        capabilities_policy,
849    )?;
850    let group_context = GroupContext::create_initial_group_context(
851        ciphersuite,
852        group_id.clone(),
853        treesync.tree_hash().to_vec(),
854        mls_group_create_config.group_context_extensions.clone(),
855    );
856    let serialized_group_context = group_context
857        .tls_serialize_detached()
858        .map_err(LibraryError::missing_bound_check)?;
859
860    // Derive epoch-0 secrets from the epoch secret derived above.
861    let epoch_secrets =
862        EpochSecrets::from_epoch_secret(provider.crypto(), ciphersuite, epoch_secret)
863            .map_err(LibraryError::unexpected_crypto_error)?;
864    let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
865        serialized_group_context,
866        TreeSize::new(1),
867        LeafNodeIndex::new(0),
868    );
869    let initial_confirmation_tag = message_secrets
870        .confirmation_key()
871        .tag(provider.crypto(), ciphersuite, &[])
872        .map_err(LibraryError::unexpected_crypto_error)?;
873    let message_secrets_store = MessageSecretsStore::new_with_secret(
874        mls_group_create_config
875            .join_config
876            .past_epoch_deletion_policy(),
877        message_secrets,
878    );
879    let public_group = PublicGroup::new(
880        provider.crypto(),
881        treesync,
882        group_context,
883        initial_confirmation_tag,
884    )?;
885
886    let mut resumption_psk_store = ResumptionPskStore::new(32);
887    let resumption_psk = group_epoch_secrets.resumption_psk();
888    resumption_psk_store.add(public_group.group_context().epoch(), resumption_psk.clone());
889
890    let mls_group = MlsGroup {
891        mls_group_config: mls_group_create_config.join_config.clone(),
892        own_leaf_nodes: vec![],
893        aad: vec![],
894        safe_aad: crate::framing::SafeAad::empty(),
895        group_state: MlsGroupState::Operational,
896        public_group,
897        group_epoch_secrets,
898        own_leaf_index: LeafNodeIndex::new(0),
899        message_secrets_store,
900        resumption_psk_store,
901        // Reconstructed VC groups do not populate the application export tree,
902        // matching the other VC group-entry paths.
903        application_export_tree: None,
904        // A group a virtual client creates is not itself an emulation group.
905        emulation_group: false,
906    };
907
908    // Bind epoch 0 of the new group to the derivation epoch so later VC
909    // operations in this group resolve the right derivation epoch state.
910    // Written before the group itself, so an error between the writes cannot
911    // leave a loadable group without a binding (a bound group is required for
912    // the reuse-guard MUST).
913    let max_entries = mls_group.message_secrets_store.max_epochs.saturating_add(1);
914    crate::components::vc_derivation_info::write_vc_emulation_binding_with_pruning(
915        provider.storage(),
916        &group_id,
917        mls_group.epoch(),
918        epoch_id,
919        max_entries,
920    )
921    .await
922    .map_err(NewGroupError::StorageError)?;
923
924    mls_group
925        .store(provider.storage())
926        .await
927        .map_err(NewGroupError::StorageError)?;
928    mls_group
929        .store_epoch_keypairs(provider.storage(), &[leaf_keypair])
930        .await
931        .map_err(NewGroupError::StorageError)?;
932
933    Ok(mls_group)
934}