openmls 0.9.0-rc.1

A Rust implementation of the Messaging Layer Security (MLS) protocol, as defined in RFC 9420.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use openmls_traits::{crypto::OpenMlsCrypto, types::Ciphersuite};
use thiserror::Error;
use tls_codec::Serialize as _;

#[cfg(doc)]
use super::CommitMessageBundle;

use crate::{
    binary_tree::LeafNodeIndex,
    credentials::CredentialWithKey,
    error::LibraryError,
    framing::{ContentType, DecryptedMessage, PublicMessageIn, Sender},
    group::{
        commit_builder::{CommitBuilder, ExternalCommitInfo, Initial},
        past_secrets::MessageSecretsStore,
        public_group::errors::CreationFromExternalError,
        ExternalCommitBuilderFinalizeError, LeafNodeLifetimePolicy, MlsGroup, MlsGroupJoinConfig,
        MlsGroupState, PendingCommitState, ProposalStore, PublicGroup, QueuedProposal,
        ValidationError, PURE_PLAINTEXT_WIRE_FORMAT_POLICY,
    },
    messages::{
        group_info::VerifiableGroupInfo,
        proposals::{
            ExternalInitProposal, PreSharedKeyProposal, Proposal, ProposalOrRefType, ProposalType,
            RemoveProposal,
        },
    },
    schedule::{psk::store::ResumptionPskStore, EpochSecrets, InitSecret},
    storage::OpenMlsProvider,
    treesync::{LeafNodeParameters, RatchetTreeIn},
    versions::ProtocolVersion,
};

/// Error type for the [`ExternalCommitBuilder`].
#[derive(Debug, Error)]
pub enum ExternalCommitBuilderError<StorageError> {
    /// See [`LibraryError`] for more details.
    #[error(transparent)]
    LibraryError(#[from] LibraryError),
    /// No ratchet tree available to build initial tree.
    #[error("No ratchet tree available to build initial tree.")]
    MissingRatchetTree,
    /// No external_pub extension available to join group by external commit.
    #[error("No external_pub extension available to join group by external commit.")]
    MissingExternalPub,
    /// We don't support the ciphersuite of the group we are trying to join.
    #[error("Ciphersuite {0:?} of the group we are trying to join is not supported by the crypto provider.")]
    UnsupportedCiphersuite(Ciphersuite),
    /// This error indicates the public tree is invalid. See
    /// [`CreationFromExternalError`] for more details.
    #[error(transparent)]
    PublicGroupError(#[from] CreationFromExternalError<StorageError>),
    /// An error occurred when writing group to storage
    #[error("An error occurred when writing group to storage.")]
    StorageError(StorageError),
    /// Error validating proposals.
    #[error("Error validating proposals: {0}")]
    InvalidProposal(#[from] ValidationError),
}

/// This is the builder for external commits. It allows you to build an external
/// commit that can be used to join a group externally. Parameters such as
/// optional SelfRemove proposals from other members, the ratchet tree, and the
/// group join configuration can be set in the first builder stage.
///
/// The second stage of this builder is a [`CommitBuilder`] that can be used to
/// add one or more [`PreSharedKeyProposal`]s to the external commit and specify
/// [`LeafNodeParameters`].
#[derive(Default)]
pub struct ExternalCommitBuilder {
    proposals: Vec<PublicMessageIn>,
    ratchet_tree: Option<RatchetTreeIn>,
    config: MlsGroupJoinConfig,
    validate_lifetimes: LeafNodeLifetimePolicy,
    aad: Vec<u8>,
}

impl MlsGroup {
    /// Creates a new [`ExternalCommitBuilder`] to build an external commit.
    pub fn external_commit_builder() -> ExternalCommitBuilder {
        ExternalCommitBuilder::new()
    }
}

impl ExternalCommitBuilder {
    /// Creates a new [`ExternalCommitBuilder`] with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds SelfRemove proposals to the external commit. Other proposals or
    /// other types of messages are ignored.
    pub fn with_proposals(mut self, proposals: Vec<PublicMessageIn>) -> Self {
        self.proposals = proposals;
        self
    }

    /// Specifies the ratchet tree to use for the external commit. This is only
    /// used if the ratchet tree is not provided in the [`VerifiableGroupInfo`]
    /// extensions. A ratchet tree must be provided, either in the
    /// [`VerifiableGroupInfo`] extensions or via this method.
    pub fn with_ratchet_tree(mut self, ratchet_tree: RatchetTreeIn) -> Self {
        self.ratchet_tree = Some(ratchet_tree);
        self
    }

    /// Specifies the configuration to use for the group built as part of the
    /// external commit. Note that the external commit will always be a
    /// `PublicMessage` regardless of the wire format policy set in the group
    /// config.
    pub fn with_config(mut self, config: MlsGroupJoinConfig) -> Self {
        self.config = config;
        self
    }

    /// Specifies additional authenticated data (AAD) to be included in the
    /// external commit.
    pub fn with_aad(mut self, aad: Vec<u8>) -> Self {
        self.aad = aad;
        self
    }

    /// Skip the validation of lifetimes in leaf nodes in the ratchet tree.
    /// Note that only the leaf nodes are checked that were never updated.
    ///
    /// By default they are validated.
    pub fn skip_lifetime_validation(mut self) -> Self {
        self.validate_lifetimes = LeafNodeLifetimePolicy::Skip;
        self
    }

    /// Build the [`MlsGroup`] from the provided [`VerifiableGroupInfo`] and
    /// [`CredentialWithKey`].
    ///
    /// Returns a [`CommitBuilder`] that can be used to further configure the
    /// external commit.
    pub fn build_group<Provider: OpenMlsProvider>(
        self,
        provider: &Provider,
        verifiable_group_info: VerifiableGroupInfo,
        credential_with_key: CredentialWithKey,
    ) -> Result<
        CommitBuilder<'_, Initial, MlsGroup>,
        ExternalCommitBuilderError<Provider::StorageError>,
    > {
        let ExternalCommitBuilder {
            proposals,
            ratchet_tree,
            mut config,
            aad,
            validate_lifetimes,
        } = self;

        let group_ciphersuite = verifiable_group_info.ciphersuite();
        provider
            .crypto()
            .supports(group_ciphersuite)
            .map_err(|_| ExternalCommitBuilderError::UnsupportedCiphersuite(group_ciphersuite))?;

        // Build the ratchet tree

        // Set nodes either from the extension or from the `ratchet_tree`.
        let ratchet_tree = match verifiable_group_info.extensions().ratchet_tree() {
            Some(extension) => extension.ratchet_tree().clone(),
            None => match ratchet_tree {
                Some(ratchet_tree) => ratchet_tree,
                None => return Err(ExternalCommitBuilderError::MissingRatchetTree),
            },
        };

        let (public_group, group_info) = PublicGroup::from_ratchet_tree(
            provider.crypto(),
            ratchet_tree,
            verifiable_group_info,
            ProposalStore::new(),
            validate_lifetimes,
        )?;
        let group_context = public_group.group_context();

        // Obtain external_pub from GroupInfo extensions.
        let external_pub = group_info
            .extensions()
            .external_pub()
            .ok_or(ExternalCommitBuilderError::MissingExternalPub)?
            .external_pub();

        let (init_secret, kem_output) = InitSecret::from_group_context(
            provider.crypto(),
            group_context,
            external_pub.as_slice(),
        )
        .map_err(|_| {
            ExternalCommitBuilderError::UnsupportedCiphersuite(group_context.ciphersuite())
        })?;

        // The `EpochSecrets` we create here are essentially zero, with the
        // exception of the `InitSecret`, which is all we need here for the
        // external commit.
        let ciphersuite = group_context.ciphersuite();
        let epoch_secrets =
            EpochSecrets::with_init_secret(provider.crypto(), ciphersuite, init_secret)
                .map_err(LibraryError::unexpected_crypto_error)?;
        let (group_epoch_secrets, message_secrets) = epoch_secrets.split_secrets(
            group_context
                .tls_serialize_detached()
                .map_err(LibraryError::missing_bound_check)?,
            public_group.tree_size(),
            // We use a fake own index of 0 here, as we're not going to use the
            // tree for encryption until after the first commit. This issue is
            // tracked in #767.
            LeafNodeIndex::new(0u32),
        );
        let message_secrets_store = MessageSecretsStore::new_with_secret(
            config.past_epoch_deletion_policy(),
            message_secrets,
        );

        let external_init_proposal =
            Proposal::external_init(ExternalInitProposal::from(kem_output));

        // Authenticate the proposals as best as we can
        let serialized_context = group_context
            .tls_serialize_detached()
            .map_err(LibraryError::missing_bound_check)?;
        let mut queued_proposals = Vec::new();
        for message in proposals {
            if message.content_type() != ContentType::Proposal {
                continue; // We only want proposals.
            }
            let decrypted_message = DecryptedMessage::from_inbound_public_message(
                message,
                None,
                serialized_context.clone(),
                provider.crypto(),
                ciphersuite,
            )?;
            let unverified_message = public_group.parse_message(decrypted_message, None)?;
            let verified = unverified_message.verify(
                ciphersuite,
                provider.crypto(),
                ProtocolVersion::default(),
            )?;
            let queued_proposal = QueuedProposal::from_authenticated_content(
                ciphersuite,
                provider.crypto(),
                verified.content,
                ProposalOrRefType::Reference,
            )?;
            // We ignore any proposal that is not a SelfRemove.
            if queued_proposal.proposal().is_type(ProposalType::SelfRemove) {
                queued_proposals.push(queued_proposal);
            }
        }

        let inline_proposals = [external_init_proposal].into_iter();

        // If there is a group member in the group with the same identity as us,
        // commit a remove proposal.
        let our_signature_key = credential_with_key.signature_key.as_slice();
        let remove_proposal = public_group.members().find_map(|member| {
            (member.signature_key == our_signature_key).then_some(Proposal::remove(
                RemoveProposal {
                    removed: member.index,
                },
            ))
        });

        let inline_proposals = inline_proposals
            .chain(remove_proposal)
            .map(|p| {
                QueuedProposal::from_proposal_and_sender(
                    ciphersuite,
                    provider.crypto(),
                    p,
                    &Sender::NewMemberCommit,
                )
            })
            .collect::<Result<Vec<_>, _>>()?;

        queued_proposals.extend(inline_proposals);

        let own_leaf_index = public_group.leftmost_free_index(queued_proposals.iter())?;

        let original_wire_format_policy = config.wire_format_policy;

        // We set this to PURE_PLAINTEXT_WIRE_FORMAT_POLICY so that the
        // external commit can be sent as a PublicMessageIn. The wire format
        // policy will be set to the original wire format policy after the
        // external commit has been sent.
        config.wire_format_policy = PURE_PLAINTEXT_WIRE_FORMAT_POLICY;

        let mut mls_group = MlsGroup {
            mls_group_config: config,
            own_leaf_nodes: vec![],
            aad: vec![],
            #[cfg(feature = "extensions-draft")]
            safe_aad: crate::framing::SafeAad::empty(),
            group_state: MlsGroupState::Operational,
            public_group,
            group_epoch_secrets,
            own_leaf_index,
            message_secrets_store,
            resumption_psk_store: ResumptionPskStore::new(32),
            // This is set to `None` for now. It will be set once the external
            // commit is merged.
            #[cfg(feature = "extensions-draft")]
            application_export_tree: None,
        };

        // Add all proposals to the proposal store.
        let proposal_store = mls_group.proposal_store_mut();
        for queued_proposal in queued_proposals {
            proposal_store.add(queued_proposal);
        }

        let mut commit_builder = CommitBuilder::<'_, Initial, MlsGroup>::new(mls_group);

        commit_builder.stage.force_self_update = true;
        commit_builder.stage.external_commit_info = Some(ExternalCommitInfo {
            wire_format_policy: original_wire_format_policy,
            credential: credential_with_key.clone(),
            aad,
        });
        let leaf_node_parameters = LeafNodeParameters::builder()
            .with_credential_with_key(credential_with_key)
            .build();
        commit_builder.stage.leaf_node_parameters = leaf_node_parameters;

        Ok(commit_builder)
    }
}

// Impls that only apply to external commits.
impl<'a> CommitBuilder<'a, Initial, MlsGroup> {
    /// Adds a [`PreSharedKeyProposal`] to the proposals to be committed.
    pub fn add_psk_proposal(mut self, proposal: PreSharedKeyProposal) -> Self {
        self.stage.own_proposals.push(Proposal::psk(proposal));
        self
    }

    /// Adds the [`PreSharedKeyProposal`] in the iterator to the proposals to be
    /// committed.
    pub fn add_psk_proposals(
        mut self,
        proposals: impl IntoIterator<Item = PreSharedKeyProposal>,
    ) -> Self {
        self.stage
            .own_proposals
            .extend(proposals.into_iter().map(Proposal::psk));
        self
    }

    /// Adds an AppDataUpdateProposal.
    #[cfg(feature = "extensions-draft")]
    pub fn add_app_data_update_proposal(
        mut self,
        proposal: crate::messages::proposals::AppDataUpdateProposal,
    ) -> Self {
        self.stage
            .own_proposals
            .push(Proposal::AppDataUpdate(Box::new(proposal)));
        self
    }
}

// Impls that apply only to external commits.
impl CommitBuilder<'_, super::Complete, MlsGroup> {
    /// Finalizes and returns the [`MlsGroup`], as well as the
    /// [`CommitMessageBundle`].
    ///
    /// In contrast to the deprecated [`MlsGroup::join_by_external_commit`]
    /// there is no need to merge the pending commit.
    pub fn finalize<Provider: OpenMlsProvider>(
        self,
        provider: &Provider,
    ) -> Result<
        (MlsGroup, super::CommitMessageBundle),
        ExternalCommitBuilderFinalizeError<Provider::StorageError>,
    > {
        let Self {
            mut group,
            stage:
                super::Complete {
                    result: create_commit_result,
                    original_wire_format_policy,
                },
            ..
        } = self;

        // Convert AuthenticatedContent messages to MLSMessage. An external
        // commit is always framed as a PublicMessage, so it carries no
        // handshake confirmation data.
        let mls_message = group
            .content_to_mls_message(create_commit_result.commit, provider)?
            .message;

        group.reset_aad();

        // Restore the original wire format policy.
        if let Some(wire_format_policy) = original_wire_format_policy {
            group.mls_group_config.wire_format_policy = wire_format_policy;
        }

        // Store the group in storage.
        group
            .store(provider.storage())
            .map_err(ExternalCommitBuilderFinalizeError::StorageError)?;

        // Set the current group state to [`MlsGroupState::PendingCommit`],
        // storing the current [`StagedCommit`] from the commit results
        group.group_state = MlsGroupState::PendingCommit(Box::new(PendingCommitState::Member(
            create_commit_result.staged_commit,
        )));

        group.merge_pending_commit(provider)?;

        let bundle = super::CommitMessageBundle {
            version: group.version(),
            commit: mls_message,
            welcome: create_commit_result.welcome_option,
            group_info: create_commit_result.group_info,
            #[cfg(feature = "virtual-clients-draft")]
            confirmation: None,
        };

        Ok((group, bundle))
    }
}