openmls/group/mls_group/
builder.rs

1use openmls_traits::{signatures::Signer, types::Ciphersuite};
2use tls_codec::Serialize;
3
4use crate::{
5    binary_tree::array_representation::TreeSize,
6    credentials::CredentialWithKey,
7    error::LibraryError,
8    extensions::{errors::InvalidExtensionError, Extensions},
9    group::{
10        public_group::errors::PublicGroupBuildError, GroupId, MlsGroupCreateConfig,
11        MlsGroupCreateConfigBuilder, NewGroupError, PublicGroup, WireFormatPolicy,
12    },
13    key_packages::Lifetime,
14    prelude::LeafNodeIndex,
15    schedule::{
16        psk::{load_psks, store::ResumptionPskStore, PskSecret},
17        InitSecret, JoinerSecret, KeySchedule, PreSharedKeyId,
18    },
19    storage::OpenMlsProvider,
20    tree::sender_ratchet::SenderRatchetConfiguration,
21    treesync::{errors::LeafNodeValidationError, node::leaf_node::Capabilities},
22};
23
24use super::{past_secrets::MessageSecretsStore, MlsGroup, MlsGroupState};
25
26/// Builder struct for an [`MlsGroup`].
27#[derive(Default, Debug)]
28pub struct MlsGroupBuilder {
29    group_id: Option<GroupId>,
30    mls_group_create_config_builder: MlsGroupCreateConfigBuilder,
31    psk_ids: Vec<PreSharedKeyId>,
32}
33
34impl MlsGroupBuilder {
35    pub(super) fn new() -> Self {
36        Self::default()
37    }
38
39    /// Sets the group ID of the [`MlsGroup`].
40    pub fn with_group_id(mut self, group_id: GroupId) -> Self {
41        self.group_id = Some(group_id);
42        self
43    }
44
45    /// Build a new group as configured by this builder.
46    pub fn build<Provider: OpenMlsProvider>(
47        self,
48        provider: &Provider,
49        signer: &impl Signer,
50        credential_with_key: CredentialWithKey,
51    ) -> Result<MlsGroup, NewGroupError<Provider::StorageError>> {
52        self.build_internal(provider, signer, credential_with_key, None)
53    }
54
55    /// Build a new group with the given group ID.
56    ///
57    /// If an [`MlsGroupCreateConfig`] is provided, it will be used to configure the
58    /// group. Otherwise, the internal builder is used to build one with the
59    /// parameters set on this builder.
60    pub(super) fn build_internal<Provider: OpenMlsProvider>(
61        self,
62        provider: &Provider,
63        signer: &impl Signer,
64        credential_with_key: CredentialWithKey,
65        mls_group_create_config_option: Option<MlsGroupCreateConfig>,
66    ) -> Result<MlsGroup, NewGroupError<Provider::StorageError>> {
67        let mls_group_create_config = mls_group_create_config_option
68            .unwrap_or_else(|| self.mls_group_create_config_builder.build());
69        let group_id = self
70            .group_id
71            .unwrap_or_else(|| GroupId::random(provider.rand()));
72        let ciphersuite = mls_group_create_config.ciphersuite;
73
74        let (public_group_builder, commit_secret, leaf_keypair) =
75            PublicGroup::builder(group_id, ciphersuite, credential_with_key)
76                .with_group_context_extensions(
77                    mls_group_create_config.group_context_extensions.clone(),
78                )?
79                .with_leaf_node_extensions(mls_group_create_config.leaf_node_extensions.clone())?
80                .with_lifetime(*mls_group_create_config.lifetime())
81                .with_capabilities(mls_group_create_config.capabilities.clone())
82                .get_secrets(provider, signer)
83                .map_err(|e| match e {
84                    PublicGroupBuildError::LibraryError(e) => NewGroupError::LibraryError(e),
85                    PublicGroupBuildError::InvalidExtensions(e) => e.into(),
86                })?;
87
88        let serialized_group_context = public_group_builder
89            .group_context()
90            .tls_serialize_detached()
91            .map_err(LibraryError::missing_bound_check)?;
92
93        // Derive an initial joiner secret based on the commit secret.
94        // Derive an epoch secret from the joiner secret.
95        // We use a random `InitSecret` for initialization.
96        let joiner_secret = JoinerSecret::new(
97            provider.crypto(),
98            ciphersuite,
99            commit_secret,
100            &InitSecret::random(ciphersuite, provider.rand())
101                .map_err(LibraryError::unexpected_crypto_error)?,
102            &serialized_group_context,
103        )
104        .map_err(LibraryError::unexpected_crypto_error)?;
105
106        // TODO(#1357)
107        let mut resumption_psk_store = ResumptionPskStore::new(32);
108
109        // Prepare the PskSecret
110        let psk_secret = load_psks(provider.storage(), &resumption_psk_store, &self.psk_ids)
111            .and_then(|psks| PskSecret::new(provider.crypto(), ciphersuite, psks))
112            .map_err(|e| {
113                log::debug!("Unexpected PSK error: {e:?}");
114                LibraryError::custom("Unexpected PSK error")
115            })?;
116
117        let mut key_schedule =
118            KeySchedule::init(ciphersuite, provider.crypto(), &joiner_secret, psk_secret)?;
119        key_schedule
120            .add_context(provider.crypto(), &serialized_group_context)
121            .map_err(|_| LibraryError::custom("Using the key schedule in the wrong state"))?;
122
123        let epoch_secrets = key_schedule
124            .epoch_secrets(provider.crypto(), ciphersuite)
125            .map_err(|_| LibraryError::custom("Using the key schedule in the wrong state"))?;
126
127        let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
128            serialized_group_context,
129            TreeSize::new(1),
130            LeafNodeIndex::new(0u32),
131        );
132
133        let initial_confirmation_tag = message_secrets
134            .confirmation_key()
135            .tag(provider.crypto(), ciphersuite, &[])
136            .map_err(LibraryError::unexpected_crypto_error)?;
137
138        let message_secrets_store = MessageSecretsStore::new_with_secret(
139            mls_group_create_config.max_past_epochs(),
140            message_secrets,
141        );
142
143        let public_group = public_group_builder
144            .with_confirmation_tag(initial_confirmation_tag)
145            .build(provider.crypto())?;
146
147        // We already add a resumption PSK for epoch 0 to make things more unified.
148        let resumption_psk = group_epoch_secrets.resumption_psk();
149        resumption_psk_store.add(public_group.group_context().epoch(), resumption_psk.clone());
150
151        let mls_group = MlsGroup {
152            mls_group_config: mls_group_create_config.join_config.clone(),
153            own_leaf_nodes: vec![],
154            aad: vec![],
155            group_state: MlsGroupState::Operational,
156            public_group,
157            group_epoch_secrets,
158            own_leaf_index: LeafNodeIndex::new(0),
159            message_secrets_store,
160            resumption_psk_store,
161        };
162
163        mls_group
164            .store(provider.storage())
165            .map_err(NewGroupError::StorageError)?;
166        mls_group
167            .store_epoch_keypairs(provider.storage(), &[leaf_keypair])
168            .map_err(NewGroupError::StorageError)?;
169
170        Ok(mls_group)
171    }
172
173    // MlsGroupCreateConfigBuilder options
174
175    /// Sets the `wire_format` property of the MlsGroup.
176    pub fn with_wire_format_policy(mut self, wire_format_policy: WireFormatPolicy) -> Self {
177        self.mls_group_create_config_builder = self
178            .mls_group_create_config_builder
179            .wire_format_policy(wire_format_policy);
180        self
181    }
182
183    /// Sets the `padding_size` property of the MlsGroup.
184    pub fn padding_size(mut self, padding_size: usize) -> Self {
185        self.mls_group_create_config_builder = self
186            .mls_group_create_config_builder
187            .padding_size(padding_size);
188        self
189    }
190
191    /// Sets the `max_past_epochs` property of the MlsGroup.
192    /// This allows application messages from previous epochs to be decrypted.
193    ///
194    /// **WARNING**
195    ///
196    /// This feature enables the storage of message secrets from past epochs.
197    /// It is a trade-off between functionality and forward secrecy and should only be enabled
198    /// if the Delivery Service cannot guarantee that application messages will be sent in
199    /// the same epoch in which they were generated. The number for `max_epochs` should be
200    /// as low as possible.
201    pub fn max_past_epochs(mut self, max_past_epochs: usize) -> Self {
202        self.mls_group_create_config_builder = self
203            .mls_group_create_config_builder
204            .max_past_epochs(max_past_epochs);
205        self
206    }
207
208    /// Sets the `number_of_resumption_psks` property of the MlsGroup.
209    pub fn number_of_resumption_psks(mut self, number_of_resumption_psks: usize) -> Self {
210        self.mls_group_create_config_builder = self
211            .mls_group_create_config_builder
212            .number_of_resumption_psks(number_of_resumption_psks);
213        self
214    }
215
216    /// Sets the `use_ratchet_tree_extension` property of the MlsGroup.
217    pub fn use_ratchet_tree_extension(mut self, use_ratchet_tree_extension: bool) -> Self {
218        self.mls_group_create_config_builder = self
219            .mls_group_create_config_builder
220            .use_ratchet_tree_extension(use_ratchet_tree_extension);
221        self
222    }
223
224    /// Sets the `sender_ratchet_configuration` property of the MlsGroup.
225    /// See [`SenderRatchetConfiguration`] for more information.
226    pub fn sender_ratchet_configuration(
227        mut self,
228        sender_ratchet_configuration: SenderRatchetConfiguration,
229    ) -> Self {
230        self.mls_group_create_config_builder = self
231            .mls_group_create_config_builder
232            .sender_ratchet_configuration(sender_ratchet_configuration);
233        self
234    }
235
236    /// Sets the `lifetime` of the group creator's leaf.
237    pub fn lifetime(mut self, lifetime: Lifetime) -> Self {
238        self.mls_group_create_config_builder =
239            self.mls_group_create_config_builder.lifetime(lifetime);
240        self
241    }
242
243    /// Sets the `ciphersuite` of the MlsGroup.
244    pub fn ciphersuite(mut self, ciphersuite: Ciphersuite) -> Self {
245        self.mls_group_create_config_builder = self
246            .mls_group_create_config_builder
247            .ciphersuite(ciphersuite);
248        self
249    }
250
251    /// Sets the initial group context extensions
252    pub fn with_group_context_extensions(
253        mut self,
254        extensions: Extensions,
255    ) -> Result<Self, InvalidExtensionError> {
256        self.mls_group_create_config_builder = self
257            .mls_group_create_config_builder
258            .with_group_context_extensions(extensions)?;
259        Ok(self)
260    }
261
262    /// Sets the initial leaf node extensions
263    pub fn with_leaf_node_extensions(
264        mut self,
265        extensions: Extensions,
266    ) -> Result<Self, LeafNodeValidationError> {
267        self.mls_group_create_config_builder = self
268            .mls_group_create_config_builder
269            .with_leaf_node_extensions(extensions)?;
270        Ok(self)
271    }
272
273    /// Sets the group creator's [`Capabilities`]
274    pub fn with_capabilities(mut self, capabilities: Capabilities) -> Self {
275        self.mls_group_create_config_builder = self
276            .mls_group_create_config_builder
277            .capabilities(capabilities);
278        self
279    }
280}