Skip to main content

openmls/group/public_group/
mod.rs

1//! # Public Groups
2//!
3//! There are a few use-cases that require the tracking of an MLS group based on
4//! [`PublicMessage`]s, e.g. for group membership tracking by a delivery
5//! service.
6//!
7//! This module and its submodules contain the [`PublicGroup`] struct, as well
8//! as associated helper structs the goal of which is to enable this
9//! functionality.
10//!
11//! To avoid duplication of code and functionality, [`MlsGroup`] internally
12//! relies on a [`PublicGroup`] as well.
13
14use std::collections::HashSet;
15
16use openmls_traits::{crypto::OpenMlsCrypto, types::Ciphersuite};
17use serde::{Deserialize, Serialize};
18
19use self::{
20    diff::{PublicGroupDiff, StagedPublicGroupDiff},
21    errors::CreationFromExternalError,
22};
23use super::{
24    proposal_store::{ProposalStore, QueuedProposal},
25    GroupContext, GroupId, Member, StagedCommit,
26};
27#[cfg(test)]
28use crate::treesync::{node::parent_node::PlainUpdatePathNode, treekem::UpdatePathNode};
29use crate::{
30    binary_tree::{
31        array_representation::{direct_path, TreeSize},
32        LeafNodeIndex,
33    },
34    ciphersuite::{hash_ref::ProposalRef, signable::Verifiable},
35    error::LibraryError,
36    extensions::RequiredCapabilitiesExtension,
37    framing::{InterimTranscriptHashInput, Sender},
38    group::mls_group::creation::LeafNodeLifetimePolicy,
39    messages::{
40        group_info::{GroupInfo, VerifiableGroupInfo},
41        proposals::Proposal,
42        ConfirmationTag, PathSecret,
43    },
44    schedule::CommitSecret,
45    storage::PublicStorageProvider,
46    treesync::{
47        errors::{DerivePathError, TreeSyncFromNodesError},
48        node::{
49            encryption_keys::{EncryptionKey, EncryptionKeyPair},
50            leaf_node::LeafNode,
51        },
52        RatchetTree, RatchetTreeIn, TreeSync,
53    },
54    versions::ProtocolVersion,
55};
56#[cfg(doc)]
57use crate::{framing::PublicMessage, group::MlsGroup};
58
59pub(crate) mod builder;
60pub(crate) mod diff;
61pub mod errors;
62pub mod process;
63pub(crate) mod staged_commit;
64#[cfg(test)]
65mod tests;
66mod validation;
67
68/// This struct holds all public values of an MLS group.
69#[derive(Debug)]
70#[cfg_attr(any(test, feature = "test-utils"), derive(PartialEq, Clone))]
71pub struct PublicGroup {
72    treesync: TreeSync,
73    proposal_store: ProposalStore,
74    group_context: GroupContext,
75    interim_transcript_hash: Vec<u8>,
76    // Most recent confirmation tag. Kept here for verification purposes.
77    confirmation_tag: ConfirmationTag,
78}
79
80/// This is a wrapper type, because we can't implement the storage traits on `Vec<u8>`.
81#[derive(Debug, Serialize, Deserialize)]
82pub struct InterimTranscriptHash(pub Vec<u8>);
83
84impl PublicGroup {
85    /// Create a new PublicGroup from a [`TreeSync`] instance and a
86    /// [`GroupInfo`].
87    pub(crate) fn new(
88        crypto: &impl OpenMlsCrypto,
89        treesync: TreeSync,
90        group_context: GroupContext,
91        initial_confirmation_tag: ConfirmationTag,
92    ) -> Result<Self, LibraryError> {
93        let interim_transcript_hash = {
94            let input = InterimTranscriptHashInput::from(&initial_confirmation_tag);
95
96            input.calculate_interim_transcript_hash(
97                crypto,
98                group_context.ciphersuite(),
99                group_context.confirmed_transcript_hash(),
100            )?
101        };
102
103        Ok(PublicGroup {
104            treesync,
105            proposal_store: ProposalStore::new(),
106            group_context,
107            interim_transcript_hash,
108            confirmation_tag: initial_confirmation_tag,
109        })
110    }
111
112    /// Create a [`PublicGroup`] instance to start tracking an existing MLS group.
113    ///
114    /// This function performs basic validation checks and returns an error if
115    /// one of the checks fails. See [`CreationFromExternalError`] for more
116    /// details.
117    pub fn from_external<StorageProvider, StorageError>(
118        crypto: &impl OpenMlsCrypto,
119        storage: &StorageProvider,
120        ratchet_tree: RatchetTreeIn,
121        verifiable_group_info: VerifiableGroupInfo,
122        proposal_store: ProposalStore,
123    ) -> Result<(Self, GroupInfo), CreationFromExternalError<StorageError>>
124    where
125        StorageProvider: PublicStorageProvider<Error = StorageError>,
126    {
127        let (public_group, group_info) = PublicGroup::from_ratchet_tree(
128            crypto,
129            ratchet_tree,
130            verifiable_group_info,
131            proposal_store,
132            LeafNodeLifetimePolicy::Verify,
133        )?;
134
135        public_group
136            .store(storage)
137            .map_err(CreationFromExternalError::WriteToStorageError)?;
138
139        Ok((public_group, group_info))
140    }
141
142    pub(crate) fn from_ratchet_tree<StorageError>(
143        crypto: &impl OpenMlsCrypto,
144        ratchet_tree: RatchetTreeIn,
145        verifiable_group_info: VerifiableGroupInfo,
146        proposal_store: ProposalStore,
147        validate_lifetimes: LeafNodeLifetimePolicy,
148    ) -> Result<(Self, GroupInfo), CreationFromExternalError<StorageError>> {
149        let ciphersuite = verifiable_group_info.ciphersuite();
150        crypto
151            .supports(ciphersuite)
152            .map_err(|_| CreationFromExternalError::UnsupportedCiphersuite(ciphersuite))?;
153
154        let group_id = verifiable_group_info.group_id();
155        let ratchet_tree = ratchet_tree
156            .into_verified(ciphersuite, crypto, group_id)
157            .map_err(|e| {
158                CreationFromExternalError::TreeSyncError(TreeSyncFromNodesError::RatchetTreeError(
159                    e,
160                ))
161            })?;
162
163        // Create a RatchetTree from the given nodes. We have to do this before
164        // verifying the group info, since we need to find the Credential to verify the
165        // signature against.
166        let treesync = TreeSync::from_ratchet_tree(crypto, ciphersuite, ratchet_tree)?;
167
168        let mut encryption_keys = HashSet::new();
169        let mut signature_keys = HashSet::new();
170
171        // Perform basic checks that the leaf nodes in the ratchet tree are valid
172        // These checks only do those that don't need group context. We do the full
173        // checks later, but do these here to fail early in case of funny business
174        // https://validation.openmls.tech/#valn1407
175        treesync.full_leaves().try_for_each(|(_, leaf_node)| {
176            leaf_node.validate_locally()?;
177
178            // Check that no two nodes share a signature key.
179            // https://validation.openmls.tech/#valn0111
180            if !signature_keys.insert(leaf_node.signature_key()) {
181                return Err(CreationFromExternalError::DuplicateSignatureKey);
182            }
183
184            // Check that no two nodes share an encryption key.
185            // https://validation.openmls.tech/#valn0112
186            if !encryption_keys.insert(leaf_node.encryption_key()) {
187                return Err(CreationFromExternalError::DuplicateEncryptionKey);
188            }
189
190            Ok(())
191        })?;
192
193        // For each non-empty parent node and each entry in the node's unmerged_leaves field:
194        treesync
195            .full_parents()
196            .try_for_each(|(parent_index, parent_node)| {
197                // Check that no two nodes share an encryption key.
198                // This is a bit stronger than what the spec requires: It requires that the encryption keys
199                // in parent nodes and unmerged leaves must be unique. Here, we check that all encryption
200                // keys (all leaf nodes, incl. unmerged and all parent nodes) are unique.
201                //
202                // https://validation.openmls.tech/#valn1410
203                if !encryption_keys.insert(parent_node.encryption_key()) {
204                    return Err(CreationFromExternalError::DuplicateEncryptionKey);
205                }
206
207                parent_node
208                    .unmerged_leaves()
209                    .iter()
210                    .try_for_each(|leaf_index| {
211                        let path = direct_path(*leaf_index, treesync.tree_size());
212
213                        // https://validation.openmls.tech/#valn1408
214                        // Verify that the entry represents a non-blank leaf node that is a descendant of the
215                        // parent node.
216                        let this_parent_offset = path
217                            .iter()
218                            .position(|x| x == &parent_index)
219                            .ok_or(
220                            CreationFromExternalError::<StorageError>::UnmergedLeafNotADescendant,
221                        )?;
222                        let path_leaf_to_this = &path[..this_parent_offset];
223
224
225                        // https://validation.openmls.tech/#valn1409
226                        // Verify that every non-blank intermediate node between the leaf node and the parent
227                        // node also has an entry for the leaf node in its unmerged_leaves.
228                        path_leaf_to_this
229                            .iter()
230                            .try_for_each(|intermediate_index| {
231                                // None would be blank, and we don't care about those
232                                if let Some(intermediate_node) = treesync
233                                    .parent(*intermediate_index) {
234                                    if !intermediate_node.unmerged_leaves().contains(leaf_index) {
235                                        return Err(CreationFromExternalError::<StorageError>::IntermediateNodeMissingUnmergedLeaf);
236                                    }
237                                }
238
239                                Ok(())
240                            })
241                    })
242            })?;
243
244        // https://validation.openmls.tech/#valn1402
245        let group_info: GroupInfo = {
246            let signer_signature_key = treesync
247                .leaf(verifiable_group_info.signer())
248                .ok_or(CreationFromExternalError::UnknownSender)?
249                .signature_key()
250                .clone()
251                .into_signature_public_key_enriched(ciphersuite.signature_algorithm());
252
253            verifiable_group_info
254                .verify(crypto, &signer_signature_key)
255                .map_err(|_| CreationFromExternalError::InvalidGroupInfoSignature)?
256        };
257
258        // https://validation.openmls.tech/#valn1405
259        if treesync.tree_hash() != group_info.group_context().tree_hash() {
260            return Err(CreationFromExternalError::TreeHashMismatch);
261        }
262
263        if group_info.group_context().protocol_version() != ProtocolVersion::Mls10 {
264            return Err(CreationFromExternalError::UnsupportedMlsVersion);
265        }
266
267        let group_context = group_info.group_context().clone();
268
269        let interim_transcript_hash = {
270            let input = InterimTranscriptHashInput::from(group_info.confirmation_tag());
271
272            input.calculate_interim_transcript_hash(
273                crypto,
274                group_context.ciphersuite(),
275                group_context.confirmed_transcript_hash(),
276            )?
277        };
278
279        let public_group = Self {
280            treesync,
281            group_context,
282            interim_transcript_hash,
283            confirmation_tag: group_info.confirmation_tag().clone(),
284            proposal_store,
285        };
286
287        // Fully check that the leaf nodes in the ratchet tree are valid
288        // https://validation.openmls.tech/#valn1407
289        public_group
290            .treesync
291            .full_leaves()
292            .try_for_each(|(_, leaf_node)| {
293                public_group.validate_leaf_node_inner(leaf_node, validate_lifetimes)
294            })?;
295
296        Ok((public_group, group_info))
297    }
298
299    /// Returns the index of the sender of a staged, external commit.
300    pub fn ext_commit_sender_index(
301        &self,
302        commit: &StagedCommit,
303    ) -> Result<LeafNodeIndex, LibraryError> {
304        self.leftmost_free_index(commit.queued_proposals())
305    }
306
307    /// Returns the leftmost free leaf index.
308    ///
309    /// For External Commits of the "resync" type, this returns the index
310    /// of the sender.
311    ///
312    /// The proposals must be validated before calling this function.
313    pub(crate) fn leftmost_free_index<'a>(
314        &self,
315        queued_proposals: impl Iterator<Item = &'a QueuedProposal>,
316    ) -> Result<LeafNodeIndex, LibraryError> {
317        // Leftmost free leaf in the tree
318        let free_leaf_index = self.treesync().free_leaf_index();
319        // Indices that are freed due to queued self-remove proposals or remove
320        // proposals.
321        let removed_indices = queued_proposals.filter_map(|proposal| {
322            match (proposal.proposal(), proposal.sender()) {
323                (Proposal::Remove(r), _) => Some(r.removed),
324                (Proposal::SelfRemove, Sender::Member(sender)) => Some(*sender),
325                _ => None, // SelfRemove proposals must come from group members
326            }
327        });
328        // Find the leftmost free leaf index, which is either the free leaf index
329        // or the leftmost index of a self-remove proposal or remove proposal.
330        removed_indices
331            .into_iter()
332            .chain(std::iter::once(free_leaf_index))
333            .min()
334            .ok_or_else(|| LibraryError::custom("No free leaf index found"))
335    }
336
337    /// Create an empty  [`PublicGroupDiff`] based on this [`PublicGroup`].
338    pub(crate) fn empty_diff(&self) -> PublicGroupDiff<'_> {
339        PublicGroupDiff::new(self)
340    }
341
342    /// Merge the changes performed on the [`PublicGroupDiff`] into this
343    /// [`PublicGroup`].
344    ///
345    /// **NOTE:** The caller must ensure that the group context in the `diff` is
346    ///           updated before calling this function with `update_group_context`.
347    pub(crate) fn merge_diff(&mut self, diff: StagedPublicGroupDiff) {
348        self.treesync.merge_diff(diff.staged_diff);
349        self.group_context = diff.group_context;
350        self.interim_transcript_hash = diff.interim_transcript_hash;
351        self.confirmation_tag = diff.confirmation_tag;
352    }
353
354    /// Derives [`EncryptionKeyPair`]s for the nodes in the shared direct path
355    /// of the leaves with index `leaf_index` and `sender_index`.  This function
356    /// also checks that the derived public keys match the existing public keys.
357    ///
358    /// Returns the [`CommitSecret`] derived from the path secret of the root
359    /// node, as well as the derived [`EncryptionKeyPair`]s. Returns an error if
360    /// the target leaf is outside of the tree.
361    ///
362    /// Returns [`DerivePathError::PublicKeyMismatch`] if the derived keys don't
363    /// match with the existing ones.
364    ///
365    /// Returns [`DerivePathError::LibraryError`] if the sender_index is not
366    /// in the tree.
367    pub(crate) fn derive_path_secrets(
368        &self,
369        crypto: &impl OpenMlsCrypto,
370        ciphersuite: Ciphersuite,
371        path_secret: PathSecret,
372        sender_index: LeafNodeIndex,
373        leaf_index: LeafNodeIndex,
374    ) -> Result<(Vec<EncryptionKeyPair>, CommitSecret), DerivePathError> {
375        self.treesync.derive_path_secrets(
376            crypto,
377            ciphersuite,
378            path_secret,
379            sender_index,
380            leaf_index,
381        )
382    }
383
384    /// Get an iterator over all [`Member`]s of this [`PublicGroup`].
385    pub fn members(&self) -> impl Iterator<Item = Member> + '_ {
386        self.treesync().full_leaf_members()
387    }
388
389    /// Export the nodes of the public tree.
390    pub fn export_ratchet_tree(&self) -> RatchetTree {
391        self.treesync().export_ratchet_tree()
392    }
393
394    /// Add the [`QueuedProposal`] to the [`PublicGroup`]s internal [`ProposalStore`].
395    pub fn add_proposal<Storage: PublicStorageProvider>(
396        &mut self,
397        storage: &Storage,
398        proposal: QueuedProposal,
399    ) -> Result<(), Storage::Error> {
400        storage.queue_proposal(self.group_id(), &proposal.proposal_reference(), &proposal)?;
401        self.proposal_store.add(proposal);
402        Ok(())
403    }
404
405    /// Remove the Proposal with the given [`ProposalRef`] from the [`PublicGroup`]s internal [`ProposalStore`].
406    pub fn remove_proposal<Storage: PublicStorageProvider>(
407        &mut self,
408        storage: &Storage,
409        proposal_ref: &ProposalRef,
410    ) -> Result<(), Storage::Error> {
411        storage.remove_proposal(self.group_id(), proposal_ref)?;
412        self.proposal_store.remove(proposal_ref);
413        Ok(())
414    }
415
416    /// Return all queued proposals
417    pub fn queued_proposals<Storage: PublicStorageProvider>(
418        &self,
419        storage: &Storage,
420    ) -> Result<Vec<(ProposalRef, QueuedProposal)>, Storage::Error> {
421        storage.queued_proposals(self.group_id())
422    }
423}
424
425// Getters
426impl PublicGroup {
427    /// Get the ciphersuite.
428    pub fn ciphersuite(&self) -> Ciphersuite {
429        self.group_context.ciphersuite()
430    }
431
432    /// Get the version.
433    pub fn version(&self) -> ProtocolVersion {
434        self.group_context.protocol_version()
435    }
436
437    /// Get the group id.
438    pub fn group_id(&self) -> &GroupId {
439        self.group_context.group_id()
440    }
441
442    /// Get the group context.
443    pub fn group_context(&self) -> &GroupContext {
444        &self.group_context
445    }
446
447    /// Get the required capabilities.
448    pub fn required_capabilities(&self) -> Option<&RequiredCapabilitiesExtension> {
449        self.group_context.required_capabilities()
450    }
451
452    /// Returns the current tree state of the group, in the form of a [`TreeSync`].
453    pub fn treesync(&self) -> &TreeSync {
454        &self.treesync
455    }
456
457    /// Get confirmation tag.
458    pub fn confirmation_tag(&self) -> &ConfirmationTag {
459        &self.confirmation_tag
460    }
461
462    /// Return a reference to the leaf at the given `LeafNodeIndex` or `None` if the
463    /// leaf is blank.
464    pub fn leaf(&self, leaf_index: LeafNodeIndex) -> Option<&LeafNode> {
465        self.treesync().leaf(leaf_index)
466    }
467
468    /// Returns the tree size
469    pub(crate) fn tree_size(&self) -> TreeSize {
470        self.treesync().tree_size()
471    }
472
473    fn interim_transcript_hash(&self) -> &[u8] {
474        &self.interim_transcript_hash
475    }
476
477    /// Return a vector containing all [`EncryptionKey`]s for which the owner of
478    /// the given `leaf_index` should have private key material.
479    pub(crate) fn owned_encryption_keys(&self, leaf_index: LeafNodeIndex) -> Vec<EncryptionKey> {
480        self.treesync().owned_encryption_keys(leaf_index)
481    }
482
483    /// Stores the [`PublicGroup`] to storage. Called from methods creating a new group and mutating an
484    /// existing group, both inside [`PublicGroup`] and in [`MlsGroup`].
485    ///
486    /// [`MlsGroup`]: crate::group::MlsGroup
487    pub(crate) fn store<Storage: PublicStorageProvider>(
488        &self,
489        storage: &Storage,
490    ) -> Result<(), Storage::Error> {
491        let group_id = self.group_context.group_id();
492        storage.write_tree(group_id, self.treesync())?;
493        storage.write_confirmation_tag(group_id, self.confirmation_tag())?;
494        storage.write_context(group_id, self.group_context())?;
495        storage.write_interim_transcript_hash(
496            group_id,
497            &InterimTranscriptHash(self.interim_transcript_hash.clone()),
498        )?;
499        Ok(())
500    }
501
502    /// Deletes the [`PublicGroup`] from storage.
503    pub fn delete<Storage: PublicStorageProvider>(
504        storage: &Storage,
505        group_id: &GroupId,
506    ) -> Result<(), Storage::Error> {
507        storage.delete_tree(group_id)?;
508        storage.delete_confirmation_tag(group_id)?;
509        storage.delete_context(group_id)?;
510        storage.delete_interim_transcript_hash(group_id)?;
511
512        Ok(())
513    }
514
515    /// Loads the [`PublicGroup`] corresponding to a [`GroupId`] from storage.
516    pub fn load<Storage: PublicStorageProvider>(
517        storage: &Storage,
518        group_id: &GroupId,
519    ) -> Result<Option<Self>, Storage::Error> {
520        let treesync = storage.tree(group_id)?;
521        let proposals: Vec<(ProposalRef, QueuedProposal)> = storage.queued_proposals(group_id)?;
522        let group_context = storage.group_context(group_id)?;
523        let interim_transcript_hash: Option<InterimTranscriptHash> =
524            storage.interim_transcript_hash(group_id)?;
525        let confirmation_tag = storage.confirmation_tag(group_id)?;
526        let mut proposal_store = ProposalStore::new();
527
528        for (_ref, proposal) in proposals {
529            proposal_store.add(proposal);
530        }
531
532        let build = || -> Option<Self> {
533            Some(Self {
534                treesync: treesync?,
535                proposal_store,
536                group_context: group_context?,
537                interim_transcript_hash: interim_transcript_hash?.0,
538                confirmation_tag: confirmation_tag?,
539            })
540        };
541
542        Ok(build())
543    }
544
545    /// Returns a reference to the [`ProposalStore`].
546    pub(crate) fn proposal_store(&self) -> &ProposalStore {
547        &self.proposal_store
548    }
549
550    /// Returns a mutable reference to the [`ProposalStore`].
551    pub(crate) fn proposal_store_mut(&mut self) -> &mut ProposalStore {
552        &mut self.proposal_store
553    }
554}
555
556// Test functions
557#[cfg(any(feature = "test-utils", test))]
558impl PublicGroup {
559    pub(crate) fn context_mut(&mut self) -> &mut GroupContext {
560        &mut self.group_context
561    }
562
563    #[cfg(test)]
564    pub(crate) fn set_group_context(&mut self, group_context: GroupContext) {
565        self.group_context = group_context;
566    }
567
568    #[cfg(test)]
569    pub(crate) fn encrypt_path(
570        &self,
571        provider: &impl crate::storage::OpenMlsProvider,
572        ciphersuite: Ciphersuite,
573        path: &[PlainUpdatePathNode],
574        group_context: &[u8],
575        exclusion_list: &HashSet<&LeafNodeIndex>,
576        own_leaf_index: LeafNodeIndex,
577    ) -> Result<Vec<UpdatePathNode>, LibraryError> {
578        self.treesync().empty_diff().encrypt_path(
579            provider.crypto(),
580            ciphersuite,
581            path,
582            group_context,
583            exclusion_list,
584            own_leaf_index,
585        )
586    }
587}